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

lightningnetwork / lnd / 14061176691

25 Mar 2025 01:43PM UTC coverage: 57.994% (-10.8%) from 68.744%
14061176691

push

github

web-flow
Merge pull request #9544 from lightningnetwork/elle-graphCacheBase

graph: move graph cache out of CRUD layer

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

28443 existing lines in 445 files now uncovered.

96006 of 165546 relevant lines covered (57.99%)

1.22 hits per line

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

64.43
/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 {
2✔
174
        return fmt.Sprintf("already connected to peer: %v", e.peer)
2✔
175
}
2✔
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 {
2✔
420
        graphSub, err := s.graphDB.SubscribeTopology()
2✔
421
        if err != nil {
2✔
422
                return err
×
423
        }
×
424

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

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

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

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

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

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

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

472
                                        s.mu.Lock()
2✔
473

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

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

488
                                        s.mu.Unlock()
2✔
489

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

496
        return nil
2✔
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) {
2✔
510
        var (
2✔
511
                host string
2✔
512
                port int
2✔
513
        )
2✔
514

2✔
515
        // Split the address into its host and port components.
2✔
516
        h, p, err := net.SplitHostPort(address)
2✔
517
        if err != nil {
2✔
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 {
2✔
523
                // Otherwise, we'll note both the host and ports.
2✔
524
                host = h
2✔
525
                portNum, err := strconv.Atoi(p)
2✔
526
                if err != nil {
2✔
527
                        return nil, err
×
528
                }
×
529
                port = portNum
2✔
530
        }
531

532
        if tor.IsOnionHost(host) {
2✔
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))
2✔
541
        return netCfg.ResolveTCPAddr("tcp", hostPort)
2✔
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) {
2✔
548

2✔
549
        return func(a net.Addr) (net.Conn, error) {
4✔
550
                lnAddr := a.(*lnwire.NetAddress)
2✔
551
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
2✔
552
        }
2✔
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) {
2✔
565

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

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

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

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

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

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

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

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

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

2✔
606
        // If the taproot overlay flag is set, but we don't have an aux funding
2✔
607
        // controller, then we'll exit as this is incompatible.
2✔
608
        if cfg.ProtocolOptions.TaprootOverlayChans &&
2✔
609
                implCfg.AuxFundingController.IsNone() {
2✔
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 &&
2✔
620
                cfg.ProtocolOptions.TaprootChans {
2✔
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{
2✔
628
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
2✔
629
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
2✔
630
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
2✔
631
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
2✔
632
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
2✔
633
                NoKeysend:                 !cfg.AcceptKeySend,
2✔
634
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
2✔
635
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
2✔
636
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
2✔
637
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
2✔
638
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
2✔
639
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
2✔
640
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
2✔
641
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
2✔
642
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
2✔
643
                NoRbfCoopClose:            !cfg.ProtocolOptions.RbfCoopClose,
2✔
644
        })
2✔
645
        if err != nil {
2✔
646
                return nil, err
×
647
        }
×
648

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

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

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

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

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

2✔
689
                listenAddrs: listenAddrs,
2✔
690

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

2✔
695
                torController: torController,
2✔
696

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

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

2✔
713
                invoiceHtlcModifier: invoiceHtlcModifier,
2✔
714

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

2✔
717
                tlsManager: tlsManager,
2✔
718

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

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

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

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

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

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

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

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

2✔
760
                return nil
2✔
761
        }
762

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

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

2✔
776
                        peer, err := s.FindPeerByPubStr(string(pubKey))
2✔
777
                        if err != nil {
2✔
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)
2✔
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 {
2✔
805
                return nil, err
×
806
        }
×
807
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
2✔
808
                &htlcswitch.InterceptableSwitchConfig{
2✔
809
                        Switch:             s.htlcSwitch,
2✔
810
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
2✔
811
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
2✔
812
                        RequireInterceptor: s.cfg.RequireInterceptor,
2✔
813
                        Notifier:           s.cc.ChainNotifier,
2✔
814
                },
2✔
815
        )
2✔
816
        if err != nil {
2✔
817
                return nil, err
×
818
        }
×
819

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

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

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

2✔
844
        // If enabled, use either UPnP or NAT-PMP to automatically configure
2✔
845
        // port forwarding for users behind a NAT.
2✔
846
        if cfg.NAT {
2✔
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))
2✔
884
        for idx, ip := range cfg.ExternalIPs {
4✔
885
                externalIPStrings[idx] = ip.String()
2✔
886
        }
2✔
887
        if s.natTraversal != nil {
2✔
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(
2✔
915
                externalIPStrings, strconv.Itoa(defaultPeerPort),
2✔
916
                cfg.net.ResolveTCPAddr,
2✔
917
        )
2✔
918
        if err != nil {
2✔
919
                return nil, err
×
920
        }
×
921

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

2✔
925
        // We'll now reconstruct a node announcement based on our current
2✔
926
        // configuration so we can send it out as a sort of heart beat within
2✔
927
        // the network.
2✔
928
        //
2✔
929
        // We'll start by parsing the node color from configuration.
2✔
930
        color, err := lncfg.ParseHexColor(cfg.Color)
2✔
931
        if err != nil {
2✔
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
2✔
939
        if alias == "" {
4✔
940
                alias = hex.EncodeToString(serializedPubKey[:10])
2✔
941
        }
2✔
942
        nodeAlias, err := lnwire.NewNodeAlias(alias)
2✔
943
        if err != nil {
2✔
944
                return nil, err
×
945
        }
×
946
        selfNode := &models.LightningNode{
2✔
947
                HaveNodeAnnouncement: true,
2✔
948
                LastUpdate:           time.Now(),
2✔
949
                Addresses:            selfAddrs,
2✔
950
                Alias:                nodeAlias.String(),
2✔
951
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
2✔
952
                Color:                color,
2✔
953
        }
2✔
954
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
2✔
955

2✔
956
        // Based on the disk representation of the node announcement generated
2✔
957
        // above, we'll generate a node announcement that can go out on the
2✔
958
        // network so we can properly sign it.
2✔
959
        nodeAnn, err := selfNode.NodeAnnouncement(false)
2✔
960
        if err != nil {
2✔
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(
2✔
967
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
2✔
968
        )
2✔
969
        if err != nil {
2✔
970
                return nil, fmt.Errorf("unable to generate signature for "+
×
971
                        "self node announcement: %v", err)
×
972
        }
×
973
        selfNode.AuthSigBytes = authSig.Serialize()
2✔
974
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
2✔
975
                selfNode.AuthSigBytes,
2✔
976
        )
2✔
977
        if err != nil {
2✔
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 {
2✔
984
                return nil, fmt.Errorf("can't set self node: %w", err)
×
985
        }
×
986
        s.currentNodeAnn = nodeAnn
2✔
987

2✔
988
        // The router will get access to the payment ID sequencer, such that it
2✔
989
        // can generate unique payment IDs.
2✔
990
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
2✔
991
        if err != nil {
2✔
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)
2✔
1000

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

2✔
1016
                        estimator, err = routing.NewAprioriEstimator(
2✔
1017
                                aprioriConfig,
2✔
1018
                        )
2✔
1019
                        if err != nil {
2✔
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{
2✔
1047
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
2✔
1048
                Estimator:               estimator,
2✔
1049
                MaxMcHistory:            routingConfig.MaxMcHistory,
2✔
1050
                McFlushInterval:         routingConfig.McFlushInterval,
2✔
1051
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
2✔
1052
        }
2✔
1053

2✔
1054
        s.missionController, err = routing.NewMissionController(
2✔
1055
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
2✔
1056
        )
2✔
1057
        if err != nil {
2✔
1058
                return nil, fmt.Errorf("can't create mission control "+
×
1059
                        "manager: %w", err)
×
1060
        }
×
1061
        s.defaultMC, err = s.missionController.GetNamespacedStore(
2✔
1062
                routing.DefaultMissionControlNamespace,
2✔
1063
        )
2✔
1064
        if err != nil {
2✔
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: "+
2✔
1070
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
2✔
1071
                int64(routingConfig.AttemptCost),
2✔
1072
                float64(routingConfig.AttemptCostPPM)/10000,
2✔
1073
                routingConfig.MinRouteProbability)
2✔
1074

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

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

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

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

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

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

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

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

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

2✔
1151
        s.authGossiper = discovery.New(discovery.Config{
2✔
1152
                Graph:                 s.graphBuilder,
2✔
1153
                ChainIO:               s.cc.ChainIO,
2✔
1154
                Notifier:              s.cc.ChainNotifier,
2✔
1155
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
2✔
1156
                Broadcast:             s.BroadcastMessage,
2✔
1157
                ChanSeries:            chanSeries,
2✔
1158
                NotifyWhenOnline:      s.NotifyWhenOnline,
2✔
1159
                NotifyWhenOffline:     s.NotifyWhenOffline,
2✔
1160
                FetchSelfAnnouncement: s.getNodeAnnouncement,
2✔
1161
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
2✔
1162
                        error) {
2✔
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
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1192
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1193
        }, nodeKeyDesc)
1194

1195
        accessCfg := &accessManConfig{
2✔
1196
                initAccessPerms: func() (map[string]channeldb.ChanCount,
2✔
1197
                        error) {
4✔
1198

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

1208
        peerAccessMan, err := newAccessMan(accessCfg)
2✔
1209
        if err != nil {
2✔
1210
                return nil, err
×
1211
        }
×
1212

1213
        s.peerAccessMan = peerAccessMan
2✔
1214

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

2✔
1223
                        return s.graphDB.ForEachNodeChannel(selfVertex,
2✔
1224
                                func(_ kvdb.RTx, c *models.ChannelEdgeInfo,
2✔
1225
                                        e *models.ChannelEdgePolicy,
2✔
1226
                                        _ *models.ChannelEdgePolicy) error {
4✔
1227

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

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

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

1258
        aggregator := sweep.NewBudgetAggregator(
2✔
1259
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
2✔
1260
                s.implCfg.AuxSweeper,
2✔
1261
        )
2✔
1262

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

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

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

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

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

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

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

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

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

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

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

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

1403
                        event := &contractcourt.ContractBreachEvent{
2✔
1404
                                ChanPoint:         chanPoint,
2✔
1405
                                ProcessACK:        processACK,
2✔
1406
                                BreachRetribution: breachRet,
2✔
1407
                        }
2✔
1408

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

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

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

2✔
1446
                        // Get the circuit map.
2✔
1447
                        circuits := s.htlcSwitch.CircuitLookup()
2✔
1448

2✔
1449
                        // Lookup the outgoing circuit.
2✔
1450
                        pc := circuits.LookupOpenCircuit(circuit)
2✔
1451
                        if pc == nil {
4✔
1452
                                return nil
2✔
1453
                        }
2✔
1454

1455
                        return &pc.Incoming
2✔
1456
                },
1457
                AuxLeafStore: implCfg.AuxLeafStore,
1458
                AuxSigner:    implCfg.AuxSigner,
1459
                AuxResolver:  implCfg.AuxContractResolver,
1460
        }, dbs.ChanStateDB)
1461

1462
        // Select the configuration and funding parameters for Bitcoin.
1463
        chainCfg := cfg.Bitcoin
2✔
1464
        minRemoteDelay := funding.MinBtcRemoteDelay
2✔
1465
        maxRemoteDelay := funding.MaxBtcRemoteDelay
2✔
1466

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

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

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

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

2✔
1494
                var ourPolicy *models.ChannelEdgePolicy
2✔
1495
                if info != nil && info.NodeKey1Bytes == ourKey {
4✔
1496
                        ourPolicy = e1
2✔
1497
                } else {
4✔
1498
                        ourPolicy = e2
2✔
1499
                }
2✔
1500

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

1506
                err = s.graphDB.DeleteChannelEdges(
2✔
1507
                        false, false, scid.ToUint64(),
2✔
1508
                )
2✔
1509
                return ourPolicy, err
2✔
1510
        }
1511

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

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

2✔
1528
                reservationTimeout = cfg.Dev.GetReservationTimeout()
2✔
1529
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
2✔
1530

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

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

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

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

1582
                        minConf := uint64(3)
×
1583
                        maxConf := uint64(6)
×
1584

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

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

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

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

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

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

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

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

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

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

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

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

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

1759
        if cfg.WtClient.Active {
4✔
1760
                policy := wtpolicy.DefaultPolicy()
2✔
1761
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
2✔
1762

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

2✔
1769
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
2✔
1770

2✔
1771
                if err := policy.Validate(); err != nil {
2✔
1772
                        return nil, err
×
1773
                }
×
1774

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

2✔
1781
                        return brontide.Dial(
2✔
1782
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
2✔
1783
                        )
2✔
1784
                }
2✔
1785

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

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

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

1809
                        return br, channel.ChanType, nil
2✔
1810
                }
1811

1812
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
2✔
1813

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

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

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

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

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

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

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

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

1889
        // Create liveness monitor.
1890
        s.createLivenessMonitor(cfg, cc, leaderElector)
2✔
1891

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

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

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

2✔
1927
        // Finally, register the subsystems in blockbeat.
2✔
1928
        s.registerBlockConsumers()
2✔
1929

2✔
1930
        return s, nil
2✔
1931
}
1932

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

2✔
1938
        switch c := cfg.Estimator.Config().(type) {
2✔
1939
        case routing.AprioriConfig:
2✔
1940
                routerCfg.ProbabilityEstimatorType =
2✔
1941
                        routing.AprioriEstimatorName
2✔
1942

2✔
1943
                targetCfg := routerCfg.AprioriConfig
2✔
1944
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
2✔
1945
                targetCfg.Weight = c.AprioriWeight
2✔
1946
                targetCfg.CapacityFraction = c.CapacityFraction
2✔
1947
                targetCfg.HopProbability = c.AprioriHopProbability
2✔
1948

1949
        case routing.BimodalConfig:
2✔
1950
                routerCfg.ProbabilityEstimatorType =
2✔
1951
                        routing.BimodalEstimatorName
2✔
1952

2✔
1953
                targetCfg := routerCfg.BimodalConfig
2✔
1954
                targetCfg.Scale = int64(c.BimodalScaleMsat)
2✔
1955
                targetCfg.NodeWeight = c.BimodalNodeWeight
2✔
1956
                targetCfg.DecayTime = c.BimodalDecayTime
2✔
1957
        }
1958

1959
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
2✔
1960
}
1961

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

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

2✔
1987
        data, err := u.DataToSign()
2✔
1988
        if err != nil {
2✔
1989
                return nil, err
×
1990
        }
×
1991

1992
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
2✔
1993
}
1994

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

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

×
2013
                chainBackendAttempts = 0
×
2014
        }
×
2015

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

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

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

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

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

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

2075
        checks := []*healthcheck.Observation{
2✔
2076
                chainHealthCheck, diskCheck, tlsHealthCheck,
2✔
2077
        }
2✔
2078

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

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

2✔
2105
                remoteSignerConnectionCheck := healthcheck.NewObservation(
2✔
2106
                        "remote signer connection",
2✔
2107
                        rpcwallet.HealthCheck(
2✔
2108
                                s.cfg.RemoteSigner,
2✔
2109

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

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

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

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

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

2163
                checks = append(checks, leaderCheck)
×
2164
        }
2165

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

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

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

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

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

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

2✔
2212
        cleanup := cleaner{}
2✔
2213

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

2219
        if startErr != nil {
2✔
2220
                cleanup.run()
×
2221
        }
×
2222

2223
        return startErr
2✔
2224
}
2225

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

2238
        var startErr error
2✔
2239

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

2✔
2245
        s.start.Do(func() {
4✔
2246
                cleanup = cleanup.add(s.customMessageServer.Stop)
2✔
2247
                if err := s.customMessageServer.Start(); err != nil {
2✔
2248
                        startErr = err
×
2249
                        return
×
2250
                }
×
2251

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

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

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

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

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

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

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

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

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

2317
                if s.towerClientMgr != nil {
4✔
2318
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
2✔
2319
                        if err := s.towerClientMgr.Start(); err != nil {
2✔
2320
                                startErr = err
×
2321
                                return
×
2322
                        }
×
2323
                }
2324

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2431
                cleanup.add(func() error {
2✔
2432
                        s.missionController.StopStoreTickers()
×
2433
                        return nil
×
2434
                })
×
2435
                s.missionController.RunStoreTickers()
2✔
2436

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

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

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

2486
                if s.natTraversal != nil {
2✔
2487
                        s.wg.Add(1)
×
2488
                        go s.watchExternalIP()
×
2489
                }
×
2490

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

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

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

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

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

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

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

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

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

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

2585
                                copy(result[idx][:], servers)
×
2586
                        }
2587

2588
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2589
                }
2590

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

2618
                // If network bootstrapping hasn't been disabled, then we'll
2619
                // configure the set of active bootstrappers, and launch a
2620
                // dedicated goroutine to maintain a set of persistent
2621
                // connections.
2622
                if shouldPeerBootstrap(s.cfg) {
2✔
2623
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2624
                        if err != nil {
×
2625
                                startErr = err
×
2626
                                return
×
2627
                        }
×
2628

2629
                        s.wg.Add(1)
×
2630
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2631
                } else {
2✔
2632
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
2✔
2633
                }
2✔
2634

2635
                // Start the blockbeat after all other subsystems have been
2636
                // started so they are ready to receive new blocks.
2637
                cleanup = cleanup.add(func() error {
2✔
2638
                        s.blockbeatDispatcher.Stop()
×
2639
                        return nil
×
2640
                })
×
2641
                if err := s.blockbeatDispatcher.Start(); err != nil {
2✔
2642
                        startErr = err
×
2643
                        return
×
2644
                }
×
2645

2646
                // Set the active flag now that we've completed the full
2647
                // startup.
2648
                atomic.StoreInt32(&s.active, 1)
2✔
2649
        })
2650

2651
        if startErr != nil {
2✔
2652
                cleanup.run()
×
2653
        }
×
2654
        return startErr
2✔
2655
}
2656

2657
// Stop gracefully shutsdown the main daemon server. This function will signal
2658
// any active goroutines, or helper objects to exit, then blocks until they've
2659
// all successfully exited. Additionally, any/all listeners are closed.
2660
// NOTE: This function is safe for concurrent access.
2661
func (s *server) Stop() error {
2✔
2662
        s.stop.Do(func() {
4✔
2663
                atomic.StoreInt32(&s.stopping, 1)
2✔
2664

2✔
2665
                close(s.quit)
2✔
2666

2✔
2667
                // Shutdown connMgr first to prevent conns during shutdown.
2✔
2668
                s.connMgr.Stop()
2✔
2669

2✔
2670
                // Stop dispatching blocks to other systems immediately.
2✔
2671
                s.blockbeatDispatcher.Stop()
2✔
2672

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

2735
                // Update channel.backup file. Make sure to do it before
2736
                // stopping chanSubSwapper.
2737
                singles, err := chanbackup.FetchStaticChanBackups(
2✔
2738
                        s.chanStateDB, s.addrSource,
2✔
2739
                )
2✔
2740
                if err != nil {
2✔
2741
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2742
                                err)
×
2743
                } else {
2✔
2744
                        err := s.chanSubSwapper.ManualUpdate(singles)
2✔
2745
                        if err != nil {
4✔
2746
                                srvrLog.Warnf("Manual update of channel "+
2✔
2747
                                        "backup failed: %v", err)
2✔
2748
                        }
2✔
2749
                }
2750

2751
                if err := s.chanSubSwapper.Stop(); err != nil {
2✔
2752
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2753
                }
×
2754
                if err := s.cc.ChainNotifier.Stop(); err != nil {
2✔
2755
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2756
                }
×
2757
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
2✔
2758
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2759
                                err)
×
2760
                }
×
2761
                if err := s.chanEventStore.Stop(); err != nil {
2✔
2762
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2763
                                err)
×
2764
                }
×
2765
                s.missionController.StopStoreTickers()
2✔
2766

2✔
2767
                // Disconnect from each active peers to ensure that
2✔
2768
                // peerTerminationWatchers signal completion to each peer.
2✔
2769
                for _, peer := range s.Peers() {
4✔
2770
                        err := s.DisconnectPeer(peer.IdentityKey())
2✔
2771
                        if err != nil {
2✔
2772
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2773
                                        "received error: %v", peer.IdentityKey(),
×
2774
                                        err,
×
2775
                                )
×
2776
                        }
×
2777
                }
2778

2779
                // Now that all connections have been torn down, stop the tower
2780
                // client which will reliably flush all queued states to the
2781
                // tower. If this is halted for any reason, the force quit timer
2782
                // will kick in and abort to allow this method to return.
2783
                if s.towerClientMgr != nil {
4✔
2784
                        if err := s.towerClientMgr.Stop(); err != nil {
2✔
2785
                                srvrLog.Warnf("Unable to shut down tower "+
×
2786
                                        "client manager: %v", err)
×
2787
                        }
×
2788
                }
2789

2790
                if s.hostAnn != nil {
2✔
2791
                        if err := s.hostAnn.Stop(); err != nil {
×
2792
                                srvrLog.Warnf("unable to shut down host "+
×
2793
                                        "annoucner: %v", err)
×
2794
                        }
×
2795
                }
2796

2797
                if s.livenessMonitor != nil {
4✔
2798
                        if err := s.livenessMonitor.Stop(); err != nil {
2✔
2799
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2800
                                        "monitor: %v", err)
×
2801
                        }
×
2802
                }
2803

2804
                // Wait for all lingering goroutines to quit.
2805
                srvrLog.Debug("Waiting for server to shutdown...")
2✔
2806
                s.wg.Wait()
2✔
2807

2✔
2808
                srvrLog.Debug("Stopping buffer pools...")
2✔
2809
                s.sigPool.Stop()
2✔
2810
                s.writePool.Stop()
2✔
2811
                s.readPool.Stop()
2✔
2812
        })
2813

2814
        return nil
2✔
2815
}
2816

2817
// Stopped returns true if the server has been instructed to shutdown.
2818
// NOTE: This function is safe for concurrent access.
2819
func (s *server) Stopped() bool {
2✔
2820
        return atomic.LoadInt32(&s.stopping) != 0
2✔
2821
}
2✔
2822

2823
// configurePortForwarding attempts to set up port forwarding for the different
2824
// ports that the server will be listening on.
2825
//
2826
// NOTE: This should only be used when using some kind of NAT traversal to
2827
// automatically set up forwarding rules.
2828
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2829
        ip, err := s.natTraversal.ExternalIP()
×
2830
        if err != nil {
×
2831
                return nil, err
×
2832
        }
×
2833
        s.lastDetectedIP = ip
×
2834

×
2835
        externalIPs := make([]string, 0, len(ports))
×
2836
        for _, port := range ports {
×
2837
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2838
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2839
                        continue
×
2840
                }
2841

2842
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2843
                externalIPs = append(externalIPs, hostIP)
×
2844
        }
2845

2846
        return externalIPs, nil
×
2847
}
2848

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

2864
// watchExternalIP continuously checks for an updated external IP address every
2865
// 15 minutes. Once a new IP address has been detected, it will automatically
2866
// handle port forwarding rules and send updated node announcements to the
2867
// currently connected peers.
2868
//
2869
// NOTE: This MUST be run as a goroutine.
2870
func (s *server) watchExternalIP() {
×
2871
        defer s.wg.Done()
×
2872

×
2873
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2874
        // up by the server.
×
2875
        defer s.removePortForwarding()
×
2876

×
2877
        // Keep track of the external IPs set by the user to avoid replacing
×
2878
        // them when detecting a new IP.
×
2879
        ipsSetByUser := make(map[string]struct{})
×
2880
        for _, ip := range s.cfg.ExternalIPs {
×
2881
                ipsSetByUser[ip.String()] = struct{}{}
×
2882
        }
×
2883

2884
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2885

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

2901
                        // Periodically renew the NAT port forwarding.
2902
                        for _, port := range forwardedPorts {
×
2903
                                err := s.natTraversal.AddPortMapping(port)
×
2904
                                if err != nil {
×
2905
                                        srvrLog.Warnf("Unable to automatically "+
×
2906
                                                "re-create port forwarding using %s: %v",
×
2907
                                                s.natTraversal.Name(), err)
×
2908
                                } else {
×
2909
                                        srvrLog.Debugf("Automatically re-created "+
×
2910
                                                "forwarding for port %d using %s to "+
×
2911
                                                "advertise external IP",
×
2912
                                                port, s.natTraversal.Name())
×
2913
                                }
×
2914
                        }
2915

2916
                        if ip.Equal(s.lastDetectedIP) {
×
2917
                                continue
×
2918
                        }
2919

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

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

2937
                                newAddrs = append(newAddrs, addr)
×
2938
                        }
2939

2940
                        // Skip the update if we weren't able to resolve any of
2941
                        // the new addresses.
2942
                        if len(newAddrs) == 0 {
×
2943
                                srvrLog.Debug("Skipping node announcement " +
×
2944
                                        "update due to not being able to " +
×
2945
                                        "resolve any new addresses")
×
2946
                                continue
×
2947
                        }
2948

2949
                        // Now, we'll need to update the addresses in our node's
2950
                        // announcement in order to propagate the update
2951
                        // throughout the network. We'll only include addresses
2952
                        // that have a different IP from the previous one, as
2953
                        // the previous IP is no longer valid.
2954
                        currentNodeAnn := s.getNodeAnnouncement()
×
2955

×
2956
                        for _, addr := range currentNodeAnn.Addresses {
×
2957
                                host, _, err := net.SplitHostPort(addr.String())
×
2958
                                if err != nil {
×
2959
                                        srvrLog.Debugf("Unable to determine "+
×
2960
                                                "host from address %v: %v",
×
2961
                                                addr, err)
×
2962
                                        continue
×
2963
                                }
2964

2965
                                // We'll also make sure to include external IPs
2966
                                // set manually by the user.
2967
                                _, setByUser := ipsSetByUser[addr.String()]
×
2968
                                if setByUser || host != s.lastDetectedIP.String() {
×
2969
                                        newAddrs = append(newAddrs, addr)
×
2970
                                }
×
2971
                        }
2972

2973
                        // Then, we'll generate a new timestamped node
2974
                        // announcement with the updated addresses and broadcast
2975
                        // it to our peers.
2976
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2977
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2978
                        )
×
2979
                        if err != nil {
×
2980
                                srvrLog.Debugf("Unable to generate new node "+
×
2981
                                        "announcement: %v", err)
×
2982
                                continue
×
2983
                        }
2984

2985
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2986
                        if err != nil {
×
2987
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2988
                                        "announcement to peers: %v", err)
×
2989
                                continue
×
2990
                        }
2991

2992
                        // Finally, update the last IP seen to the current one.
2993
                        s.lastDetectedIP = ip
×
2994
                case <-s.quit:
×
2995
                        break out
×
2996
                }
2997
        }
2998
}
2999

3000
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3001
// based on the server, and currently active bootstrap mechanisms as defined
3002
// within the current configuration.
3003
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
3004
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
3005

×
3006
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
3007

×
3008
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
3009
        // this can be used by default if we've already partially seeded the
×
3010
        // network.
×
3011
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
3012
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
3013
        if err != nil {
×
3014
                return nil, err
×
3015
        }
×
3016
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
3017

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

×
3023
                // If we have a set of DNS seeds for this chain, then we'll add
×
3024
                // it as an additional bootstrapping source.
×
3025
                if ok {
×
3026
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3027
                                "seeds: %v", dnsSeeds)
×
3028

×
3029
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3030
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3031
                        )
×
3032
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3033
                }
×
3034
        }
3035

3036
        return bootStrappers, nil
×
3037
}
3038

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

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

×
3051
        // We should ignore ourselves from bootstrapping.
×
3052
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
3053
        ignore[selfKey] = struct{}{}
×
3054

×
3055
        // Ignore all connected peers.
×
3056
        for _, peer := range s.peersByPub {
×
3057
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3058
                ignore[nID] = struct{}{}
×
3059
        }
×
3060

3061
        // Ignore all persistent peers as they have a dedicated reconnecting
3062
        // process.
3063
        for pubKeyStr := range s.persistentPeers {
×
3064
                var nID autopilot.NodeID
×
3065
                copy(nID[:], []byte(pubKeyStr))
×
3066
                ignore[nID] = struct{}{}
×
3067
        }
×
3068

3069
        return ignore
×
3070
}
3071

3072
// peerBootstrapper is a goroutine which is tasked with attempting to establish
3073
// and maintain a target minimum number of outbound connections. With this
3074
// invariant, we ensure that our node is connected to a diverse set of peers
3075
// and that nodes newly joining the network receive an up to date network view
3076
// as soon as possible.
3077
func (s *server) peerBootstrapper(numTargetPeers uint32,
3078
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3079

×
3080
        defer s.wg.Done()
×
3081

×
3082
        // Before we continue, init the ignore peers map.
×
3083
        ignoreList := s.createBootstrapIgnorePeers()
×
3084

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

×
3089
        // Once done, we'll attempt to maintain our target minimum number of
×
3090
        // peers.
×
3091
        //
×
3092
        // We'll use a 15 second backoff, and double the time every time an
×
3093
        // epoch fails up to a ceiling.
×
3094
        backOff := time.Second * 15
×
3095

×
3096
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
3097
        // see if we've reached our minimum number of peers.
×
3098
        sampleTicker := time.NewTicker(backOff)
×
3099
        defer sampleTicker.Stop()
×
3100

×
3101
        // We'll use the number of attempts and errors to determine if we need
×
3102
        // to increase the time between discovery epochs.
×
3103
        var epochErrors uint32 // To be used atomically.
×
3104
        var epochAttempts uint32
×
3105

×
3106
        for {
×
3107
                select {
×
3108
                // The ticker has just woken us up, so we'll need to check if
3109
                // we need to attempt to connect our to any more peers.
3110
                case <-sampleTicker.C:
×
3111
                        // Obtain the current number of peers, so we can gauge
×
3112
                        // if we need to sample more peers or not.
×
3113
                        s.mu.RLock()
×
3114
                        numActivePeers := uint32(len(s.peersByPub))
×
3115
                        s.mu.RUnlock()
×
3116

×
3117
                        // If we have enough peers, then we can loop back
×
3118
                        // around to the next round as we're done here.
×
3119
                        if numActivePeers >= numTargetPeers {
×
3120
                                continue
×
3121
                        }
3122

3123
                        // If all of our attempts failed during this last back
3124
                        // off period, then will increase our backoff to 5
3125
                        // minute ceiling to avoid an excessive number of
3126
                        // queries
3127
                        //
3128
                        // TODO(roasbeef): add reverse policy too?
3129

3130
                        if epochAttempts > 0 &&
×
3131
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3132

×
3133
                                sampleTicker.Stop()
×
3134

×
3135
                                backOff *= 2
×
3136
                                if backOff > bootstrapBackOffCeiling {
×
3137
                                        backOff = bootstrapBackOffCeiling
×
3138
                                }
×
3139

3140
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3141
                                        "%v", backOff)
×
3142
                                sampleTicker = time.NewTicker(backOff)
×
3143
                                continue
×
3144
                        }
3145

3146
                        atomic.StoreUint32(&epochErrors, 0)
×
3147
                        epochAttempts = 0
×
3148

×
3149
                        // Since we know need more peers, we'll compute the
×
3150
                        // exact number we need to reach our threshold.
×
3151
                        numNeeded := numTargetPeers - numActivePeers
×
3152

×
3153
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3154
                                "peers", numNeeded)
×
3155

×
3156
                        // With the number of peers we need calculated, we'll
×
3157
                        // query the network bootstrappers to sample a set of
×
3158
                        // random addrs for us.
×
3159
                        //
×
3160
                        // Before we continue, get a copy of the ignore peers
×
3161
                        // map.
×
3162
                        ignoreList = s.createBootstrapIgnorePeers()
×
3163

×
3164
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3165
                                ignoreList, numNeeded*2, bootstrappers...,
×
3166
                        )
×
3167
                        if err != nil {
×
3168
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3169
                                        "peers: %v", err)
×
3170
                                continue
×
3171
                        }
3172

3173
                        // Finally, we'll launch a new goroutine for each
3174
                        // prospective peer candidates.
3175
                        for _, addr := range peerAddrs {
×
3176
                                epochAttempts++
×
3177

×
3178
                                go func(a *lnwire.NetAddress) {
×
3179
                                        // TODO(roasbeef): can do AS, subnet,
×
3180
                                        // country diversity, etc
×
3181
                                        errChan := make(chan error, 1)
×
3182
                                        s.connectToPeer(
×
3183
                                                a, errChan,
×
3184
                                                s.cfg.ConnectionTimeout,
×
3185
                                        )
×
3186
                                        select {
×
3187
                                        case err := <-errChan:
×
3188
                                                if err == nil {
×
3189
                                                        return
×
3190
                                                }
×
3191

3192
                                                srvrLog.Errorf("Unable to "+
×
3193
                                                        "connect to %v: %v",
×
3194
                                                        a, err)
×
3195
                                                atomic.AddUint32(&epochErrors, 1)
×
3196
                                        case <-s.quit:
×
3197
                                        }
3198
                                }(addr)
3199
                        }
3200
                case <-s.quit:
×
3201
                        return
×
3202
                }
3203
        }
3204
}
3205

3206
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3207
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3208
// query back off each time we encounter a failure.
3209
const bootstrapBackOffCeiling = time.Minute * 5
3210

3211
// initialPeerBootstrap attempts to continuously connect to peers on startup
3212
// until the target number of peers has been reached. This ensures that nodes
3213
// receive an up to date network view as soon as possible.
3214
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
3215
        numTargetPeers uint32,
3216
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3217

×
3218
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3219
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3220

×
3221
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3222
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3223
        var delaySignal <-chan time.Time
×
3224
        delayTime := time.Second * 2
×
3225

×
3226
        // As want to be more aggressive, we'll use a lower back off celling
×
3227
        // then the main peer bootstrap logic.
×
3228
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3229

×
3230
        for attempts := 0; ; attempts++ {
×
3231
                // Check if the server has been requested to shut down in order
×
3232
                // to prevent blocking.
×
3233
                if s.Stopped() {
×
3234
                        return
×
3235
                }
×
3236

3237
                // We can exit our aggressive initial peer bootstrapping stage
3238
                // if we've reached out target number of peers.
3239
                s.mu.RLock()
×
3240
                numActivePeers := uint32(len(s.peersByPub))
×
3241
                s.mu.RUnlock()
×
3242

×
3243
                if numActivePeers >= numTargetPeers {
×
3244
                        return
×
3245
                }
×
3246

3247
                if attempts > 0 {
×
3248
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3249
                                "bootstrap peers (attempt #%v)", delayTime,
×
3250
                                attempts)
×
3251

×
3252
                        // We've completed at least one iterating and haven't
×
3253
                        // finished, so we'll start to insert a delay period
×
3254
                        // between each attempt.
×
3255
                        delaySignal = time.After(delayTime)
×
3256
                        select {
×
3257
                        case <-delaySignal:
×
3258
                        case <-s.quit:
×
3259
                                return
×
3260
                        }
3261

3262
                        // After our delay, we'll double the time we wait up to
3263
                        // the max back off period.
3264
                        delayTime *= 2
×
3265
                        if delayTime > backOffCeiling {
×
3266
                                delayTime = backOffCeiling
×
3267
                        }
×
3268
                }
3269

3270
                // Otherwise, we'll request for the remaining number of peers
3271
                // in order to reach our target.
3272
                peersNeeded := numTargetPeers - numActivePeers
×
3273
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3274
                        ignore, peersNeeded, bootstrappers...,
×
3275
                )
×
3276
                if err != nil {
×
3277
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3278
                                "peers: %v", err)
×
3279
                        continue
×
3280
                }
3281

3282
                // Then, we'll attempt to establish a connection to the
3283
                // different peer addresses retrieved by our bootstrappers.
3284
                var wg sync.WaitGroup
×
3285
                for _, bootstrapAddr := range bootstrapAddrs {
×
3286
                        wg.Add(1)
×
3287
                        go func(addr *lnwire.NetAddress) {
×
3288
                                defer wg.Done()
×
3289

×
3290
                                errChan := make(chan error, 1)
×
3291
                                go s.connectToPeer(
×
3292
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3293
                                )
×
3294

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

3318
                wg.Wait()
×
3319
        }
3320
}
3321

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

3334
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3335
        if err != nil {
×
3336
                return err
×
3337
        }
×
3338

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

×
3351
        switch {
×
3352
        case s.cfg.Tor.V2:
×
3353
                onionCfg.Type = tor.V2
×
3354
        case s.cfg.Tor.V3:
×
3355
                onionCfg.Type = tor.V3
×
3356
        }
3357

3358
        addr, err := s.torController.AddOnion(onionCfg)
×
3359
        if err != nil {
×
3360
                return err
×
3361
        }
×
3362

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

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

3393
        return nil
×
3394
}
3395

3396
// findChannel finds a channel given a public key and ChannelID. It is an
3397
// optimization that is quicker than seeking for a channel given only the
3398
// ChannelID.
3399
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3400
        *channeldb.OpenChannel, error) {
2✔
3401

2✔
3402
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
2✔
3403
        if err != nil {
2✔
3404
                return nil, err
×
3405
        }
×
3406

3407
        for _, channel := range nodeChans {
4✔
3408
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
4✔
3409
                        return channel, nil
2✔
3410
                }
2✔
3411
        }
3412

3413
        return nil, fmt.Errorf("unable to find channel")
2✔
3414
}
3415

3416
// getNodeAnnouncement fetches the current, fully signed node announcement.
3417
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
2✔
3418
        s.mu.Lock()
2✔
3419
        defer s.mu.Unlock()
2✔
3420

2✔
3421
        return *s.currentNodeAnn
2✔
3422
}
2✔
3423

3424
// genNodeAnnouncement generates and returns the current fully signed node
3425
// announcement. The time stamp of the announcement will be updated in order
3426
// to ensure it propagates through the network.
3427
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3428
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
2✔
3429

2✔
3430
        s.mu.Lock()
2✔
3431
        defer s.mu.Unlock()
2✔
3432

2✔
3433
        // First, try to update our feature manager with the updated set of
2✔
3434
        // features.
2✔
3435
        if features != nil {
4✔
3436
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
2✔
3437
                        feature.SetNodeAnn: features,
2✔
3438
                }
2✔
3439
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
2✔
3440
                if err != nil {
4✔
3441
                        return lnwire.NodeAnnouncement{}, err
2✔
3442
                }
2✔
3443

3444
                // If we could successfully update our feature manager, add
3445
                // an update modifier to include these new features to our
3446
                // set.
3447
                modifiers = append(
2✔
3448
                        modifiers, netann.NodeAnnSetFeatures(features),
2✔
3449
                )
2✔
3450
        }
3451

3452
        // Always update the timestamp when refreshing to ensure the update
3453
        // propagates.
3454
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
2✔
3455

2✔
3456
        // Apply the requested changes to the node announcement.
2✔
3457
        for _, modifier := range modifiers {
4✔
3458
                modifier(s.currentNodeAnn)
2✔
3459
        }
2✔
3460

3461
        // Sign a new update after applying all of the passed modifiers.
3462
        err := netann.SignNodeAnnouncement(
2✔
3463
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
2✔
3464
        )
2✔
3465
        if err != nil {
2✔
3466
                return lnwire.NodeAnnouncement{}, err
×
3467
        }
×
3468

3469
        return *s.currentNodeAnn, nil
2✔
3470
}
3471

3472
// updateAndBroadcastSelfNode generates a new node announcement
3473
// applying the giving modifiers and updating the time stamp
3474
// to ensure it propagates through the network. Then it broadcasts
3475
// it to the network.
3476
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
3477
        modifiers ...netann.NodeAnnModifier) error {
2✔
3478

2✔
3479
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
2✔
3480
        if err != nil {
4✔
3481
                return fmt.Errorf("unable to generate new node "+
2✔
3482
                        "announcement: %v", err)
2✔
3483
        }
2✔
3484

3485
        // Update the on-disk version of our announcement.
3486
        // Load and modify self node istead of creating anew instance so we
3487
        // don't risk overwriting any existing values.
3488
        selfNode, err := s.graphDB.SourceNode()
2✔
3489
        if err != nil {
2✔
3490
                return fmt.Errorf("unable to get current source node: %w", err)
×
3491
        }
×
3492

3493
        selfNode.HaveNodeAnnouncement = true
2✔
3494
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
2✔
3495
        selfNode.Addresses = newNodeAnn.Addresses
2✔
3496
        selfNode.Alias = newNodeAnn.Alias.String()
2✔
3497
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
2✔
3498
        selfNode.Color = newNodeAnn.RGBColor
2✔
3499
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
2✔
3500

2✔
3501
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
2✔
3502

2✔
3503
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
2✔
3504
                return fmt.Errorf("can't set self node: %w", err)
×
3505
        }
×
3506

3507
        // Finally, propagate it to the nodes in the network.
3508
        err = s.BroadcastMessage(nil, &newNodeAnn)
2✔
3509
        if err != nil {
2✔
3510
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3511
                        "announcement to peers: %v", err)
×
3512
                return err
×
3513
        }
×
3514

3515
        return nil
2✔
3516
}
3517

3518
type nodeAddresses struct {
3519
        pubKey    *btcec.PublicKey
3520
        addresses []net.Addr
3521
}
3522

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

2✔
3533
        // Iterate through the list of LinkNodes to find addresses we should
2✔
3534
        // attempt to connect to based on our set of previous connections. Set
2✔
3535
        // the reconnection port to the default peer port.
2✔
3536
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
2✔
3537
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
2✔
3538
                return err
×
3539
        }
×
3540
        for _, node := range linkNodes {
4✔
3541
                pubStr := string(node.IdentityPub.SerializeCompressed())
2✔
3542
                nodeAddrs := &nodeAddresses{
2✔
3543
                        pubKey:    node.IdentityPub,
2✔
3544
                        addresses: node.Addresses,
2✔
3545
                }
2✔
3546
                nodeAddrsMap[pubStr] = nodeAddrs
2✔
3547
        }
2✔
3548

3549
        // After checking our previous connections for addresses to connect to,
3550
        // iterate through the nodes in our channel graph to find addresses
3551
        // that have been added via NodeAnnouncement messages.
3552
        sourceNode, err := s.graphDB.SourceNode()
2✔
3553
        if err != nil {
2✔
3554
                return err
×
3555
        }
×
3556

3557
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3558
        // each of the nodes.
3559
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
2✔
3560
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
2✔
3561
                tx kvdb.RTx,
2✔
3562
                chanInfo *models.ChannelEdgeInfo,
2✔
3563
                policy, _ *models.ChannelEdgePolicy) error {
4✔
3564

2✔
3565
                // If the remote party has announced the channel to us, but we
2✔
3566
                // haven't yet, then we won't have a policy. However, we don't
2✔
3567
                // need this to connect to the peer, so we'll log it and move on.
2✔
3568
                if policy == nil {
2✔
3569
                        srvrLog.Warnf("No channel policy found for "+
×
3570
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3571
                }
×
3572

3573
                // We'll now fetch the peer opposite from us within this
3574
                // channel so we can queue up a direct connection to them.
3575
                channelPeer, err := s.graphDB.FetchOtherNode(
2✔
3576
                        tx, chanInfo, selfPub,
2✔
3577
                )
2✔
3578
                if err != nil {
2✔
3579
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3580
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3581
                                err)
×
3582
                }
×
3583

3584
                pubStr := string(channelPeer.PubKeyBytes[:])
2✔
3585

2✔
3586
                // Add all unique addresses from channel
2✔
3587
                // graph/NodeAnnouncements to the list of addresses we'll
2✔
3588
                // connect to for this peer.
2✔
3589
                addrSet := make(map[string]net.Addr)
2✔
3590
                for _, addr := range channelPeer.Addresses {
4✔
3591
                        switch addr.(type) {
2✔
3592
                        case *net.TCPAddr:
2✔
3593
                                addrSet[addr.String()] = addr
2✔
3594

3595
                        // We'll only attempt to connect to Tor addresses if Tor
3596
                        // outbound support is enabled.
3597
                        case *tor.OnionAddr:
×
3598
                                if s.cfg.Tor.Active {
×
3599
                                        addrSet[addr.String()] = addr
×
3600
                                }
×
3601
                        }
3602
                }
3603

3604
                // If this peer is also recorded as a link node, we'll add any
3605
                // additional addresses that have not already been selected.
3606
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
2✔
3607
                if ok {
4✔
3608
                        for _, lnAddress := range linkNodeAddrs.addresses {
4✔
3609
                                switch lnAddress.(type) {
2✔
3610
                                case *net.TCPAddr:
2✔
3611
                                        addrSet[lnAddress.String()] = lnAddress
2✔
3612

3613
                                // We'll only attempt to connect to Tor
3614
                                // addresses if Tor outbound support is enabled.
3615
                                case *tor.OnionAddr:
×
3616
                                        if s.cfg.Tor.Active {
×
3617
                                                addrSet[lnAddress.String()] = lnAddress
×
3618
                                        }
×
3619
                                }
3620
                        }
3621
                }
3622

3623
                // Construct a slice of the deduped addresses.
3624
                var addrs []net.Addr
2✔
3625
                for _, addr := range addrSet {
4✔
3626
                        addrs = append(addrs, addr)
2✔
3627
                }
2✔
3628

3629
                n := &nodeAddresses{
2✔
3630
                        addresses: addrs,
2✔
3631
                }
2✔
3632
                n.pubKey, err = channelPeer.PubKey()
2✔
3633
                if err != nil {
2✔
3634
                        return err
×
3635
                }
×
3636

3637
                nodeAddrsMap[pubStr] = n
2✔
3638
                return nil
2✔
3639
        })
3640
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
2✔
3641
                return err
×
3642
        }
×
3643

3644
        srvrLog.Debugf("Establishing %v persistent connections on start",
2✔
3645
                len(nodeAddrsMap))
2✔
3646

2✔
3647
        // Acquire and hold server lock until all persistent connection requests
2✔
3648
        // have been recorded and sent to the connection manager.
2✔
3649
        s.mu.Lock()
2✔
3650
        defer s.mu.Unlock()
2✔
3651

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

3666
                for _, address := range nodeAddr.addresses {
4✔
3667
                        // Create a wrapper address which couples the IP and
2✔
3668
                        // the pubkey so the brontide authenticated connection
2✔
3669
                        // can be established.
2✔
3670
                        lnAddr := &lnwire.NetAddress{
2✔
3671
                                IdentityKey: nodeAddr.pubKey,
2✔
3672
                                Address:     address,
2✔
3673
                        }
2✔
3674

2✔
3675
                        s.persistentPeerAddrs[pubStr] = append(
2✔
3676
                                s.persistentPeerAddrs[pubStr], lnAddr)
2✔
3677
                }
2✔
3678

3679
                // We'll connect to the first 10 peers immediately, then
3680
                // randomly stagger any remaining connections if the
3681
                // stagger initial reconnect flag is set. This ensures
3682
                // that mobile nodes or nodes with a small number of
3683
                // channels obtain connectivity quickly, but larger
3684
                // nodes are able to disperse the costs of connecting to
3685
                // all peers at once.
3686
                if numOutboundConns < numInstantInitReconnect ||
2✔
3687
                        !s.cfg.StaggerInitialReconnect {
4✔
3688

2✔
3689
                        go s.connectToPersistentPeer(pubStr)
2✔
3690
                } else {
2✔
3691
                        go s.delayInitialReconnect(pubStr)
×
3692
                }
×
3693

3694
                numOutboundConns++
2✔
3695
        }
3696

3697
        return nil
2✔
3698
}
3699

3700
// delayInitialReconnect will attempt a reconnection to the given peer after
3701
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3702
//
3703
// NOTE: This method MUST be run as a goroutine.
3704
func (s *server) delayInitialReconnect(pubStr string) {
×
3705
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3706
        select {
×
3707
        case <-time.After(delay):
×
3708
                s.connectToPersistentPeer(pubStr)
×
3709
        case <-s.quit:
×
3710
        }
3711
}
3712

3713
// prunePersistentPeerConnection removes all internal state related to
3714
// persistent connections to a peer within the server. This is used to avoid
3715
// persistent connection retries to peers we do not have any open channels with.
3716
func (s *server) prunePersistentPeerConnection(compressedPubKey [33]byte) {
2✔
3717
        pubKeyStr := string(compressedPubKey[:])
2✔
3718

2✔
3719
        s.mu.Lock()
2✔
3720
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
4✔
3721
                delete(s.persistentPeers, pubKeyStr)
2✔
3722
                delete(s.persistentPeersBackoff, pubKeyStr)
2✔
3723
                delete(s.persistentPeerAddrs, pubKeyStr)
2✔
3724
                s.cancelConnReqs(pubKeyStr, nil)
2✔
3725
                s.mu.Unlock()
2✔
3726

2✔
3727
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
2✔
3728
                        "peer has no open channels", compressedPubKey)
2✔
3729

2✔
3730
                return
2✔
3731
        }
2✔
3732
        s.mu.Unlock()
2✔
3733
}
3734

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

3752
// BroadcastMessage sends a request to the server to broadcast a set of
3753
// messages to all peers other than the one specified by the `skips` parameter.
3754
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3755
// the target peers.
3756
//
3757
// NOTE: This function is safe for concurrent access.
3758
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3759
        msgs ...lnwire.Message) error {
2✔
3760

2✔
3761
        // Filter out peers found in the skips map. We synchronize access to
2✔
3762
        // peersByPub throughout this process to ensure we deliver messages to
2✔
3763
        // exact set of peers present at the time of invocation.
2✔
3764
        s.mu.RLock()
2✔
3765
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
2✔
3766
        for pubStr, sPeer := range s.peersByPub {
4✔
3767
                if skips != nil {
4✔
3768
                        if _, ok := skips[sPeer.PubKey()]; ok {
4✔
3769
                                srvrLog.Tracef("Skipping %x in broadcast with "+
2✔
3770
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
2✔
3771
                                continue
2✔
3772
                        }
3773
                }
3774

3775
                peers = append(peers, sPeer)
2✔
3776
        }
3777
        s.mu.RUnlock()
2✔
3778

2✔
3779
        // Iterate over all known peers, dispatching a go routine to enqueue
2✔
3780
        // all messages to each of peers.
2✔
3781
        var wg sync.WaitGroup
2✔
3782
        for _, sPeer := range peers {
4✔
3783
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
2✔
3784
                        sPeer.PubKey())
2✔
3785

2✔
3786
                // Dispatch a go routine to enqueue all messages to this peer.
2✔
3787
                wg.Add(1)
2✔
3788
                s.wg.Add(1)
2✔
3789
                go func(p lnpeer.Peer) {
4✔
3790
                        defer s.wg.Done()
2✔
3791
                        defer wg.Done()
2✔
3792

2✔
3793
                        p.SendMessageLazy(false, msgs...)
2✔
3794
                }(sPeer)
2✔
3795
        }
3796

3797
        // Wait for all messages to have been dispatched before returning to
3798
        // caller.
3799
        wg.Wait()
2✔
3800

2✔
3801
        return nil
2✔
3802
}
3803

3804
// NotifyWhenOnline can be called by other subsystems to get notified when a
3805
// particular peer comes online. The peer itself is sent across the peerChan.
3806
//
3807
// NOTE: This function is safe for concurrent access.
3808
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3809
        peerChan chan<- lnpeer.Peer) {
2✔
3810

2✔
3811
        s.mu.Lock()
2✔
3812

2✔
3813
        // Compute the target peer's identifier.
2✔
3814
        pubStr := string(peerKey[:])
2✔
3815

2✔
3816
        // Check if peer is connected.
2✔
3817
        peer, ok := s.peersByPub[pubStr]
2✔
3818
        if ok {
4✔
3819
                // Unlock here so that the mutex isn't held while we are
2✔
3820
                // waiting for the peer to become active.
2✔
3821
                s.mu.Unlock()
2✔
3822

2✔
3823
                // Wait until the peer signals that it is actually active
2✔
3824
                // rather than only in the server's maps.
2✔
3825
                select {
2✔
3826
                case <-peer.ActiveSignal():
2✔
3827
                case <-peer.QuitSignal():
1✔
3828
                        // The peer quit, so we'll add the channel to the slice
1✔
3829
                        // and return.
1✔
3830
                        s.mu.Lock()
1✔
3831
                        s.peerConnectedListeners[pubStr] = append(
1✔
3832
                                s.peerConnectedListeners[pubStr], peerChan,
1✔
3833
                        )
1✔
3834
                        s.mu.Unlock()
1✔
3835
                        return
1✔
3836
                }
3837

3838
                // Connected, can return early.
3839
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
2✔
3840

2✔
3841
                select {
2✔
3842
                case peerChan <- peer:
2✔
3843
                case <-s.quit:
1✔
3844
                }
3845

3846
                return
2✔
3847
        }
3848

3849
        // Not connected, store this listener such that it can be notified when
3850
        // the peer comes online.
3851
        s.peerConnectedListeners[pubStr] = append(
2✔
3852
                s.peerConnectedListeners[pubStr], peerChan,
2✔
3853
        )
2✔
3854
        s.mu.Unlock()
2✔
3855
}
3856

3857
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3858
// the given public key has been disconnected. The notification is signaled by
3859
// closing the channel returned.
3860
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
2✔
3861
        s.mu.Lock()
2✔
3862
        defer s.mu.Unlock()
2✔
3863

2✔
3864
        c := make(chan struct{})
2✔
3865

2✔
3866
        // If the peer is already offline, we can immediately trigger the
2✔
3867
        // notification.
2✔
3868
        peerPubKeyStr := string(peerPubKey[:])
2✔
3869
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
2✔
3870
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3871
                close(c)
×
3872
                return c
×
3873
        }
×
3874

3875
        // Otherwise, the peer is online, so we'll keep track of the channel to
3876
        // trigger the notification once the server detects the peer
3877
        // disconnects.
3878
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
2✔
3879
                s.peerDisconnectedListeners[peerPubKeyStr], c,
2✔
3880
        )
2✔
3881

2✔
3882
        return c
2✔
3883
}
3884

3885
// FindPeer will return the peer that corresponds to the passed in public key.
3886
// This function is used by the funding manager, allowing it to update the
3887
// daemon's local representation of the remote peer.
3888
//
3889
// NOTE: This function is safe for concurrent access.
3890
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
2✔
3891
        s.mu.RLock()
2✔
3892
        defer s.mu.RUnlock()
2✔
3893

2✔
3894
        pubStr := string(peerKey.SerializeCompressed())
2✔
3895

2✔
3896
        return s.findPeerByPubStr(pubStr)
2✔
3897
}
2✔
3898

3899
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3900
// which should be a string representation of the peer's serialized, compressed
3901
// public key.
3902
//
3903
// NOTE: This function is safe for concurrent access.
3904
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
2✔
3905
        s.mu.RLock()
2✔
3906
        defer s.mu.RUnlock()
2✔
3907

2✔
3908
        return s.findPeerByPubStr(pubStr)
2✔
3909
}
2✔
3910

3911
// findPeerByPubStr is an internal method that retrieves the specified peer from
3912
// the server's internal state using.
3913
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
2✔
3914
        peer, ok := s.peersByPub[pubStr]
2✔
3915
        if !ok {
4✔
3916
                return nil, ErrPeerNotConnected
2✔
3917
        }
2✔
3918

3919
        return peer, nil
2✔
3920
}
3921

3922
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3923
// exponential backoff. If no previous backoff was known, the default is
3924
// returned.
3925
func (s *server) nextPeerBackoff(pubStr string,
3926
        startTime time.Time) time.Duration {
2✔
3927

2✔
3928
        // Now, determine the appropriate backoff to use for the retry.
2✔
3929
        backoff, ok := s.persistentPeersBackoff[pubStr]
2✔
3930
        if !ok {
4✔
3931
                // If an existing backoff was unknown, use the default.
2✔
3932
                return s.cfg.MinBackoff
2✔
3933
        }
2✔
3934

3935
        // If the peer failed to start properly, we'll just use the previous
3936
        // backoff to compute the subsequent randomized exponential backoff
3937
        // duration. This will roughly double on average.
3938
        if startTime.IsZero() {
2✔
3939
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3940
        }
×
3941

3942
        // The peer succeeded in starting. If the connection didn't last long
3943
        // enough to be considered stable, we'll continue to back off retries
3944
        // with this peer.
3945
        connDuration := time.Since(startTime)
2✔
3946
        if connDuration < defaultStableConnDuration {
4✔
3947
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
2✔
3948
        }
2✔
3949

3950
        // The peer succeed in starting and this was stable peer, so we'll
3951
        // reduce the timeout duration by the length of the connection after
3952
        // applying randomized exponential backoff. We'll only apply this in the
3953
        // case that:
3954
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3955
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3956
        if relaxedBackoff > s.cfg.MinBackoff {
×
3957
                return relaxedBackoff
×
3958
        }
×
3959

3960
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3961
        // the stable connection lasted much longer than our previous backoff.
3962
        // To reward such good behavior, we'll reconnect after the default
3963
        // timeout.
3964
        return s.cfg.MinBackoff
×
3965
}
3966

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

×
3977
        // The connection that comes from the node with a "smaller" pubkey
×
3978
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3979
        // should drop our established connection.
×
3980
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3981
}
×
3982

3983
// InboundPeerConnected initializes a new peer in response to a new inbound
3984
// connection.
3985
//
3986
// NOTE: This function is safe for concurrent access.
3987
func (s *server) InboundPeerConnected(conn net.Conn) {
2✔
3988
        // Exit early if we have already been instructed to shutdown, this
2✔
3989
        // prevents any delayed callbacks from accidentally registering peers.
2✔
3990
        if s.Stopped() {
2✔
3991
                return
×
3992
        }
×
3993

3994
        nodePub := conn.(*brontide.Conn).RemotePub()
2✔
3995
        pubSer := nodePub.SerializeCompressed()
2✔
3996
        pubStr := string(pubSer)
2✔
3997

2✔
3998
        var pubBytes [33]byte
2✔
3999
        copy(pubBytes[:], pubSer)
2✔
4000

2✔
4001
        s.mu.Lock()
2✔
4002
        defer s.mu.Unlock()
2✔
4003

2✔
4004
        // If the remote node's public key is banned, drop the connection.
2✔
4005
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
2✔
4006
        if err != nil {
2✔
4007
                // Clean up the persistent peer maps if we're dropping this
×
4008
                // connection.
×
4009
                s.bannedPersistentPeerConnection(pubStr)
×
4010

×
4011
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4012
                        "of restricted-access connection slots: %v.", pubSer,
×
4013
                        err)
×
4014

×
4015
                conn.Close()
×
4016

×
4017
                return
×
4018
        }
×
4019

4020
        // If we already have an outbound connection to this peer, then ignore
4021
        // this new connection.
4022
        if p, ok := s.outboundPeers[pubStr]; ok {
4✔
4023
                srvrLog.Debugf("Already have outbound connection for %v, "+
2✔
4024
                        "ignoring inbound connection from local=%v, remote=%v",
2✔
4025
                        p, conn.LocalAddr(), conn.RemoteAddr())
2✔
4026

2✔
4027
                conn.Close()
2✔
4028
                return
2✔
4029
        }
2✔
4030

4031
        // If we already have a valid connection that is scheduled to take
4032
        // precedence once the prior peer has finished disconnecting, we'll
4033
        // ignore this connection.
4034
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
2✔
4035
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4036
                        "scheduled", conn.RemoteAddr(), p)
×
4037
                conn.Close()
×
4038
                return
×
4039
        }
×
4040

4041
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
2✔
4042

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

4056
        case nil:
×
4057
                // We already have a connection with the incoming peer. If the
×
4058
                // connection we've already established should be kept and is
×
4059
                // not of the same type of the new connection (inbound), then
×
4060
                // we'll close out the new connection s.t there's only a single
×
4061
                // connection between us.
×
4062
                localPub := s.identityECDH.PubKey()
×
4063
                if !connectedPeer.Inbound() &&
×
4064
                        !shouldDropLocalConnection(localPub, nodePub) {
×
4065

×
4066
                        srvrLog.Warnf("Received inbound connection from "+
×
4067
                                "peer %v, but already have outbound "+
×
4068
                                "connection, dropping conn", connectedPeer)
×
4069
                        conn.Close()
×
4070
                        return
×
4071
                }
×
4072

4073
                // Otherwise, if we should drop the connection, then we'll
4074
                // disconnect our already connected peer.
4075
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4076
                        connectedPeer)
×
4077

×
4078
                s.cancelConnReqs(pubStr, nil)
×
4079

×
4080
                // Remove the current peer from the server's internal state and
×
4081
                // signal that the peer termination watcher does not need to
×
4082
                // execute for this peer.
×
4083
                s.removePeer(connectedPeer)
×
4084
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4085
                s.scheduledPeerConnection[pubStr] = func() {
×
4086
                        s.peerConnected(conn, nil, true, access)
×
4087
                }
×
4088
        }
4089
}
4090

4091
// OutboundPeerConnected initializes a new peer in response to a new outbound
4092
// connection.
4093
// NOTE: This function is safe for concurrent access.
4094
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
2✔
4095
        // Exit early if we have already been instructed to shutdown, this
2✔
4096
        // prevents any delayed callbacks from accidentally registering peers.
2✔
4097
        if s.Stopped() {
2✔
4098
                return
×
4099
        }
×
4100

4101
        nodePub := conn.(*brontide.Conn).RemotePub()
2✔
4102
        pubSer := nodePub.SerializeCompressed()
2✔
4103
        pubStr := string(pubSer)
2✔
4104

2✔
4105
        var pubBytes [33]byte
2✔
4106
        copy(pubBytes[:], pubSer)
2✔
4107

2✔
4108
        s.mu.Lock()
2✔
4109
        defer s.mu.Unlock()
2✔
4110

2✔
4111
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
2✔
4112
        if err != nil {
2✔
4113
                // Clean up the persistent peer maps if we're dropping this
×
4114
                // connection.
×
4115
                s.bannedPersistentPeerConnection(pubStr)
×
4116

×
4117
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4118
                        "of restricted-access connection slots: %v.", pubSer,
×
4119
                        err)
×
4120

×
4121
                if connReq != nil {
×
4122
                        s.connMgr.Remove(connReq.ID())
×
4123
                }
×
4124

4125
                conn.Close()
×
4126

×
4127
                return
×
4128
        }
4129

4130
        // If we already have an inbound connection to this peer, then ignore
4131
        // this new connection.
4132
        if p, ok := s.inboundPeers[pubStr]; ok {
4✔
4133
                srvrLog.Debugf("Already have inbound connection for %v, "+
2✔
4134
                        "ignoring outbound connection from local=%v, remote=%v",
2✔
4135
                        p, conn.LocalAddr(), conn.RemoteAddr())
2✔
4136

2✔
4137
                if connReq != nil {
4✔
4138
                        s.connMgr.Remove(connReq.ID())
2✔
4139
                }
2✔
4140
                conn.Close()
2✔
4141
                return
2✔
4142
        }
4143
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
2✔
4144
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4145
                s.connMgr.Remove(connReq.ID())
×
4146
                conn.Close()
×
4147
                return
×
4148
        }
×
4149

4150
        // If we already have a valid connection that is scheduled to take
4151
        // precedence once the prior peer has finished disconnecting, we'll
4152
        // ignore this connection.
4153
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
2✔
4154
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
4155

×
4156
                if connReq != nil {
×
4157
                        s.connMgr.Remove(connReq.ID())
×
4158
                }
×
4159

4160
                conn.Close()
×
4161
                return
×
4162
        }
4163

4164
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
2✔
4165
                conn.RemoteAddr())
2✔
4166

2✔
4167
        if connReq != nil {
4✔
4168
                // A successful connection was returned by the connmgr.
2✔
4169
                // Immediately cancel all pending requests, excluding the
2✔
4170
                // outbound connection we just established.
2✔
4171
                ignore := connReq.ID()
2✔
4172
                s.cancelConnReqs(pubStr, &ignore)
2✔
4173
        } else {
4✔
4174
                // This was a successful connection made by some other
2✔
4175
                // subsystem. Remove all requests being managed by the connmgr.
2✔
4176
                s.cancelConnReqs(pubStr, nil)
2✔
4177
        }
2✔
4178

4179
        // If we already have a connection with this peer, decide whether or not
4180
        // we need to drop the stale connection. We forgo adding a default case
4181
        // as we expect these to be the only error values returned from
4182
        // findPeerByPubStr.
4183
        connectedPeer, err := s.findPeerByPubStr(pubStr)
2✔
4184
        switch err {
2✔
4185
        case ErrPeerNotConnected:
2✔
4186
                // We were unable to locate an existing connection with the
2✔
4187
                // target peer, proceed to connect.
2✔
4188
                s.peerConnected(conn, connReq, false, access)
2✔
4189

4190
        case nil:
×
4191
                // We already have a connection with the incoming peer. If the
×
4192
                // connection we've already established should be kept and is
×
4193
                // not of the same type of the new connection (outbound), then
×
4194
                // we'll close out the new connection s.t there's only a single
×
4195
                // connection between us.
×
4196
                localPub := s.identityECDH.PubKey()
×
4197
                if connectedPeer.Inbound() &&
×
4198
                        shouldDropLocalConnection(localPub, nodePub) {
×
4199

×
4200
                        srvrLog.Warnf("Established outbound connection to "+
×
4201
                                "peer %v, but already have inbound "+
×
4202
                                "connection, dropping conn", connectedPeer)
×
4203
                        if connReq != nil {
×
4204
                                s.connMgr.Remove(connReq.ID())
×
4205
                        }
×
4206
                        conn.Close()
×
4207
                        return
×
4208
                }
4209

4210
                // Otherwise, _their_ connection should be dropped. So we'll
4211
                // disconnect the peer and send the now obsolete peer to the
4212
                // server for garbage collection.
4213
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4214
                        connectedPeer)
×
4215

×
4216
                // Remove the current peer from the server's internal state and
×
4217
                // signal that the peer termination watcher does not need to
×
4218
                // execute for this peer.
×
4219
                s.removePeer(connectedPeer)
×
4220
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4221
                s.scheduledPeerConnection[pubStr] = func() {
×
4222
                        s.peerConnected(conn, connReq, false, access)
×
4223
                }
×
4224
        }
4225
}
4226

4227
// UnassignedConnID is the default connection ID that a request can have before
4228
// it actually is submitted to the connmgr.
4229
// TODO(conner): move into connmgr package, or better, add connmgr method for
4230
// generating atomic IDs
4231
const UnassignedConnID uint64 = 0
4232

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

4247
        // Next, check to see if we have any outstanding persistent connection
4248
        // requests to this peer. If so, then we'll remove all of these
4249
        // connection requests, and also delete the entry from the map.
4250
        connReqs, ok := s.persistentConnReqs[pubStr]
2✔
4251
        if !ok {
4✔
4252
                return
2✔
4253
        }
2✔
4254

4255
        for _, connReq := range connReqs {
4✔
4256
                srvrLog.Tracef("Canceling %s:", connReqs)
2✔
4257

2✔
4258
                // Atomically capture the current request identifier.
2✔
4259
                connID := connReq.ID()
2✔
4260

2✔
4261
                // Skip any zero IDs, this indicates the request has not
2✔
4262
                // yet been schedule.
2✔
4263
                if connID == UnassignedConnID {
2✔
4264
                        continue
×
4265
                }
4266

4267
                // Skip a particular connection ID if instructed.
4268
                if skip != nil && connID == *skip {
4✔
4269
                        continue
2✔
4270
                }
4271

4272
                s.connMgr.Remove(connID)
2✔
4273
        }
4274

4275
        delete(s.persistentConnReqs, pubStr)
2✔
4276
}
4277

4278
// handleCustomMessage dispatches an incoming custom peers message to
4279
// subscribers.
4280
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
2✔
4281
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
2✔
4282
                peer, msg.Type)
2✔
4283

2✔
4284
        return s.customMessageServer.SendUpdate(&CustomMessage{
2✔
4285
                Peer: peer,
2✔
4286
                Msg:  msg,
2✔
4287
        })
2✔
4288
}
2✔
4289

4290
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4291
// messages.
4292
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
2✔
4293
        return s.customMessageServer.Subscribe()
2✔
4294
}
2✔
4295

4296
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4297
// the channelNotifier's NotifyOpenChannelEvent.
4298
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4299
        remotePub *btcec.PublicKey) error {
2✔
4300

2✔
4301
        // Call newOpenChan to update the access manager's maps for this peer.
2✔
4302
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
4✔
4303
                return err
2✔
4304
        }
2✔
4305

4306
        // Notify subscribers about this open channel event.
4307
        s.channelNotifier.NotifyOpenChannelEvent(op)
2✔
4308

2✔
4309
        return nil
2✔
4310
}
4311

4312
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4313
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4314
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4315
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) error {
2✔
4316

2✔
4317
        // Call newPendingOpenChan to update the access manager's maps for this
2✔
4318
        // peer.
2✔
4319
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
2✔
4320
                return err
×
4321
        }
×
4322

4323
        // Notify subscribers about this event.
4324
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
2✔
4325

2✔
4326
        return nil
2✔
4327
}
4328

4329
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4330
// calls the channelNotifier's NotifyFundingTimeout.
4331
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4332
        remotePub *btcec.PublicKey) error {
2✔
4333

2✔
4334
        // Call newPendingCloseChan to potentially demote the peer.
2✔
4335
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
2✔
4336
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
2✔
4337
                // If we encounter an error while attempting to disconnect the
×
4338
                // peer, log the error.
×
4339
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4340
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4341
                }
×
4342
        }
4343

4344
        // Notify subscribers about this event.
4345
        s.channelNotifier.NotifyFundingTimeout(op)
2✔
4346

2✔
4347
        return nil
2✔
4348
}
4349

4350
// peerConnected is a function that handles initialization a newly connected
4351
// peer by adding it to the server's global list of all active peers, and
4352
// starting all the goroutines the peer needs to function properly. The inbound
4353
// boolean should be true if the peer initiated the connection to us.
4354
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4355
        inbound bool, access peerAccessStatus) {
2✔
4356

2✔
4357
        brontideConn := conn.(*brontide.Conn)
2✔
4358
        addr := conn.RemoteAddr()
2✔
4359
        pubKey := brontideConn.RemotePub()
2✔
4360

2✔
4361
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
2✔
4362
                pubKey.SerializeCompressed(), addr, inbound)
2✔
4363

2✔
4364
        peerAddr := &lnwire.NetAddress{
2✔
4365
                IdentityKey: pubKey,
2✔
4366
                Address:     addr,
2✔
4367
                ChainNet:    s.cfg.ActiveNetParams.Net,
2✔
4368
        }
2✔
4369

2✔
4370
        // With the brontide connection established, we'll now craft the feature
2✔
4371
        // vectors to advertise to the remote node.
2✔
4372
        initFeatures := s.featureMgr.Get(feature.SetInit)
2✔
4373
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
2✔
4374

2✔
4375
        // Lookup past error caches for the peer in the server. If no buffer is
2✔
4376
        // found, create a fresh buffer.
2✔
4377
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
2✔
4378
        errBuffer, ok := s.peerErrors[pkStr]
2✔
4379
        if !ok {
4✔
4380
                var err error
2✔
4381
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
2✔
4382
                if err != nil {
2✔
4383
                        srvrLog.Errorf("unable to create peer %v", err)
×
4384
                        return
×
4385
                }
×
4386
        }
4387

4388
        // If we directly set the peer.Config TowerClient member to the
4389
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4390
        // the peer.Config's TowerClient member will not evaluate to nil even
4391
        // though the underlying value is nil. To avoid this gotcha which can
4392
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4393
        // TowerClient if needed.
4394
        var towerClient wtclient.ClientManager
2✔
4395
        if s.towerClientMgr != nil {
4✔
4396
                towerClient = s.towerClientMgr
2✔
4397
        }
2✔
4398

4399
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
2✔
4400
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
2✔
4401

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

2✔
4445
                        return s.genNodeAnnouncement(nil)
2✔
4446
                },
2✔
4447

4448
                PongBuf: s.pongBuf,
4449

4450
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4451

4452
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4453

4454
                FundingManager: s.fundingMgr,
4455

4456
                Hodl:                    s.cfg.Hodl,
4457
                UnsafeReplay:            s.cfg.UnsafeReplay,
4458
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4459
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4460
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4461
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4462
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4463
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4464
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4465
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4466
                HandleCustomMessage:    s.handleCustomMessage,
4467
                GetAliases:             s.aliasMgr.GetAliases,
4468
                RequestAlias:           s.aliasMgr.RequestAlias,
4469
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4470
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4471
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4472
                MaxFeeExposure:         thresholdMSats,
4473
                Quit:                   s.quit,
4474
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4475
                AuxSigner:              s.implCfg.AuxSigner,
4476
                MsgRouter:              s.implCfg.MsgRouter,
4477
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4478
                AuxResolver:            s.implCfg.AuxContractResolver,
4479
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4480
                ShouldFwdExpEndorsement: func() bool {
2✔
4481
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
4✔
4482
                                return false
2✔
4483
                        }
2✔
4484

4485
                        return clock.NewDefaultClock().Now().Before(
2✔
4486
                                EndorsementExperimentEnd,
2✔
4487
                        )
2✔
4488
                },
4489
        }
4490

4491
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
2✔
4492
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
2✔
4493

2✔
4494
        p := peer.NewBrontide(pCfg)
2✔
4495

2✔
4496
        // Update the access manager with the access permission for this peer.
2✔
4497
        s.peerAccessMan.addPeerAccess(pubKey, access)
2✔
4498

2✔
4499
        // TODO(roasbeef): update IP address for link-node
2✔
4500
        //  * also mark last-seen, do it one single transaction?
2✔
4501

2✔
4502
        s.addPeer(p)
2✔
4503

2✔
4504
        // Once we have successfully added the peer to the server, we can
2✔
4505
        // delete the previous error buffer from the server's map of error
2✔
4506
        // buffers.
2✔
4507
        delete(s.peerErrors, pkStr)
2✔
4508

2✔
4509
        // Dispatch a goroutine to asynchronously start the peer. This process
2✔
4510
        // includes sending and receiving Init messages, which would be a DOS
2✔
4511
        // vector if we held the server's mutex throughout the procedure.
2✔
4512
        s.wg.Add(1)
2✔
4513
        go s.peerInitializer(p)
2✔
4514
}
4515

4516
// addPeer adds the passed peer to the server's global state of all active
4517
// peers.
4518
func (s *server) addPeer(p *peer.Brontide) {
2✔
4519
        if p == nil {
2✔
4520
                return
×
4521
        }
×
4522

4523
        pubBytes := p.IdentityKey().SerializeCompressed()
2✔
4524

2✔
4525
        // Ignore new peers if we're shutting down.
2✔
4526
        if s.Stopped() {
2✔
4527
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4528
                        pubBytes)
×
4529
                p.Disconnect(ErrServerShuttingDown)
×
4530

×
4531
                return
×
4532
        }
×
4533

4534
        // Track the new peer in our indexes so we can quickly look it up either
4535
        // according to its public key, or its peer ID.
4536
        // TODO(roasbeef): pipe all requests through to the
4537
        // queryHandler/peerManager
4538

4539
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4540
        // be human-readable.
4541
        pubStr := string(pubBytes)
2✔
4542

2✔
4543
        s.peersByPub[pubStr] = p
2✔
4544

2✔
4545
        if p.Inbound() {
4✔
4546
                s.inboundPeers[pubStr] = p
2✔
4547
        } else {
4✔
4548
                s.outboundPeers[pubStr] = p
2✔
4549
        }
2✔
4550

4551
        // Inform the peer notifier of a peer online event so that it can be reported
4552
        // to clients listening for peer events.
4553
        var pubKey [33]byte
2✔
4554
        copy(pubKey[:], pubBytes)
2✔
4555

2✔
4556
        s.peerNotifier.NotifyPeerOnline(pubKey)
2✔
4557
}
4558

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

2✔
4571
        pubBytes := p.IdentityKey().SerializeCompressed()
2✔
4572

2✔
4573
        // Avoid initializing peers while the server is exiting.
2✔
4574
        if s.Stopped() {
2✔
4575
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4576
                        pubBytes)
×
4577
                return
×
4578
        }
×
4579

4580
        // Create a channel that will be used to signal a successful start of
4581
        // the link. This prevents the peer termination watcher from beginning
4582
        // its duty too early.
4583
        ready := make(chan struct{})
2✔
4584

2✔
4585
        // Before starting the peer, launch a goroutine to watch for the
2✔
4586
        // unexpected termination of this peer, which will ensure all resources
2✔
4587
        // are properly cleaned up, and re-establish persistent connections when
2✔
4588
        // necessary. The peer termination watcher will be short circuited if
2✔
4589
        // the peer is ever added to the ignorePeerTermination map, indicating
2✔
4590
        // that the server has already handled the removal of this peer.
2✔
4591
        s.wg.Add(1)
2✔
4592
        go s.peerTerminationWatcher(p, ready)
2✔
4593

2✔
4594
        // Start the peer! If an error occurs, we Disconnect the peer, which
2✔
4595
        // will unblock the peerTerminationWatcher.
2✔
4596
        if err := p.Start(); err != nil {
4✔
4597
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
2✔
4598

2✔
4599
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
2✔
4600
                return
2✔
4601
        }
2✔
4602

4603
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4604
        // was successful, and to begin watching the peer's wait group.
4605
        close(ready)
2✔
4606

2✔
4607
        s.mu.Lock()
2✔
4608
        defer s.mu.Unlock()
2✔
4609

2✔
4610
        // Check if there are listeners waiting for this peer to come online.
2✔
4611
        srvrLog.Debugf("Notifying that peer %v is online", p)
2✔
4612

2✔
4613
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
2✔
4614
        // route.Vertex as the key type of peerConnectedListeners.
2✔
4615
        pubStr := string(pubBytes)
2✔
4616
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
4✔
4617
                select {
2✔
4618
                case peerChan <- p:
2✔
4619
                case <-s.quit:
×
4620
                        return
×
4621
                }
4622
        }
4623
        delete(s.peerConnectedListeners, pubStr)
2✔
4624
}
4625

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

2✔
4640
        p.WaitForDisconnect(ready)
2✔
4641

2✔
4642
        srvrLog.Debugf("Peer %v has been disconnected", p)
2✔
4643

2✔
4644
        // If the server is exiting then we can bail out early ourselves as all
2✔
4645
        // the other sub-systems will already be shutting down.
2✔
4646
        if s.Stopped() {
4✔
4647
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
2✔
4648
                return
2✔
4649
        }
2✔
4650

4651
        // Next, we'll cancel all pending funding reservations with this node.
4652
        // If we tried to initiate any funding flows that haven't yet finished,
4653
        // then we need to unlock those committed outputs so they're still
4654
        // available for use.
4655
        s.fundingMgr.CancelPeerReservations(p.PubKey())
2✔
4656

2✔
4657
        pubKey := p.IdentityKey()
2✔
4658

2✔
4659
        // We'll also inform the gossiper that this peer is no longer active,
2✔
4660
        // so we don't need to maintain sync state for it any longer.
2✔
4661
        s.authGossiper.PruneSyncState(p.PubKey())
2✔
4662

2✔
4663
        // Tell the switch to remove all links associated with this peer.
2✔
4664
        // Passing nil as the target link indicates that all links associated
2✔
4665
        // with this interface should be closed.
2✔
4666
        //
2✔
4667
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
2✔
4668
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
2✔
4669
        if err != nil && err != htlcswitch.ErrNoLinksFound {
2✔
4670
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4671
        }
×
4672

4673
        for _, link := range links {
4✔
4674
                s.htlcSwitch.RemoveLink(link.ChanID())
2✔
4675
        }
2✔
4676

4677
        s.mu.Lock()
2✔
4678
        defer s.mu.Unlock()
2✔
4679

2✔
4680
        // If there were any notification requests for when this peer
2✔
4681
        // disconnected, we can trigger them now.
2✔
4682
        srvrLog.Debugf("Notifying that peer %v is offline", p)
2✔
4683
        pubStr := string(pubKey.SerializeCompressed())
2✔
4684
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
4✔
4685
                close(offlineChan)
2✔
4686
        }
2✔
4687
        delete(s.peerDisconnectedListeners, pubStr)
2✔
4688

2✔
4689
        // If the server has already removed this peer, we can short circuit the
2✔
4690
        // peer termination watcher and skip cleanup.
2✔
4691
        if _, ok := s.ignorePeerTermination[p]; ok {
2✔
4692
                delete(s.ignorePeerTermination, p)
×
4693

×
4694
                pubKey := p.PubKey()
×
4695
                pubStr := string(pubKey[:])
×
4696

×
4697
                // If a connection callback is present, we'll go ahead and
×
4698
                // execute it now that previous peer has fully disconnected. If
×
4699
                // the callback is not present, this likely implies the peer was
×
4700
                // purposefully disconnected via RPC, and that no reconnect
×
4701
                // should be attempted.
×
4702
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4703
                if ok {
×
4704
                        delete(s.scheduledPeerConnection, pubStr)
×
4705
                        connCallback()
×
4706
                }
×
4707
                return
×
4708
        }
4709

4710
        // First, cleanup any remaining state the server has regarding the peer
4711
        // in question.
4712
        s.removePeer(p)
2✔
4713

2✔
4714
        // Next, check to see if this is a persistent peer or not.
2✔
4715
        if _, ok := s.persistentPeers[pubStr]; !ok {
4✔
4716
                return
2✔
4717
        }
2✔
4718

4719
        // Get the last address that we used to connect to the peer.
4720
        addrs := []net.Addr{
2✔
4721
                p.NetAddress().Address,
2✔
4722
        }
2✔
4723

2✔
4724
        // We'll ensure that we locate all the peers advertised addresses for
2✔
4725
        // reconnection purposes.
2✔
4726
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
2✔
4727
        switch {
2✔
4728
        // We found advertised addresses, so use them.
4729
        case err == nil:
2✔
4730
                addrs = advertisedAddrs
2✔
4731

4732
        // The peer doesn't have an advertised address.
4733
        case err == errNoAdvertisedAddr:
2✔
4734
                // If it is an outbound peer then we fall back to the existing
2✔
4735
                // peer address.
2✔
4736
                if !p.Inbound() {
4✔
4737
                        break
2✔
4738
                }
4739

4740
                // Fall back to the existing peer address if
4741
                // we're not accepting connections over Tor.
4742
                if s.torController == nil {
4✔
4743
                        break
2✔
4744
                }
4745

4746
                // If we are, the peer's address won't be known
4747
                // to us (we'll see a private address, which is
4748
                // the address used by our onion service to dial
4749
                // to lnd), so we don't have enough information
4750
                // to attempt a reconnect.
4751
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4752
                        "to inbound peer %v without "+
×
4753
                        "advertised address", p)
×
4754
                return
×
4755

4756
        // We came across an error retrieving an advertised
4757
        // address, log it, and fall back to the existing peer
4758
        // address.
4759
        default:
2✔
4760
                srvrLog.Errorf("Unable to retrieve advertised "+
2✔
4761
                        "address for node %x: %v", p.PubKey(),
2✔
4762
                        err)
2✔
4763
        }
4764

4765
        // Make an easy lookup map so that we can check if an address
4766
        // is already in the address list that we have stored for this peer.
4767
        existingAddrs := make(map[string]bool)
2✔
4768
        for _, addr := range s.persistentPeerAddrs[pubStr] {
4✔
4769
                existingAddrs[addr.String()] = true
2✔
4770
        }
2✔
4771

4772
        // Add any missing addresses for this peer to persistentPeerAddr.
4773
        for _, addr := range addrs {
4✔
4774
                if existingAddrs[addr.String()] {
2✔
4775
                        continue
×
4776
                }
4777

4778
                s.persistentPeerAddrs[pubStr] = append(
2✔
4779
                        s.persistentPeerAddrs[pubStr],
2✔
4780
                        &lnwire.NetAddress{
2✔
4781
                                IdentityKey: p.IdentityKey(),
2✔
4782
                                Address:     addr,
2✔
4783
                                ChainNet:    p.NetAddress().ChainNet,
2✔
4784
                        },
2✔
4785
                )
2✔
4786
        }
4787

4788
        // Record the computed backoff in the backoff map.
4789
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
2✔
4790
        s.persistentPeersBackoff[pubStr] = backoff
2✔
4791

2✔
4792
        // Initialize a retry canceller for this peer if one does not
2✔
4793
        // exist.
2✔
4794
        cancelChan, ok := s.persistentRetryCancels[pubStr]
2✔
4795
        if !ok {
4✔
4796
                cancelChan = make(chan struct{})
2✔
4797
                s.persistentRetryCancels[pubStr] = cancelChan
2✔
4798
        }
2✔
4799

4800
        // We choose not to wait group this go routine since the Connect
4801
        // call can stall for arbitrarily long if we shutdown while an
4802
        // outbound connection attempt is being made.
4803
        go func() {
4✔
4804
                srvrLog.Debugf("Scheduling connection re-establishment to "+
2✔
4805
                        "persistent peer %x in %s",
2✔
4806
                        p.IdentityKey().SerializeCompressed(), backoff)
2✔
4807

2✔
4808
                select {
2✔
4809
                case <-time.After(backoff):
2✔
4810
                case <-cancelChan:
2✔
4811
                        return
2✔
4812
                case <-s.quit:
2✔
4813
                        return
2✔
4814
                }
4815

4816
                srvrLog.Debugf("Attempting to re-establish persistent "+
2✔
4817
                        "connection to peer %x",
2✔
4818
                        p.IdentityKey().SerializeCompressed())
2✔
4819

2✔
4820
                s.connectToPersistentPeer(pubStr)
2✔
4821
        }()
4822
}
4823

4824
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4825
// to connect to the peer. It creates connection requests if there are
4826
// currently none for a given address and it removes old connection requests
4827
// if the associated address is no longer in the latest address list for the
4828
// peer.
4829
func (s *server) connectToPersistentPeer(pubKeyStr string) {
2✔
4830
        s.mu.Lock()
2✔
4831
        defer s.mu.Unlock()
2✔
4832

2✔
4833
        // Create an easy lookup map of the addresses we have stored for the
2✔
4834
        // peer. We will remove entries from this map if we have existing
2✔
4835
        // connection requests for the associated address and then any leftover
2✔
4836
        // entries will indicate which addresses we should create new
2✔
4837
        // connection requests for.
2✔
4838
        addrMap := make(map[string]*lnwire.NetAddress)
2✔
4839
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
4✔
4840
                addrMap[addr.String()] = addr
2✔
4841
        }
2✔
4842

4843
        // Go through each of the existing connection requests and
4844
        // check if they correspond to the latest set of addresses. If
4845
        // there is a connection requests that does not use one of the latest
4846
        // advertised addresses then remove that connection request.
4847
        var updatedConnReqs []*connmgr.ConnReq
2✔
4848
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
4✔
4849
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
2✔
4850

2✔
4851
                switch _, ok := addrMap[lnAddr]; ok {
2✔
4852
                // If the existing connection request is using one of the
4853
                // latest advertised addresses for the peer then we add it to
4854
                // updatedConnReqs and remove the associated address from
4855
                // addrMap so that we don't recreate this connReq later on.
4856
                case true:
×
4857
                        updatedConnReqs = append(
×
4858
                                updatedConnReqs, connReq,
×
4859
                        )
×
4860
                        delete(addrMap, lnAddr)
×
4861

4862
                // If the existing connection request is using an address that
4863
                // is not one of the latest advertised addresses for the peer
4864
                // then we remove the connecting request from the connection
4865
                // manager.
4866
                case false:
2✔
4867
                        srvrLog.Info(
2✔
4868
                                "Removing conn req:", connReq.Addr.String(),
2✔
4869
                        )
2✔
4870
                        s.connMgr.Remove(connReq.ID())
2✔
4871
                }
4872
        }
4873

4874
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
2✔
4875

2✔
4876
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
2✔
4877
        if !ok {
4✔
4878
                cancelChan = make(chan struct{})
2✔
4879
                s.persistentRetryCancels[pubKeyStr] = cancelChan
2✔
4880
        }
2✔
4881

4882
        // Any addresses left in addrMap are new ones that we have not made
4883
        // connection requests for. So create new connection requests for those.
4884
        // If there is more than one address in the address map, stagger the
4885
        // creation of the connection requests for those.
4886
        go func() {
4✔
4887
                ticker := time.NewTicker(multiAddrConnectionStagger)
2✔
4888
                defer ticker.Stop()
2✔
4889

2✔
4890
                for _, addr := range addrMap {
4✔
4891
                        // Send the persistent connection request to the
2✔
4892
                        // connection manager, saving the request itself so we
2✔
4893
                        // can cancel/restart the process as needed.
2✔
4894
                        connReq := &connmgr.ConnReq{
2✔
4895
                                Addr:      addr,
2✔
4896
                                Permanent: true,
2✔
4897
                        }
2✔
4898

2✔
4899
                        s.mu.Lock()
2✔
4900
                        s.persistentConnReqs[pubKeyStr] = append(
2✔
4901
                                s.persistentConnReqs[pubKeyStr], connReq,
2✔
4902
                        )
2✔
4903
                        s.mu.Unlock()
2✔
4904

2✔
4905
                        srvrLog.Debugf("Attempting persistent connection to "+
2✔
4906
                                "channel peer %v", addr)
2✔
4907

2✔
4908
                        go s.connMgr.Connect(connReq)
2✔
4909

2✔
4910
                        select {
2✔
4911
                        case <-s.quit:
2✔
4912
                                return
2✔
4913
                        case <-cancelChan:
2✔
4914
                                return
2✔
4915
                        case <-ticker.C:
2✔
4916
                        }
4917
                }
4918
        }()
4919
}
4920

4921
// removePeer removes the passed peer from the server's state of all active
4922
// peers.
4923
func (s *server) removePeer(p *peer.Brontide) {
2✔
4924
        if p == nil {
2✔
4925
                return
×
4926
        }
×
4927

4928
        srvrLog.Debugf("removing peer %v", p)
2✔
4929

2✔
4930
        // As the peer is now finished, ensure that the TCP connection is
2✔
4931
        // closed and all of its related goroutines have exited.
2✔
4932
        p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
2✔
4933

2✔
4934
        // If this peer had an active persistent connection request, remove it.
2✔
4935
        if p.ConnReq() != nil {
4✔
4936
                s.connMgr.Remove(p.ConnReq().ID())
2✔
4937
        }
2✔
4938

4939
        // Ignore deleting peers if we're shutting down.
4940
        if s.Stopped() {
2✔
4941
                return
×
4942
        }
×
4943

4944
        pKey := p.PubKey()
2✔
4945
        pubSer := pKey[:]
2✔
4946
        pubStr := string(pubSer)
2✔
4947

2✔
4948
        delete(s.peersByPub, pubStr)
2✔
4949

2✔
4950
        if p.Inbound() {
4✔
4951
                delete(s.inboundPeers, pubStr)
2✔
4952
        } else {
4✔
4953
                delete(s.outboundPeers, pubStr)
2✔
4954
        }
2✔
4955

4956
        // Remove the peer's access permission from the access manager.
4957
        s.peerAccessMan.removePeerAccess(p.IdentityKey())
2✔
4958

2✔
4959
        // Copy the peer's error buffer across to the server if it has any items
2✔
4960
        // in it so that we can restore peer errors across connections.
2✔
4961
        if p.ErrorBuffer().Total() > 0 {
4✔
4962
                s.peerErrors[pubStr] = p.ErrorBuffer()
2✔
4963
        }
2✔
4964

4965
        // Inform the peer notifier of a peer offline event so that it can be
4966
        // reported to clients listening for peer events.
4967
        var pubKey [33]byte
2✔
4968
        copy(pubKey[:], pubSer)
2✔
4969

2✔
4970
        s.peerNotifier.NotifyPeerOffline(pubKey)
2✔
4971
}
4972

4973
// ConnectToPeer requests that the server connect to a Lightning Network peer
4974
// at the specified address. This function will *block* until either a
4975
// connection is established, or the initial handshake process fails.
4976
//
4977
// NOTE: This function is safe for concurrent access.
4978
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4979
        perm bool, timeout time.Duration) error {
2✔
4980

2✔
4981
        targetPub := string(addr.IdentityKey.SerializeCompressed())
2✔
4982

2✔
4983
        // Acquire mutex, but use explicit unlocking instead of defer for
2✔
4984
        // better granularity.  In certain conditions, this method requires
2✔
4985
        // making an outbound connection to a remote peer, which requires the
2✔
4986
        // lock to be released, and subsequently reacquired.
2✔
4987
        s.mu.Lock()
2✔
4988

2✔
4989
        // Ensure we're not already connected to this peer.
2✔
4990
        peer, err := s.findPeerByPubStr(targetPub)
2✔
4991
        if err == nil {
4✔
4992
                s.mu.Unlock()
2✔
4993
                return &errPeerAlreadyConnected{peer: peer}
2✔
4994
        }
2✔
4995

4996
        // Peer was not found, continue to pursue connection with peer.
4997

4998
        // If there's already a pending connection request for this pubkey,
4999
        // then we ignore this request to ensure we don't create a redundant
5000
        // connection.
5001
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
4✔
5002
                srvrLog.Warnf("Already have %d persistent connection "+
2✔
5003
                        "requests for %v, connecting anyway.", len(reqs), addr)
2✔
5004
        }
2✔
5005

5006
        // If there's not already a pending or active connection to this node,
5007
        // then instruct the connection manager to attempt to establish a
5008
        // persistent connection to the peer.
5009
        srvrLog.Debugf("Connecting to %v", addr)
2✔
5010
        if perm {
4✔
5011
                connReq := &connmgr.ConnReq{
2✔
5012
                        Addr:      addr,
2✔
5013
                        Permanent: true,
2✔
5014
                }
2✔
5015

2✔
5016
                // Since the user requested a permanent connection, we'll set
2✔
5017
                // the entry to true which will tell the server to continue
2✔
5018
                // reconnecting even if the number of channels with this peer is
2✔
5019
                // zero.
2✔
5020
                s.persistentPeers[targetPub] = true
2✔
5021
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
4✔
5022
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
2✔
5023
                }
2✔
5024
                s.persistentConnReqs[targetPub] = append(
2✔
5025
                        s.persistentConnReqs[targetPub], connReq,
2✔
5026
                )
2✔
5027
                s.mu.Unlock()
2✔
5028

2✔
5029
                go s.connMgr.Connect(connReq)
2✔
5030

2✔
5031
                return nil
2✔
5032
        }
5033
        s.mu.Unlock()
2✔
5034

2✔
5035
        // If we're not making a persistent connection, then we'll attempt to
2✔
5036
        // connect to the target peer. If the we can't make the connection, or
2✔
5037
        // the crypto negotiation breaks down, then return an error to the
2✔
5038
        // caller.
2✔
5039
        errChan := make(chan error, 1)
2✔
5040
        s.connectToPeer(addr, errChan, timeout)
2✔
5041

2✔
5042
        select {
2✔
5043
        case err := <-errChan:
2✔
5044
                return err
2✔
5045
        case <-s.quit:
×
5046
                return ErrServerShuttingDown
×
5047
        }
5048
}
5049

5050
// connectToPeer establishes a connection to a remote peer. errChan is used to
5051
// notify the caller if the connection attempt has failed. Otherwise, it will be
5052
// closed.
5053
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5054
        errChan chan<- error, timeout time.Duration) {
2✔
5055

2✔
5056
        conn, err := brontide.Dial(
2✔
5057
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
2✔
5058
        )
2✔
5059
        if err != nil {
4✔
5060
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
2✔
5061
                select {
2✔
5062
                case errChan <- err:
2✔
5063
                case <-s.quit:
×
5064
                }
5065
                return
2✔
5066
        }
5067

5068
        close(errChan)
2✔
5069

2✔
5070
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
2✔
5071
                conn.LocalAddr(), conn.RemoteAddr())
2✔
5072

2✔
5073
        s.OutboundPeerConnected(nil, conn)
2✔
5074
}
5075

5076
// DisconnectPeer sends the request to server to close the connection with peer
5077
// identified by public key.
5078
//
5079
// NOTE: This function is safe for concurrent access.
5080
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
2✔
5081
        pubBytes := pubKey.SerializeCompressed()
2✔
5082
        pubStr := string(pubBytes)
2✔
5083

2✔
5084
        s.mu.Lock()
2✔
5085
        defer s.mu.Unlock()
2✔
5086

2✔
5087
        // Check that were actually connected to this peer. If not, then we'll
2✔
5088
        // exit in an error as we can't disconnect from a peer that we're not
2✔
5089
        // currently connected to.
2✔
5090
        peer, err := s.findPeerByPubStr(pubStr)
2✔
5091
        if err == ErrPeerNotConnected {
4✔
5092
                return fmt.Errorf("peer %x is not connected", pubBytes)
2✔
5093
        }
2✔
5094

5095
        srvrLog.Infof("Disconnecting from %v", peer)
2✔
5096

2✔
5097
        s.cancelConnReqs(pubStr, nil)
2✔
5098

2✔
5099
        // If this peer was formerly a persistent connection, then we'll remove
2✔
5100
        // them from this map so we don't attempt to re-connect after we
2✔
5101
        // disconnect.
2✔
5102
        delete(s.persistentPeers, pubStr)
2✔
5103
        delete(s.persistentPeersBackoff, pubStr)
2✔
5104

2✔
5105
        // Remove the peer by calling Disconnect. Previously this was done with
2✔
5106
        // removePeer, which bypassed the peerTerminationWatcher.
2✔
5107
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
2✔
5108

2✔
5109
        return nil
2✔
5110
}
5111

5112
// OpenChannel sends a request to the server to open a channel to the specified
5113
// peer identified by nodeKey with the passed channel funding parameters.
5114
//
5115
// NOTE: This function is safe for concurrent access.
5116
func (s *server) OpenChannel(
5117
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
2✔
5118

2✔
5119
        // The updateChan will have a buffer of 2, since we expect a ChanPending
2✔
5120
        // + a ChanOpen update, and we want to make sure the funding process is
2✔
5121
        // not blocked if the caller is not reading the updates.
2✔
5122
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
2✔
5123
        req.Err = make(chan error, 1)
2✔
5124

2✔
5125
        // First attempt to locate the target peer to open a channel with, if
2✔
5126
        // we're unable to locate the peer then this request will fail.
2✔
5127
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
2✔
5128
        s.mu.RLock()
2✔
5129
        peer, ok := s.peersByPub[string(pubKeyBytes)]
2✔
5130
        if !ok {
2✔
5131
                s.mu.RUnlock()
×
5132

×
5133
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5134
                return req.Updates, req.Err
×
5135
        }
×
5136
        req.Peer = peer
2✔
5137
        s.mu.RUnlock()
2✔
5138

2✔
5139
        // We'll wait until the peer is active before beginning the channel
2✔
5140
        // opening process.
2✔
5141
        select {
2✔
5142
        case <-peer.ActiveSignal():
2✔
5143
        case <-peer.QuitSignal():
×
5144
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5145
                return req.Updates, req.Err
×
5146
        case <-s.quit:
×
5147
                req.Err <- ErrServerShuttingDown
×
5148
                return req.Updates, req.Err
×
5149
        }
5150

5151
        // If the fee rate wasn't specified at this point we fail the funding
5152
        // because of the missing fee rate information. The caller of the
5153
        // `OpenChannel` method needs to make sure that default values for the
5154
        // fee rate are set beforehand.
5155
        if req.FundingFeePerKw == 0 {
2✔
5156
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5157
                        "the channel opening transaction")
×
5158

×
5159
                return req.Updates, req.Err
×
5160
        }
×
5161

5162
        // Spawn a goroutine to send the funding workflow request to the funding
5163
        // manager. This allows the server to continue handling queries instead
5164
        // of blocking on this request which is exported as a synchronous
5165
        // request to the outside world.
5166
        go s.fundingMgr.InitFundingWorkflow(req)
2✔
5167

2✔
5168
        return req.Updates, req.Err
2✔
5169
}
5170

5171
// Peers returns a slice of all active peers.
5172
//
5173
// NOTE: This function is safe for concurrent access.
5174
func (s *server) Peers() []*peer.Brontide {
2✔
5175
        s.mu.RLock()
2✔
5176
        defer s.mu.RUnlock()
2✔
5177

2✔
5178
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
2✔
5179
        for _, peer := range s.peersByPub {
4✔
5180
                peers = append(peers, peer)
2✔
5181
        }
2✔
5182

5183
        return peers
2✔
5184
}
5185

5186
// computeNextBackoff uses a truncated exponential backoff to compute the next
5187
// backoff using the value of the exiting backoff. The returned duration is
5188
// randomized in either direction by 1/20 to prevent tight loops from
5189
// stabilizing.
5190
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
2✔
5191
        // Double the current backoff, truncating if it exceeds our maximum.
2✔
5192
        nextBackoff := 2 * currBackoff
2✔
5193
        if nextBackoff > maxBackoff {
4✔
5194
                nextBackoff = maxBackoff
2✔
5195
        }
2✔
5196

5197
        // Using 1/10 of our duration as a margin, compute a random offset to
5198
        // avoid the nodes entering connection cycles.
5199
        margin := nextBackoff / 10
2✔
5200

2✔
5201
        var wiggle big.Int
2✔
5202
        wiggle.SetUint64(uint64(margin))
2✔
5203
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
2✔
5204
                // Randomizing is not mission critical, so we'll just return the
×
5205
                // current backoff.
×
5206
                return nextBackoff
×
5207
        }
×
5208

5209
        // Otherwise add in our wiggle, but subtract out half of the margin so
5210
        // that the backoff can tweaked by 1/20 in either direction.
5211
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
2✔
5212
}
5213

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

5218
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5219
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
2✔
5220
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
2✔
5221
        if err != nil {
2✔
5222
                return nil, err
×
5223
        }
×
5224

5225
        node, err := s.graphDB.FetchLightningNode(vertex)
2✔
5226
        if err != nil {
4✔
5227
                return nil, err
2✔
5228
        }
2✔
5229

5230
        if len(node.Addresses) == 0 {
4✔
5231
                return nil, errNoAdvertisedAddr
2✔
5232
        }
2✔
5233

5234
        return node.Addresses, nil
2✔
5235
}
5236

5237
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5238
// channel update for a target channel.
5239
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5240
        *lnwire.ChannelUpdate1, error) {
2✔
5241

2✔
5242
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
2✔
5243
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
4✔
5244
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
2✔
5245
                if err != nil {
4✔
5246
                        return nil, err
2✔
5247
                }
2✔
5248

5249
                return netann.ExtractChannelUpdate(
2✔
5250
                        ourPubKey[:], info, edge1, edge2,
2✔
5251
                )
2✔
5252
        }
5253
}
5254

5255
// applyChannelUpdate applies the channel update to the different sub-systems of
5256
// the server. The useAlias boolean denotes whether or not to send an alias in
5257
// place of the real SCID.
5258
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5259
        op *wire.OutPoint, useAlias bool) error {
2✔
5260

2✔
5261
        var (
2✔
5262
                peerAlias    *lnwire.ShortChannelID
2✔
5263
                defaultAlias lnwire.ShortChannelID
2✔
5264
        )
2✔
5265

2✔
5266
        chanID := lnwire.NewChanIDFromOutPoint(*op)
2✔
5267

2✔
5268
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
2✔
5269
        // in the ChannelUpdate if it hasn't been announced yet.
2✔
5270
        if useAlias {
4✔
5271
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
2✔
5272
                if foundAlias != defaultAlias {
4✔
5273
                        peerAlias = &foundAlias
2✔
5274
                }
2✔
5275
        }
5276

5277
        errChan := s.authGossiper.ProcessLocalAnnouncement(
2✔
5278
                update, discovery.RemoteAlias(peerAlias),
2✔
5279
        )
2✔
5280
        select {
2✔
5281
        case err := <-errChan:
2✔
5282
                return err
2✔
5283
        case <-s.quit:
×
5284
                return ErrServerShuttingDown
×
5285
        }
5286
}
5287

5288
// SendCustomMessage sends a custom message to the peer with the specified
5289
// pubkey.
5290
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5291
        data []byte) error {
2✔
5292

2✔
5293
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
2✔
5294
        if err != nil {
2✔
5295
                return err
×
5296
        }
×
5297

5298
        // We'll wait until the peer is active.
5299
        select {
2✔
5300
        case <-peer.ActiveSignal():
2✔
5301
        case <-peer.QuitSignal():
×
5302
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5303
        case <-s.quit:
×
5304
                return ErrServerShuttingDown
×
5305
        }
5306

5307
        msg, err := lnwire.NewCustom(msgType, data)
2✔
5308
        if err != nil {
4✔
5309
                return err
2✔
5310
        }
2✔
5311

5312
        // Send the message as low-priority. For now we assume that all
5313
        // application-defined message are low priority.
5314
        return peer.SendMessageLazy(true, msg)
2✔
5315
}
5316

5317
// newSweepPkScriptGen creates closure that generates a new public key script
5318
// which should be used to sweep any funds into the on-chain wallet.
5319
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5320
// (p2wkh) output.
5321
func newSweepPkScriptGen(
5322
        wallet lnwallet.WalletController,
5323
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
2✔
5324

2✔
5325
        return func() fn.Result[lnwallet.AddrWithKey] {
4✔
5326
                sweepAddr, err := wallet.NewAddress(
2✔
5327
                        lnwallet.TaprootPubkey, false,
2✔
5328
                        lnwallet.DefaultAccountName,
2✔
5329
                )
2✔
5330
                if err != nil {
2✔
5331
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5332
                }
×
5333

5334
                addr, err := txscript.PayToAddrScript(sweepAddr)
2✔
5335
                if err != nil {
2✔
5336
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5337
                }
×
5338

5339
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
2✔
5340
                        wallet, netParams, addr,
2✔
5341
                )
2✔
5342
                if err != nil {
2✔
5343
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5344
                }
×
5345

5346
                return fn.Ok(lnwallet.AddrWithKey{
2✔
5347
                        DeliveryAddress: addr,
2✔
5348
                        InternalKey:     internalKeyDesc,
2✔
5349
                })
2✔
5350
        }
5351
}
5352

5353
// shouldPeerBootstrap returns true if we should attempt to perform peer
5354
// bootstrapping to actively seek our peers using the set of active network
5355
// bootstrappers.
5356
func shouldPeerBootstrap(cfg *Config) bool {
2✔
5357
        isSimnet := cfg.Bitcoin.SimNet
2✔
5358
        isSignet := cfg.Bitcoin.SigNet
2✔
5359
        isRegtest := cfg.Bitcoin.RegTest
2✔
5360
        isDevNetwork := isSimnet || isSignet || isRegtest
2✔
5361

2✔
5362
        // TODO(yy): remove the check on simnet/regtest such that the itest is
2✔
5363
        // covering the bootstrapping process.
2✔
5364
        return !cfg.NoNetBootstrap && !isDevNetwork
2✔
5365
}
2✔
5366

5367
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5368
// finished.
5369
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
2✔
5370
        // Get a list of closed channels.
2✔
5371
        channels, err := s.chanStateDB.FetchClosedChannels(false)
2✔
5372
        if err != nil {
2✔
5373
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5374
                return nil
×
5375
        }
×
5376

5377
        // Save the SCIDs in a map.
5378
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
2✔
5379
        for _, c := range channels {
4✔
5380
                // If the channel is not pending, its FC has been finalized.
2✔
5381
                if !c.IsPending {
4✔
5382
                        closedSCIDs[c.ShortChanID] = struct{}{}
2✔
5383
                }
2✔
5384
        }
5385

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

5400
        for _, c := range pendings {
4✔
5401
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
4✔
5402
                        continue
2✔
5403
                }
5404

5405
                // If the channel is still reported as pending, remove it from
5406
                // the map.
5407
                delete(closedSCIDs, c.ShortChannelID)
×
5408

×
5409
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5410
                        c.ShortChannelID)
×
5411
        }
5412

5413
        return closedSCIDs
2✔
5414
}
5415

5416
// getStartingBeat returns the current beat. This is used during the startup to
5417
// initialize blockbeat consumers.
5418
func (s *server) getStartingBeat() (*chainio.Beat, error) {
2✔
5419
        // beat is the current blockbeat.
2✔
5420
        var beat *chainio.Beat
2✔
5421

2✔
5422
        // We should get a notification with the current best block immediately
2✔
5423
        // by passing a nil block.
2✔
5424
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
2✔
5425
        if err != nil {
2✔
5426
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5427
        }
×
5428
        defer blockEpochs.Cancel()
2✔
5429

2✔
5430
        // We registered for the block epochs with a nil request. The notifier
2✔
5431
        // should send us the current best block immediately. So we need to
2✔
5432
        // wait for it here because we need to know the current best height.
2✔
5433
        select {
2✔
5434
        case bestBlock := <-blockEpochs.Epochs:
2✔
5435
                srvrLog.Infof("Received initial block %v at height %d",
2✔
5436
                        bestBlock.Hash, bestBlock.Height)
2✔
5437

2✔
5438
                // Update the current blockbeat.
2✔
5439
                beat = chainio.NewBeat(*bestBlock)
2✔
5440

5441
        case <-s.quit:
×
5442
                srvrLog.Debug("LND shutting down")
×
5443
        }
5444

5445
        return beat, nil
2✔
5446
}
5447

5448
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5449
// point has an active RBF chan closer.
5450
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5451
        chanPoint wire.OutPoint) bool {
2✔
5452

2✔
5453
        pubBytes := peerPub.SerializeCompressed()
2✔
5454

2✔
5455
        s.mu.RLock()
2✔
5456
        targetPeer, ok := s.peersByPub[string(pubBytes)]
2✔
5457
        s.mu.RUnlock()
2✔
5458
        if !ok {
2✔
5459
                return false
×
5460
        }
×
5461

5462
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
2✔
5463
}
5464

5465
// attemptCoopRbfFeeBump attempts to look up the active chan closer for a
5466
// channel given the outpoint. If found, we'll attempt to do a fee bump,
5467
// returning channels used for updates. If the channel isn't currently active
5468
// (p2p connection established), then his function will return an error.
5469
func (s *server) attemptCoopRbfFeeBump(ctx context.Context,
5470
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
5471
        deliveryScript lnwire.DeliveryAddress) (*peer.CoopCloseUpdates, error) {
2✔
5472

2✔
5473
        // First, we'll attempt to look up the channel based on it's
2✔
5474
        // ChannelPoint.
2✔
5475
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
2✔
5476
        if err != nil {
2✔
5477
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5478
        }
×
5479

5480
        // From the channel, we can now get the pubkey of the peer, then use
5481
        // that to eventually get the chan closer.
5482
        peerPub := channel.IdentityPub.SerializeCompressed()
2✔
5483

2✔
5484
        // Now that we have the peer pub, we can look up the peer itself.
2✔
5485
        s.mu.RLock()
2✔
5486
        targetPeer, ok := s.peersByPub[string(peerPub)]
2✔
5487
        s.mu.RUnlock()
2✔
5488
        if !ok {
2✔
5489
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5490
                        "not online", chanPoint)
×
5491
        }
×
5492

5493
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
2✔
5494
                ctx, chanPoint, feeRate, deliveryScript,
2✔
5495
        )
2✔
5496
        if err != nil {
2✔
5497
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5498
                        "%w", err)
×
5499
        }
×
5500

5501
        return closeUpdates, nil
2✔
5502
}
5503

5504
// AttemptRBFCloseUpdate attempts to trigger a new RBF iteration for a co-op
5505
// close update. This route it to be used only if the target channel in question
5506
// is no longer active in the link. This can happen when we restart while we
5507
// already have done a single RBF co-op close iteration.
5508
func (s *server) AttemptRBFCloseUpdate(ctx context.Context,
5509
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
5510
        deliveryScript lnwire.DeliveryAddress) (*peer.CoopCloseUpdates, error) {
2✔
5511

2✔
5512
        // If the channel is present in the switch, then the request should flow
2✔
5513
        // through the switch instead.
2✔
5514
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
5515
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
2✔
5516
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5517
                        "invalid request", chanPoint)
×
5518
        }
×
5519

5520
        // At this point, we know that the channel isn't present in the link, so
5521
        // we'll check to see if we have an entry in the active chan closer map.
5522
        updates, err := s.attemptCoopRbfFeeBump(
2✔
5523
                ctx, chanPoint, feeRate, deliveryScript,
2✔
5524
        )
2✔
5525
        if err != nil {
2✔
5526
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5527
                        "ChannelPoint(%v)", chanPoint)
×
5528
        }
×
5529

5530
        return updates, nil
2✔
5531
}
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