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

lightningnetwork / lnd / 14204383128

01 Apr 2025 07:30PM UTC coverage: 58.637% (+0.02%) from 58.614%
14204383128

push

github

web-flow
Merge pull request #9667 from guggero/kvdb-update

mod: bump kvdb to latest tagged version v1.4.13

97150 of 165680 relevant lines covered (58.64%)

1.82 hits per line

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

63.91
/server.go
1
package lnd
2

3
import (
4
        "bytes"
5
        "context"
6
        "crypto/rand"
7
        "encoding/hex"
8
        "fmt"
9
        "math/big"
10
        prand "math/rand"
11
        "net"
12
        "strconv"
13
        "strings"
14
        "sync"
15
        "sync/atomic"
16
        "time"
17

18
        "github.com/btcsuite/btcd/btcec/v2"
19
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
20
        "github.com/btcsuite/btcd/btcutil"
21
        "github.com/btcsuite/btcd/chaincfg"
22
        "github.com/btcsuite/btcd/chaincfg/chainhash"
23
        "github.com/btcsuite/btcd/connmgr"
24
        "github.com/btcsuite/btcd/txscript"
25
        "github.com/btcsuite/btcd/wire"
26
        "github.com/go-errors/errors"
27
        sphinx "github.com/lightningnetwork/lightning-onion"
28
        "github.com/lightningnetwork/lnd/aliasmgr"
29
        "github.com/lightningnetwork/lnd/autopilot"
30
        "github.com/lightningnetwork/lnd/brontide"
31
        "github.com/lightningnetwork/lnd/chainio"
32
        "github.com/lightningnetwork/lnd/chainreg"
33
        "github.com/lightningnetwork/lnd/chanacceptor"
34
        "github.com/lightningnetwork/lnd/chanbackup"
35
        "github.com/lightningnetwork/lnd/chanfitness"
36
        "github.com/lightningnetwork/lnd/channeldb"
37
        "github.com/lightningnetwork/lnd/channelnotifier"
38
        "github.com/lightningnetwork/lnd/clock"
39
        "github.com/lightningnetwork/lnd/cluster"
40
        "github.com/lightningnetwork/lnd/contractcourt"
41
        "github.com/lightningnetwork/lnd/discovery"
42
        "github.com/lightningnetwork/lnd/feature"
43
        "github.com/lightningnetwork/lnd/fn/v2"
44
        "github.com/lightningnetwork/lnd/funding"
45
        "github.com/lightningnetwork/lnd/graph"
46
        graphdb "github.com/lightningnetwork/lnd/graph/db"
47
        "github.com/lightningnetwork/lnd/graph/db/models"
48
        "github.com/lightningnetwork/lnd/healthcheck"
49
        "github.com/lightningnetwork/lnd/htlcswitch"
50
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
51
        "github.com/lightningnetwork/lnd/input"
52
        "github.com/lightningnetwork/lnd/invoices"
53
        "github.com/lightningnetwork/lnd/keychain"
54
        "github.com/lightningnetwork/lnd/kvdb"
55
        "github.com/lightningnetwork/lnd/lncfg"
56
        "github.com/lightningnetwork/lnd/lnencrypt"
57
        "github.com/lightningnetwork/lnd/lnpeer"
58
        "github.com/lightningnetwork/lnd/lnrpc"
59
        "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
60
        "github.com/lightningnetwork/lnd/lnwallet"
61
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
62
        "github.com/lightningnetwork/lnd/lnwallet/chanfunding"
63
        "github.com/lightningnetwork/lnd/lnwallet/rpcwallet"
64
        "github.com/lightningnetwork/lnd/lnwire"
65
        "github.com/lightningnetwork/lnd/nat"
66
        "github.com/lightningnetwork/lnd/netann"
67
        "github.com/lightningnetwork/lnd/peer"
68
        "github.com/lightningnetwork/lnd/peernotifier"
69
        "github.com/lightningnetwork/lnd/pool"
70
        "github.com/lightningnetwork/lnd/queue"
71
        "github.com/lightningnetwork/lnd/routing"
72
        "github.com/lightningnetwork/lnd/routing/localchans"
73
        "github.com/lightningnetwork/lnd/routing/route"
74
        "github.com/lightningnetwork/lnd/subscribe"
75
        "github.com/lightningnetwork/lnd/sweep"
76
        "github.com/lightningnetwork/lnd/ticker"
77
        "github.com/lightningnetwork/lnd/tor"
78
        "github.com/lightningnetwork/lnd/walletunlocker"
79
        "github.com/lightningnetwork/lnd/watchtower/blob"
80
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
81
        "github.com/lightningnetwork/lnd/watchtower/wtpolicy"
82
        "github.com/lightningnetwork/lnd/watchtower/wtserver"
83
)
84

85
const (
86
        // defaultMinPeers is the minimum number of peers nodes should always be
87
        // connected to.
88
        defaultMinPeers = 3
89

90
        // defaultStableConnDuration is a floor under which all reconnection
91
        // attempts will apply exponential randomized backoff. Connections
92
        // durations exceeding this value will be eligible to have their
93
        // backoffs reduced.
94
        defaultStableConnDuration = 10 * time.Minute
95

96
        // numInstantInitReconnect specifies how many persistent peers we should
97
        // always attempt outbound connections to immediately. After this value
98
        // is surpassed, the remaining peers will be randomly delayed using
99
        // maxInitReconnectDelay.
100
        numInstantInitReconnect = 10
101

102
        // maxInitReconnectDelay specifies the maximum delay in seconds we will
103
        // apply in attempting to reconnect to persistent peers on startup. The
104
        // value used or a particular peer will be chosen between 0s and this
105
        // value.
106
        maxInitReconnectDelay = 30
107

108
        // multiAddrConnectionStagger is the number of seconds to wait between
109
        // attempting to a peer with each of its advertised addresses.
110
        multiAddrConnectionStagger = 10 * time.Second
111
)
112

113
var (
114
        // ErrPeerNotConnected signals that the server has no connection to the
115
        // given peer.
116
        ErrPeerNotConnected = errors.New("peer is not connected")
117

118
        // ErrServerNotActive indicates that the server has started but hasn't
119
        // fully finished the startup process.
120
        ErrServerNotActive = errors.New("server is still in the process of " +
121
                "starting")
122

123
        // ErrServerShuttingDown indicates that the server is in the process of
124
        // gracefully exiting.
125
        ErrServerShuttingDown = errors.New("server is shutting down")
126

127
        // MaxFundingAmount is a soft-limit of the maximum channel size
128
        // currently accepted within the Lightning Protocol. This is
129
        // defined in BOLT-0002, and serves as an initial precautionary limit
130
        // while implementations are battle tested in the real world.
131
        //
132
        // At the moment, this value depends on which chain is active. It is set
133
        // to the value under the Bitcoin chain as default.
134
        //
135
        // TODO(roasbeef): add command line param to modify.
136
        MaxFundingAmount = funding.MaxBtcFundingAmount
137

138
        // EndorsementExperimentEnd is the time after which nodes should stop
139
        // propagating experimental endorsement signals.
140
        //
141
        // Per blip04: January 1, 2026 12:00:00 AM UTC in unix seconds.
142
        EndorsementExperimentEnd = time.Unix(1767225600, 0)
143

144
        // ErrGossiperBan is one of the errors that can be returned when we
145
        // attempt to finalize a connection to a remote peer.
146
        ErrGossiperBan = errors.New("gossiper has banned remote's key")
147

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

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

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

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

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

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

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

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

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

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

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

212
        start sync.Once
213
        stop  sync.Once
214

215
        cfg *Config
216

217
        implCfg *ImplementationCfg
218

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

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

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

230
        chanStatusMgr *netann.ChanStatusManager
231

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

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

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

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

252
        mu sync.RWMutex
253

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

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

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

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

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

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

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

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

304
        cc *chainreg.ChainControl
305

306
        fundingMgr *funding.Manager
307

308
        graphDB *graphdb.ChannelGraph
309

310
        chanStateDB *channeldb.ChannelStateDB
311

312
        addrSource channeldb.AddrSource
313

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

318
        invoicesDB invoices.InvoiceDB
319

320
        aliasMgr *aliasmgr.Manager
321

322
        htlcSwitch *htlcswitch.Switch
323

324
        interceptableSwitch *htlcswitch.InterceptableSwitch
325

326
        invoices *invoices.InvoiceRegistry
327

328
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
329

330
        channelNotifier *channelnotifier.ChannelNotifier
331

332
        peerNotifier *peernotifier.PeerNotifier
333

334
        htlcNotifier *htlcswitch.HtlcNotifier
335

336
        witnessBeacon contractcourt.WitnessBeacon
337

338
        breachArbitrator *contractcourt.BreachArbitrator
339

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

343
        graphBuilder *graph.Builder
344

345
        chanRouter *routing.ChannelRouter
346

347
        controlTower routing.ControlTower
348

349
        authGossiper *discovery.AuthenticatedGossiper
350

351
        localChanMgr *localchans.Manager
352

353
        utxoNursery *contractcourt.UtxoNursery
354

355
        sweeper *sweep.UtxoSweeper
356

357
        chainArb *contractcourt.ChainArbitrator
358

359
        sphinx *hop.OnionProcessor
360

361
        towerClientMgr *wtclient.Manager
362

363
        connMgr *connmgr.ConnManager
364

365
        sigPool *lnwallet.SigPool
366

367
        writePool *pool.Write
368

369
        readPool *pool.Read
370

371
        tlsManager *TLSManager
372

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

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

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

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

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

395
        hostAnn *netann.HostAnnouncer
396

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

400
        customMessageServer *subscribe.Server
401

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

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

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

412
        quit chan struct{}
413

414
        wg sync.WaitGroup
415
}
416

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

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

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

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

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

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

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

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

472
                                        s.mu.Lock()
3✔
473

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

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

488
                                        s.mu.Unlock()
3✔
489

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

496
        return nil
3✔
497
}
498

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
689
                listenAddrs: listenAddrs,
3✔
690

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

3✔
695
                torController: torController,
3✔
696

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

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

3✔
713
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
714

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

3✔
717
                tlsManager: tlsManager,
3✔
718

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

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

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

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

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

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

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

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

3✔
760
                return nil
3✔
761
        }
762

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1213
        s.peerAccessMan = peerAccessMan
3✔
1214

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

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

3✔
1228
                                        // NOTE: The invoked callback here may
3✔
1229
                                        // receive a nil channel policy.
3✔
1230
                                        return cb(c, e)
3✔
1231
                                },
3✔
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(
3✔
1243
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1244
        )
3✔
1245
        if err != nil {
3✔
1246
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1247
                return nil, err
×
1248
        }
×
1249

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

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

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

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

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

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

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

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

3✔
1337
        //nolint:ll
3✔
1338
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1339
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1340
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1341
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1342
                NewSweepAddr: func() ([]byte, error) {
3✔
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 {
3✔
1354
                        for _, msg := range msgs {
6✔
1355
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1356
                                if err != nil {
3✔
1357
                                        return err
×
1358
                                }
×
1359
                        }
1360
                        return nil
3✔
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 {
3✔
1367

3✔
1368
                        return s.utxoNursery.IncubateOutputs(
3✔
1369
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1370
                                broadcastHeight, deadlineHeight,
3✔
1371
                        )
3✔
1372
                },
3✔
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 {
3✔
1380
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1381
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1382
                        return nil
3✔
1383
                },
3✔
1384
                IsOurAddress: cc.Wallet.IsOurAddress,
1385
                ContractBreach: func(chanPoint wire.OutPoint,
1386
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1387

3✔
1388
                        // processACK will handle the BreachArbitrator ACKing
3✔
1389
                        // the event.
3✔
1390
                        finalErr := make(chan error, 1)
3✔
1391
                        processACK := func(brarErr error) {
6✔
1392
                                if brarErr != nil {
3✔
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
3✔
1401
                        }
1402

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

3✔
1409
                        // Send the contract breach event to the
3✔
1410
                        // BreachArbitrator.
3✔
1411
                        select {
3✔
1412
                        case contractBreaches <- event:
3✔
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 {
3✔
1420
                        case err := <-finalErr:
3✔
1421
                                return err
3✔
1422
                        case <-s.quit:
×
1423
                                return ErrServerShuttingDown
×
1424
                        }
1425
                },
1426
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1427
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1428
                },
3✔
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 {
3✔
1445

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

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

1455
                        return &pc.Incoming
3✔
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
3✔
1464
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1465
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1466

3✔
1467
        var chanIDSeed [32]byte
3✔
1468
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
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) (
3✔
1475
                *models.ChannelEdgePolicy, error) {
6✔
1476

3✔
1477
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1478
                        scid.ToUint64(),
3✔
1479
                )
3✔
1480
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
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 {
3✔
1487
                        return nil, err
×
1488
                }
×
1489

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

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

1501
                if ourPolicy == nil {
3✔
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(
3✔
1507
                        false, false, scid.ToUint64(),
3✔
1508
                )
3✔
1509
                return ourPolicy, err
3✔
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
3✔
1516
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1517

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

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

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

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

3✔
1554
                        return s.genNodeAnnouncement(nil)
3✔
1555
                },
3✔
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 {
3✔
1564
                        // For large channels we increase the number
3✔
1565
                        // of confirmations we require for the
3✔
1566
                        // channel to be considered open. As it is
3✔
1567
                        // always the responder that gets to choose
3✔
1568
                        // value, the pushAmt is value being pushed
3✔
1569
                        // to us. This means we have more to lose
3✔
1570
                        // in the case this gets re-orged out, and
3✔
1571
                        // we will require more confirmations before
3✔
1572
                        // we consider it open.
3✔
1573

3✔
1574
                        // In case the user has explicitly specified
3✔
1575
                        // a default value for the number of
3✔
1576
                        // confirmations, we use it.
3✔
1577
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1578
                        if defaultConf != 0 {
6✔
1579
                                return defaultConf
3✔
1580
                        }
3✔
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 {
3✔
1607
                        // We scale the remote CSV delay (the time the
3✔
1608
                        // remote have to claim funds in case of a unilateral
3✔
1609
                        // close) linearly from minRemoteDelay blocks
3✔
1610
                        // for small channels, to maxRemoteDelay blocks
3✔
1611
                        // for channels of size MaxFundingAmount.
3✔
1612

3✔
1613
                        // In case the user has explicitly specified
3✔
1614
                        // a default value for the remote delay, we
3✔
1615
                        // use it.
3✔
1616
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1617
                        if defaultDelay > 0 {
6✔
1618
                                return defaultDelay
3✔
1619
                        }
3✔
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 {
3✔
1640

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

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

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

1675
                        return reserve
3✔
1676
                },
1677
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1678
                        // By default, we'll allow the remote peer to fully
3✔
1679
                        // utilize the full bandwidth of the channel, minus our
3✔
1680
                        // required reserve.
3✔
1681
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1682
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1683
                },
3✔
1684
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1685
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1686
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1687
                        }
3✔
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 {
3✔
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{
3✔
1721
                chanNotifier: s.channelNotifier,
3✔
1722
                addrs:        s.addrSource,
3✔
1723
        }
3✔
1724
        backupFile := chanbackup.NewMultiFile(
3✔
1725
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1726
        )
3✔
1727
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1728
                s.chanStateDB, s.addrSource,
3✔
1729
        )
3✔
1730
        if err != nil {
3✔
1731
                return nil, err
×
1732
        }
×
1733
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1734
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1735
        )
3✔
1736
        if err != nil {
3✔
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()
3✔
1743

3✔
1744
        // Create a channel event store which monitors all open channels.
3✔
1745
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1746
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1747
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1748
                },
3✔
1749
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1750
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1751
                },
3✔
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 {
6✔
1760
                policy := wtpolicy.DefaultPolicy()
3✔
1761
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1762

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

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

3✔
1771
                if err := policy.Validate(); err != nil {
3✔
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,
3✔
1778
                        netAddr *lnwire.NetAddress,
3✔
1779
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1780

3✔
1781
                        return brontide.Dial(
3✔
1782
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1783
                        )
3✔
1784
                }
3✔
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,
3✔
1790
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1791
                        channeldb.ChannelType, error) {
6✔
1792

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

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

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

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

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

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

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

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

1846
                                return addr.DeliveryAddress, nil
3✔
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 {
3✔
1858
                        return nil, err
×
1859
                }
×
1860
        }
1861

1862
        if len(cfg.ExternalHosts) != 0 {
3✔
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)
3✔
1891

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

3✔
1898
                // RESOLVE: We are actually partially accepting inbound
3✔
1899
                // connection requests when we call NewListener.
3✔
1900
                listeners[i], err = brontide.NewListener(
3✔
1901
                        nodeKeyECDH, listenAddr.String(),
3✔
1902
                        s.peerAccessMan.checkIncomingConnBanScore,
3✔
1903
                )
3✔
1904
                if err != nil {
3✔
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{
3✔
1913
                Listeners:      listeners,
3✔
1914
                OnAccept:       s.InboundPeerConnected,
3✔
1915
                RetryDuration:  time.Second * 5,
3✔
1916
                TargetOutbound: 100,
3✔
1917
                Dial: noiseDial(
3✔
1918
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1919
                ),
3✔
1920
                OnConnection: s.OutboundPeerConnected,
3✔
1921
        })
3✔
1922
        if err != nil {
3✔
1923
                return nil, err
×
1924
        }
×
1925
        s.connMgr = cmgr
3✔
1926

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

3✔
1930
        return s, nil
3✔
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) {
3✔
1936
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1937

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

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

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

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

1959
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
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() {
3✔
1971
        // In this queue, when a new block arrives, it will be received and
3✔
1972
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
1973
        consumers := []chainio.Consumer{
3✔
1974
                s.chainArb,
3✔
1975
                s.sweeper,
3✔
1976
                s.txPublisher,
3✔
1977
        }
3✔
1978
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
1979
}
3✔
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) {
3✔
1986

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

1992
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
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) {
3✔
2007

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

×
2013
                chainBackendAttempts = 0
×
2014
        }
×
2015

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

3✔
2025
        diskCheck := healthcheck.NewObservation(
3✔
2026
                "disk space",
3✔
2027
                func() error {
3✔
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(
3✔
2052
                "tls",
3✔
2053
                func() error {
3✔
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{
3✔
2076
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2077
        }
3✔
2078

3✔
2079
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2080
        if s.torController != nil {
3✔
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 {
6✔
2100
                // Because we have two cascading timeouts here, we need to add
3✔
2101
                // some slack to the "outer" one of them in case the "inner"
3✔
2102
                // returns exactly on time.
3✔
2103
                overhead := time.Millisecond * 10
3✔
2104

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

3✔
2110
                                // For the health check we might to be even
3✔
2111
                                // stricter than the initial/normal connect, so
3✔
2112
                                // we use the health check timeout here.
3✔
2113
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2114
                        ),
3✔
2115
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2116
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2117
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2118
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2119
                )
3✔
2120
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2121
        }
3✔
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 {
3✔
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(
3✔
2169
                &healthcheck.Config{
3✔
2170
                        Checks:   checks,
3✔
2171
                        Shutdown: srvrLog.Criticalf,
3✔
2172
                },
3✔
2173
        )
3✔
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 {
3✔
2179
        return atomic.LoadInt32(&s.active) != 0
3✔
2180
}
3✔
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 {
3✔
2191
        return append(c, cleanup)
3✔
2192
}
3✔
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.Errorf("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 {
3✔
2210
        var startErr error
3✔
2211

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

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

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

2223
        return startErr
3✔
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 {
3✔
2232
        // Get the current blockbeat.
3✔
2233
        beat, err := s.getStartingBeat()
3✔
2234
        if err != nil {
3✔
2235
                return err
×
2236
        }
×
2237

2238
        var startErr error
3✔
2239

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

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

2252
                if s.hostAnn != nil {
3✔
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 {
6✔
2261
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2262
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
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)
3✔
2274
                if err := s.sigPool.Start(); err != nil {
3✔
2275
                        startErr = err
×
2276
                        return
×
2277
                }
×
2278

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

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

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

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

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

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

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

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

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

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

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

2349
                cleanup = cleanup.add(s.fundingMgr.Stop)
3✔
2350
                if err := s.fundingMgr.Start(); err != nil {
3✔
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)
3✔
2359
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2360
                        startErr = err
×
2361
                        return
×
2362
                }
×
2363

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

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

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

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

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

2394
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2395
                if err := s.chanRouter.Start(); err != nil {
3✔
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)
3✔
2402
                if err := s.authGossiper.Start(); err != nil {
3✔
2403
                        startErr = err
×
2404
                        return
×
2405
                }
×
2406

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

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

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

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

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

3✔
2437
                // Before we start the connMgr, we'll check to see if we have
3✔
2438
                // any backups to recover. We do this now as we want to ensure
3✔
2439
                // that have all the information we need to handle channel
3✔
2440
                // recovery _before_ we even accept connections from any peers.
3✔
2441
                chanRestorer := &chanDBRestorer{
3✔
2442
                        db:         s.chanStateDB,
3✔
2443
                        secretKeys: s.cc.KeyRing,
3✔
2444
                        chainArb:   s.chainArb,
3✔
2445
                }
3✔
2446
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
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 {
6✔
2458
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2459
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2460
                                s.cc.KeyRing, chanRestorer, s,
3✔
2461
                        )
3✔
2462
                        if err != nil {
3✔
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)
3✔
2473
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2474
                        startErr = err
×
2475
                        return
×
2476
                }
×
2477

2478
                if s.torController != nil {
3✔
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 {
3✔
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 {
3✔
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
                //
2502
                // TODO(yy): move the log into the connMgr's `Start` method.
2503
                srvrLog.Info("connMgr starting...")
3✔
2504
                s.connMgr.Start()
3✔
2505
                srvrLog.Debug("connMgr started")
3✔
2506

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

2526
                        peerAddr := &lnwire.NetAddress{
3✔
2527
                                IdentityKey: parsedPubkey,
3✔
2528
                                Address:     addr,
3✔
2529
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2530
                        }
3✔
2531

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

2544
                // Subscribe to NodeAnnouncements that advertise new addresses
2545
                // our persistent peers.
2546
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2547
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2548
                                "addr: %v", err)
×
2549

×
2550
                        startErr = err
×
2551
                        return
×
2552
                }
×
2553

2554
                // With all the relevant sub-systems started, we'll now attempt
2555
                // to establish persistent connections to our direct channel
2556
                // collaborators within the network. Before doing so however,
2557
                // we'll prune our set of link nodes found within the database
2558
                // to ensure we don't reconnect to any nodes we no longer have
2559
                // open channels with.
2560
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2561
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2562

×
2563
                        startErr = err
×
2564
                        return
×
2565
                }
×
2566

2567
                if err := s.establishPersistentConnections(); err != nil {
3✔
2568
                        srvrLog.Errorf("Failed to establish persistent "+
×
2569
                                "connections: %v", err)
×
2570
                }
×
2571

2572
                // setSeedList is a helper function that turns multiple DNS seed
2573
                // server tuples from the command line or config file into the
2574
                // data structure we need and does a basic formal sanity check
2575
                // in the process.
2576
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2577
                        if len(tuples) == 0 {
×
2578
                                return
×
2579
                        }
×
2580

2581
                        result := make([][2]string, len(tuples))
×
2582
                        for idx, tuple := range tuples {
×
2583
                                tuple = strings.TrimSpace(tuple)
×
2584
                                if len(tuple) == 0 {
×
2585
                                        return
×
2586
                                }
×
2587

2588
                                servers := strings.Split(tuple, ",")
×
2589
                                if len(servers) > 2 || len(servers) == 0 {
×
2590
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2591
                                                "seed tuple: %v", servers)
×
2592
                                        return
×
2593
                                }
×
2594

2595
                                copy(result[idx][:], servers)
×
2596
                        }
2597

2598
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2599
                }
2600

2601
                // Let users overwrite the DNS seed nodes. We only allow them
2602
                // for bitcoin mainnet/testnet/signet.
2603
                if s.cfg.Bitcoin.MainNet {
3✔
2604
                        setSeedList(
×
2605
                                s.cfg.Bitcoin.DNSSeeds,
×
2606
                                chainreg.BitcoinMainnetGenesis,
×
2607
                        )
×
2608
                }
×
2609
                if s.cfg.Bitcoin.TestNet3 {
3✔
2610
                        setSeedList(
×
2611
                                s.cfg.Bitcoin.DNSSeeds,
×
2612
                                chainreg.BitcoinTestnetGenesis,
×
2613
                        )
×
2614
                }
×
2615
                if s.cfg.Bitcoin.TestNet4 {
3✔
2616
                        setSeedList(
×
2617
                                s.cfg.Bitcoin.DNSSeeds,
×
2618
                                chainreg.BitcoinTestnet4Genesis,
×
2619
                        )
×
2620
                }
×
2621
                if s.cfg.Bitcoin.SigNet {
3✔
2622
                        setSeedList(
×
2623
                                s.cfg.Bitcoin.DNSSeeds,
×
2624
                                chainreg.BitcoinSignetGenesis,
×
2625
                        )
×
2626
                }
×
2627

2628
                // If network bootstrapping hasn't been disabled, then we'll
2629
                // configure the set of active bootstrappers, and launch a
2630
                // dedicated goroutine to maintain a set of persistent
2631
                // connections.
2632
                if shouldPeerBootstrap(s.cfg) {
3✔
2633
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2634
                        if err != nil {
×
2635
                                startErr = err
×
2636
                                return
×
2637
                        }
×
2638

2639
                        s.wg.Add(1)
×
2640
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2641
                } else {
3✔
2642
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2643
                }
3✔
2644

2645
                // Start the blockbeat after all other subsystems have been
2646
                // started so they are ready to receive new blocks.
2647
                cleanup = cleanup.add(func() error {
3✔
2648
                        s.blockbeatDispatcher.Stop()
×
2649
                        return nil
×
2650
                })
×
2651
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2652
                        startErr = err
×
2653
                        return
×
2654
                }
×
2655

2656
                // Set the active flag now that we've completed the full
2657
                // startup.
2658
                atomic.StoreInt32(&s.active, 1)
3✔
2659
        })
2660

2661
        if startErr != nil {
3✔
2662
                cleanup.run()
×
2663
        }
×
2664
        return startErr
3✔
2665
}
2666

2667
// Stop gracefully shutsdown the main daemon server. This function will signal
2668
// any active goroutines, or helper objects to exit, then blocks until they've
2669
// all successfully exited. Additionally, any/all listeners are closed.
2670
// NOTE: This function is safe for concurrent access.
2671
func (s *server) Stop() error {
3✔
2672
        s.stop.Do(func() {
6✔
2673
                atomic.StoreInt32(&s.stopping, 1)
3✔
2674

3✔
2675
                close(s.quit)
3✔
2676

3✔
2677
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2678
                s.connMgr.Stop()
3✔
2679

3✔
2680
                // Stop dispatching blocks to other systems immediately.
3✔
2681
                s.blockbeatDispatcher.Stop()
3✔
2682

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

2745
                // Update channel.backup file. Make sure to do it before
2746
                // stopping chanSubSwapper.
2747
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2748
                        s.chanStateDB, s.addrSource,
3✔
2749
                )
3✔
2750
                if err != nil {
3✔
2751
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2752
                                err)
×
2753
                } else {
3✔
2754
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2755
                        if err != nil {
6✔
2756
                                srvrLog.Warnf("Manual update of channel "+
3✔
2757
                                        "backup failed: %v", err)
3✔
2758
                        }
3✔
2759
                }
2760

2761
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2762
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2763
                }
×
2764
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2765
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2766
                }
×
2767
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2768
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2769
                                err)
×
2770
                }
×
2771
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2772
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2773
                                err)
×
2774
                }
×
2775
                s.missionController.StopStoreTickers()
3✔
2776

3✔
2777
                // Disconnect from each active peers to ensure that
3✔
2778
                // peerTerminationWatchers signal completion to each peer.
3✔
2779
                for _, peer := range s.Peers() {
6✔
2780
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2781
                        if err != nil {
3✔
2782
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2783
                                        "received error: %v", peer.IdentityKey(),
×
2784
                                        err,
×
2785
                                )
×
2786
                        }
×
2787
                }
2788

2789
                // Now that all connections have been torn down, stop the tower
2790
                // client which will reliably flush all queued states to the
2791
                // tower. If this is halted for any reason, the force quit timer
2792
                // will kick in and abort to allow this method to return.
2793
                if s.towerClientMgr != nil {
6✔
2794
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2795
                                srvrLog.Warnf("Unable to shut down tower "+
×
2796
                                        "client manager: %v", err)
×
2797
                        }
×
2798
                }
2799

2800
                if s.hostAnn != nil {
3✔
2801
                        if err := s.hostAnn.Stop(); err != nil {
×
2802
                                srvrLog.Warnf("unable to shut down host "+
×
2803
                                        "annoucner: %v", err)
×
2804
                        }
×
2805
                }
2806

2807
                if s.livenessMonitor != nil {
6✔
2808
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2809
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2810
                                        "monitor: %v", err)
×
2811
                        }
×
2812
                }
2813

2814
                // Wait for all lingering goroutines to quit.
2815
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2816
                s.wg.Wait()
3✔
2817

3✔
2818
                srvrLog.Debug("Stopping buffer pools...")
3✔
2819
                s.sigPool.Stop()
3✔
2820
                s.writePool.Stop()
3✔
2821
                s.readPool.Stop()
3✔
2822
        })
2823

2824
        return nil
3✔
2825
}
2826

2827
// Stopped returns true if the server has been instructed to shutdown.
2828
// NOTE: This function is safe for concurrent access.
2829
func (s *server) Stopped() bool {
3✔
2830
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2831
}
3✔
2832

2833
// configurePortForwarding attempts to set up port forwarding for the different
2834
// ports that the server will be listening on.
2835
//
2836
// NOTE: This should only be used when using some kind of NAT traversal to
2837
// automatically set up forwarding rules.
2838
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2839
        ip, err := s.natTraversal.ExternalIP()
×
2840
        if err != nil {
×
2841
                return nil, err
×
2842
        }
×
2843
        s.lastDetectedIP = ip
×
2844

×
2845
        externalIPs := make([]string, 0, len(ports))
×
2846
        for _, port := range ports {
×
2847
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2848
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2849
                        continue
×
2850
                }
2851

2852
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2853
                externalIPs = append(externalIPs, hostIP)
×
2854
        }
2855

2856
        return externalIPs, nil
×
2857
}
2858

2859
// removePortForwarding attempts to clear the forwarding rules for the different
2860
// ports the server is currently listening on.
2861
//
2862
// NOTE: This should only be used when using some kind of NAT traversal to
2863
// automatically set up forwarding rules.
2864
func (s *server) removePortForwarding() {
×
2865
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2866
        for _, port := range forwardedPorts {
×
2867
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2868
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2869
                                "port %d: %v", port, err)
×
2870
                }
×
2871
        }
2872
}
2873

2874
// watchExternalIP continuously checks for an updated external IP address every
2875
// 15 minutes. Once a new IP address has been detected, it will automatically
2876
// handle port forwarding rules and send updated node announcements to the
2877
// currently connected peers.
2878
//
2879
// NOTE: This MUST be run as a goroutine.
2880
func (s *server) watchExternalIP() {
×
2881
        defer s.wg.Done()
×
2882

×
2883
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2884
        // up by the server.
×
2885
        defer s.removePortForwarding()
×
2886

×
2887
        // Keep track of the external IPs set by the user to avoid replacing
×
2888
        // them when detecting a new IP.
×
2889
        ipsSetByUser := make(map[string]struct{})
×
2890
        for _, ip := range s.cfg.ExternalIPs {
×
2891
                ipsSetByUser[ip.String()] = struct{}{}
×
2892
        }
×
2893

2894
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2895

×
2896
        ticker := time.NewTicker(15 * time.Minute)
×
2897
        defer ticker.Stop()
×
2898
out:
×
2899
        for {
×
2900
                select {
×
2901
                case <-ticker.C:
×
2902
                        // We'll start off by making sure a new IP address has
×
2903
                        // been detected.
×
2904
                        ip, err := s.natTraversal.ExternalIP()
×
2905
                        if err != nil {
×
2906
                                srvrLog.Debugf("Unable to retrieve the "+
×
2907
                                        "external IP address: %v", err)
×
2908
                                continue
×
2909
                        }
2910

2911
                        // Periodically renew the NAT port forwarding.
2912
                        for _, port := range forwardedPorts {
×
2913
                                err := s.natTraversal.AddPortMapping(port)
×
2914
                                if err != nil {
×
2915
                                        srvrLog.Warnf("Unable to automatically "+
×
2916
                                                "re-create port forwarding using %s: %v",
×
2917
                                                s.natTraversal.Name(), err)
×
2918
                                } else {
×
2919
                                        srvrLog.Debugf("Automatically re-created "+
×
2920
                                                "forwarding for port %d using %s to "+
×
2921
                                                "advertise external IP",
×
2922
                                                port, s.natTraversal.Name())
×
2923
                                }
×
2924
                        }
2925

2926
                        if ip.Equal(s.lastDetectedIP) {
×
2927
                                continue
×
2928
                        }
2929

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

×
2932
                        // Next, we'll craft the new addresses that will be
×
2933
                        // included in the new node announcement and advertised
×
2934
                        // to the network. Each address will consist of the new
×
2935
                        // IP detected and one of the currently advertised
×
2936
                        // ports.
×
2937
                        var newAddrs []net.Addr
×
2938
                        for _, port := range forwardedPorts {
×
2939
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2940
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2941
                                if err != nil {
×
2942
                                        srvrLog.Debugf("Unable to resolve "+
×
2943
                                                "host %v: %v", addr, err)
×
2944
                                        continue
×
2945
                                }
2946

2947
                                newAddrs = append(newAddrs, addr)
×
2948
                        }
2949

2950
                        // Skip the update if we weren't able to resolve any of
2951
                        // the new addresses.
2952
                        if len(newAddrs) == 0 {
×
2953
                                srvrLog.Debug("Skipping node announcement " +
×
2954
                                        "update due to not being able to " +
×
2955
                                        "resolve any new addresses")
×
2956
                                continue
×
2957
                        }
2958

2959
                        // Now, we'll need to update the addresses in our node's
2960
                        // announcement in order to propagate the update
2961
                        // throughout the network. We'll only include addresses
2962
                        // that have a different IP from the previous one, as
2963
                        // the previous IP is no longer valid.
2964
                        currentNodeAnn := s.getNodeAnnouncement()
×
2965

×
2966
                        for _, addr := range currentNodeAnn.Addresses {
×
2967
                                host, _, err := net.SplitHostPort(addr.String())
×
2968
                                if err != nil {
×
2969
                                        srvrLog.Debugf("Unable to determine "+
×
2970
                                                "host from address %v: %v",
×
2971
                                                addr, err)
×
2972
                                        continue
×
2973
                                }
2974

2975
                                // We'll also make sure to include external IPs
2976
                                // set manually by the user.
2977
                                _, setByUser := ipsSetByUser[addr.String()]
×
2978
                                if setByUser || host != s.lastDetectedIP.String() {
×
2979
                                        newAddrs = append(newAddrs, addr)
×
2980
                                }
×
2981
                        }
2982

2983
                        // Then, we'll generate a new timestamped node
2984
                        // announcement with the updated addresses and broadcast
2985
                        // it to our peers.
2986
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2987
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2988
                        )
×
2989
                        if err != nil {
×
2990
                                srvrLog.Debugf("Unable to generate new node "+
×
2991
                                        "announcement: %v", err)
×
2992
                                continue
×
2993
                        }
2994

2995
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2996
                        if err != nil {
×
2997
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2998
                                        "announcement to peers: %v", err)
×
2999
                                continue
×
3000
                        }
3001

3002
                        // Finally, update the last IP seen to the current one.
3003
                        s.lastDetectedIP = ip
×
3004
                case <-s.quit:
×
3005
                        break out
×
3006
                }
3007
        }
3008
}
3009

3010
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3011
// based on the server, and currently active bootstrap mechanisms as defined
3012
// within the current configuration.
3013
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
3014
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
3015

×
3016
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
3017

×
3018
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
3019
        // this can be used by default if we've already partially seeded the
×
3020
        // network.
×
3021
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
3022
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
3023
        if err != nil {
×
3024
                return nil, err
×
3025
        }
×
3026
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
3027

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

×
3033
                // If we have a set of DNS seeds for this chain, then we'll add
×
3034
                // it as an additional bootstrapping source.
×
3035
                if ok {
×
3036
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3037
                                "seeds: %v", dnsSeeds)
×
3038

×
3039
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3040
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3041
                        )
×
3042
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3043
                }
×
3044
        }
3045

3046
        return bootStrappers, nil
×
3047
}
3048

3049
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3050
// needs to ignore, which is made of three parts,
3051
//   - the node itself needs to be skipped as it doesn't make sense to connect
3052
//     to itself.
3053
//   - the peers that already have connections with, as in s.peersByPub.
3054
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3055
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
3056
        s.mu.RLock()
×
3057
        defer s.mu.RUnlock()
×
3058

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

×
3061
        // We should ignore ourselves from bootstrapping.
×
3062
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
3063
        ignore[selfKey] = struct{}{}
×
3064

×
3065
        // Ignore all connected peers.
×
3066
        for _, peer := range s.peersByPub {
×
3067
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3068
                ignore[nID] = struct{}{}
×
3069
        }
×
3070

3071
        // Ignore all persistent peers as they have a dedicated reconnecting
3072
        // process.
3073
        for pubKeyStr := range s.persistentPeers {
×
3074
                var nID autopilot.NodeID
×
3075
                copy(nID[:], []byte(pubKeyStr))
×
3076
                ignore[nID] = struct{}{}
×
3077
        }
×
3078

3079
        return ignore
×
3080
}
3081

3082
// peerBootstrapper is a goroutine which is tasked with attempting to establish
3083
// and maintain a target minimum number of outbound connections. With this
3084
// invariant, we ensure that our node is connected to a diverse set of peers
3085
// and that nodes newly joining the network receive an up to date network view
3086
// as soon as possible.
3087
func (s *server) peerBootstrapper(numTargetPeers uint32,
3088
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3089

×
3090
        defer s.wg.Done()
×
3091

×
3092
        // Before we continue, init the ignore peers map.
×
3093
        ignoreList := s.createBootstrapIgnorePeers()
×
3094

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

×
3099
        // Once done, we'll attempt to maintain our target minimum number of
×
3100
        // peers.
×
3101
        //
×
3102
        // We'll use a 15 second backoff, and double the time every time an
×
3103
        // epoch fails up to a ceiling.
×
3104
        backOff := time.Second * 15
×
3105

×
3106
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
3107
        // see if we've reached our minimum number of peers.
×
3108
        sampleTicker := time.NewTicker(backOff)
×
3109
        defer sampleTicker.Stop()
×
3110

×
3111
        // We'll use the number of attempts and errors to determine if we need
×
3112
        // to increase the time between discovery epochs.
×
3113
        var epochErrors uint32 // To be used atomically.
×
3114
        var epochAttempts uint32
×
3115

×
3116
        for {
×
3117
                select {
×
3118
                // The ticker has just woken us up, so we'll need to check if
3119
                // we need to attempt to connect our to any more peers.
3120
                case <-sampleTicker.C:
×
3121
                        // Obtain the current number of peers, so we can gauge
×
3122
                        // if we need to sample more peers or not.
×
3123
                        s.mu.RLock()
×
3124
                        numActivePeers := uint32(len(s.peersByPub))
×
3125
                        s.mu.RUnlock()
×
3126

×
3127
                        // If we have enough peers, then we can loop back
×
3128
                        // around to the next round as we're done here.
×
3129
                        if numActivePeers >= numTargetPeers {
×
3130
                                continue
×
3131
                        }
3132

3133
                        // If all of our attempts failed during this last back
3134
                        // off period, then will increase our backoff to 5
3135
                        // minute ceiling to avoid an excessive number of
3136
                        // queries
3137
                        //
3138
                        // TODO(roasbeef): add reverse policy too?
3139

3140
                        if epochAttempts > 0 &&
×
3141
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3142

×
3143
                                sampleTicker.Stop()
×
3144

×
3145
                                backOff *= 2
×
3146
                                if backOff > bootstrapBackOffCeiling {
×
3147
                                        backOff = bootstrapBackOffCeiling
×
3148
                                }
×
3149

3150
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3151
                                        "%v", backOff)
×
3152
                                sampleTicker = time.NewTicker(backOff)
×
3153
                                continue
×
3154
                        }
3155

3156
                        atomic.StoreUint32(&epochErrors, 0)
×
3157
                        epochAttempts = 0
×
3158

×
3159
                        // Since we know need more peers, we'll compute the
×
3160
                        // exact number we need to reach our threshold.
×
3161
                        numNeeded := numTargetPeers - numActivePeers
×
3162

×
3163
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3164
                                "peers", numNeeded)
×
3165

×
3166
                        // With the number of peers we need calculated, we'll
×
3167
                        // query the network bootstrappers to sample a set of
×
3168
                        // random addrs for us.
×
3169
                        //
×
3170
                        // Before we continue, get a copy of the ignore peers
×
3171
                        // map.
×
3172
                        ignoreList = s.createBootstrapIgnorePeers()
×
3173

×
3174
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3175
                                ignoreList, numNeeded*2, bootstrappers...,
×
3176
                        )
×
3177
                        if err != nil {
×
3178
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3179
                                        "peers: %v", err)
×
3180
                                continue
×
3181
                        }
3182

3183
                        // Finally, we'll launch a new goroutine for each
3184
                        // prospective peer candidates.
3185
                        for _, addr := range peerAddrs {
×
3186
                                epochAttempts++
×
3187

×
3188
                                go func(a *lnwire.NetAddress) {
×
3189
                                        // TODO(roasbeef): can do AS, subnet,
×
3190
                                        // country diversity, etc
×
3191
                                        errChan := make(chan error, 1)
×
3192
                                        s.connectToPeer(
×
3193
                                                a, errChan,
×
3194
                                                s.cfg.ConnectionTimeout,
×
3195
                                        )
×
3196
                                        select {
×
3197
                                        case err := <-errChan:
×
3198
                                                if err == nil {
×
3199
                                                        return
×
3200
                                                }
×
3201

3202
                                                srvrLog.Errorf("Unable to "+
×
3203
                                                        "connect to %v: %v",
×
3204
                                                        a, err)
×
3205
                                                atomic.AddUint32(&epochErrors, 1)
×
3206
                                        case <-s.quit:
×
3207
                                        }
3208
                                }(addr)
3209
                        }
3210
                case <-s.quit:
×
3211
                        return
×
3212
                }
3213
        }
3214
}
3215

3216
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3217
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3218
// query back off each time we encounter a failure.
3219
const bootstrapBackOffCeiling = time.Minute * 5
3220

3221
// initialPeerBootstrap attempts to continuously connect to peers on startup
3222
// until the target number of peers has been reached. This ensures that nodes
3223
// receive an up to date network view as soon as possible.
3224
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
3225
        numTargetPeers uint32,
3226
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3227

×
3228
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3229
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3230

×
3231
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3232
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3233
        var delaySignal <-chan time.Time
×
3234
        delayTime := time.Second * 2
×
3235

×
3236
        // As want to be more aggressive, we'll use a lower back off celling
×
3237
        // then the main peer bootstrap logic.
×
3238
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3239

×
3240
        for attempts := 0; ; attempts++ {
×
3241
                // Check if the server has been requested to shut down in order
×
3242
                // to prevent blocking.
×
3243
                if s.Stopped() {
×
3244
                        return
×
3245
                }
×
3246

3247
                // We can exit our aggressive initial peer bootstrapping stage
3248
                // if we've reached out target number of peers.
3249
                s.mu.RLock()
×
3250
                numActivePeers := uint32(len(s.peersByPub))
×
3251
                s.mu.RUnlock()
×
3252

×
3253
                if numActivePeers >= numTargetPeers {
×
3254
                        return
×
3255
                }
×
3256

3257
                if attempts > 0 {
×
3258
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3259
                                "bootstrap peers (attempt #%v)", delayTime,
×
3260
                                attempts)
×
3261

×
3262
                        // We've completed at least one iterating and haven't
×
3263
                        // finished, so we'll start to insert a delay period
×
3264
                        // between each attempt.
×
3265
                        delaySignal = time.After(delayTime)
×
3266
                        select {
×
3267
                        case <-delaySignal:
×
3268
                        case <-s.quit:
×
3269
                                return
×
3270
                        }
3271

3272
                        // After our delay, we'll double the time we wait up to
3273
                        // the max back off period.
3274
                        delayTime *= 2
×
3275
                        if delayTime > backOffCeiling {
×
3276
                                delayTime = backOffCeiling
×
3277
                        }
×
3278
                }
3279

3280
                // Otherwise, we'll request for the remaining number of peers
3281
                // in order to reach our target.
3282
                peersNeeded := numTargetPeers - numActivePeers
×
3283
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3284
                        ignore, peersNeeded, bootstrappers...,
×
3285
                )
×
3286
                if err != nil {
×
3287
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3288
                                "peers: %v", err)
×
3289
                        continue
×
3290
                }
3291

3292
                // Then, we'll attempt to establish a connection to the
3293
                // different peer addresses retrieved by our bootstrappers.
3294
                var wg sync.WaitGroup
×
3295
                for _, bootstrapAddr := range bootstrapAddrs {
×
3296
                        wg.Add(1)
×
3297
                        go func(addr *lnwire.NetAddress) {
×
3298
                                defer wg.Done()
×
3299

×
3300
                                errChan := make(chan error, 1)
×
3301
                                go s.connectToPeer(
×
3302
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3303
                                )
×
3304

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

3328
                wg.Wait()
×
3329
        }
3330
}
3331

3332
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3333
// order to listen for inbound connections over Tor.
3334
func (s *server) createNewHiddenService() error {
×
3335
        // Determine the different ports the server is listening on. The onion
×
3336
        // service's virtual port will map to these ports and one will be picked
×
3337
        // at random when the onion service is being accessed.
×
3338
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3339
        for _, listenAddr := range s.listenAddrs {
×
3340
                port := listenAddr.(*net.TCPAddr).Port
×
3341
                listenPorts = append(listenPorts, port)
×
3342
        }
×
3343

3344
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3345
        if err != nil {
×
3346
                return err
×
3347
        }
×
3348

3349
        // Once the port mapping has been set, we can go ahead and automatically
3350
        // create our onion service. The service's private key will be saved to
3351
        // disk in order to regain access to this service when restarting `lnd`.
3352
        onionCfg := tor.AddOnionConfig{
×
3353
                VirtualPort: defaultPeerPort,
×
3354
                TargetPorts: listenPorts,
×
3355
                Store: tor.NewOnionFile(
×
3356
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3357
                        encrypter,
×
3358
                ),
×
3359
        }
×
3360

×
3361
        switch {
×
3362
        case s.cfg.Tor.V2:
×
3363
                onionCfg.Type = tor.V2
×
3364
        case s.cfg.Tor.V3:
×
3365
                onionCfg.Type = tor.V3
×
3366
        }
3367

3368
        addr, err := s.torController.AddOnion(onionCfg)
×
3369
        if err != nil {
×
3370
                return err
×
3371
        }
×
3372

3373
        // Now that the onion service has been created, we'll add the onion
3374
        // address it can be reached at to our list of advertised addresses.
3375
        newNodeAnn, err := s.genNodeAnnouncement(
×
3376
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3377
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3378
                },
×
3379
        )
3380
        if err != nil {
×
3381
                return fmt.Errorf("unable to generate new node "+
×
3382
                        "announcement: %v", err)
×
3383
        }
×
3384

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

3403
        return nil
×
3404
}
3405

3406
// findChannel finds a channel given a public key and ChannelID. It is an
3407
// optimization that is quicker than seeking for a channel given only the
3408
// ChannelID.
3409
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3410
        *channeldb.OpenChannel, error) {
3✔
3411

3✔
3412
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3413
        if err != nil {
3✔
3414
                return nil, err
×
3415
        }
×
3416

3417
        for _, channel := range nodeChans {
6✔
3418
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3419
                        return channel, nil
3✔
3420
                }
3✔
3421
        }
3422

3423
        return nil, fmt.Errorf("unable to find channel")
3✔
3424
}
3425

3426
// getNodeAnnouncement fetches the current, fully signed node announcement.
3427
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3428
        s.mu.Lock()
3✔
3429
        defer s.mu.Unlock()
3✔
3430

3✔
3431
        return *s.currentNodeAnn
3✔
3432
}
3✔
3433

3434
// genNodeAnnouncement generates and returns the current fully signed node
3435
// announcement. The time stamp of the announcement will be updated in order
3436
// to ensure it propagates through the network.
3437
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3438
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3439

3✔
3440
        s.mu.Lock()
3✔
3441
        defer s.mu.Unlock()
3✔
3442

3✔
3443
        // First, try to update our feature manager with the updated set of
3✔
3444
        // features.
3✔
3445
        if features != nil {
6✔
3446
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3447
                        feature.SetNodeAnn: features,
3✔
3448
                }
3✔
3449
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3450
                if err != nil {
6✔
3451
                        return lnwire.NodeAnnouncement{}, err
3✔
3452
                }
3✔
3453

3454
                // If we could successfully update our feature manager, add
3455
                // an update modifier to include these new features to our
3456
                // set.
3457
                modifiers = append(
3✔
3458
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3459
                )
3✔
3460
        }
3461

3462
        // Always update the timestamp when refreshing to ensure the update
3463
        // propagates.
3464
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3465

3✔
3466
        // Apply the requested changes to the node announcement.
3✔
3467
        for _, modifier := range modifiers {
6✔
3468
                modifier(s.currentNodeAnn)
3✔
3469
        }
3✔
3470

3471
        // Sign a new update after applying all of the passed modifiers.
3472
        err := netann.SignNodeAnnouncement(
3✔
3473
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
3✔
3474
        )
3✔
3475
        if err != nil {
3✔
3476
                return lnwire.NodeAnnouncement{}, err
×
3477
        }
×
3478

3479
        return *s.currentNodeAnn, nil
3✔
3480
}
3481

3482
// updateAndBroadcastSelfNode generates a new node announcement
3483
// applying the giving modifiers and updating the time stamp
3484
// to ensure it propagates through the network. Then it broadcasts
3485
// it to the network.
3486
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
3487
        modifiers ...netann.NodeAnnModifier) error {
3✔
3488

3✔
3489
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3490
        if err != nil {
6✔
3491
                return fmt.Errorf("unable to generate new node "+
3✔
3492
                        "announcement: %v", err)
3✔
3493
        }
3✔
3494

3495
        // Update the on-disk version of our announcement.
3496
        // Load and modify self node istead of creating anew instance so we
3497
        // don't risk overwriting any existing values.
3498
        selfNode, err := s.graphDB.SourceNode()
3✔
3499
        if err != nil {
3✔
3500
                return fmt.Errorf("unable to get current source node: %w", err)
×
3501
        }
×
3502

3503
        selfNode.HaveNodeAnnouncement = true
3✔
3504
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3505
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3506
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3507
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3508
        selfNode.Color = newNodeAnn.RGBColor
3✔
3509
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3510

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

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

3517
        // Finally, propagate it to the nodes in the network.
3518
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3519
        if err != nil {
3✔
3520
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3521
                        "announcement to peers: %v", err)
×
3522
                return err
×
3523
        }
×
3524

3525
        return nil
3✔
3526
}
3527

3528
type nodeAddresses struct {
3529
        pubKey    *btcec.PublicKey
3530
        addresses []net.Addr
3531
}
3532

3533
// establishPersistentConnections attempts to establish persistent connections
3534
// to all our direct channel collaborators. In order to promote liveness of our
3535
// active channels, we instruct the connection manager to attempt to establish
3536
// and maintain persistent connections to all our direct channel counterparties.
3537
func (s *server) establishPersistentConnections() error {
3✔
3538
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3539
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3540
        // since other PubKey forms can't be compared.
3✔
3541
        nodeAddrsMap := map[string]*nodeAddresses{}
3✔
3542

3✔
3543
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3544
        // attempt to connect to based on our set of previous connections. Set
3✔
3545
        // the reconnection port to the default peer port.
3✔
3546
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3547
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3548
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3549
        }
×
3550

3551
        for _, node := range linkNodes {
6✔
3552
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3553
                nodeAddrs := &nodeAddresses{
3✔
3554
                        pubKey:    node.IdentityPub,
3✔
3555
                        addresses: node.Addresses,
3✔
3556
                }
3✔
3557
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3558
        }
3✔
3559

3560
        // After checking our previous connections for addresses to connect to,
3561
        // iterate through the nodes in our channel graph to find addresses
3562
        // that have been added via NodeAnnouncement messages.
3563
        sourceNode, err := s.graphDB.SourceNode()
3✔
3564
        if err != nil {
3✔
3565
                return fmt.Errorf("failed to fetch source node: %w", err)
×
3566
        }
×
3567

3568
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3569
        // each of the nodes.
3570
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
3✔
3571
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
3✔
3572
                tx kvdb.RTx,
3✔
3573
                chanInfo *models.ChannelEdgeInfo,
3✔
3574
                policy, _ *models.ChannelEdgePolicy) error {
6✔
3575

3✔
3576
                // If the remote party has announced the channel to us, but we
3✔
3577
                // haven't yet, then we won't have a policy. However, we don't
3✔
3578
                // need this to connect to the peer, so we'll log it and move on.
3✔
3579
                if policy == nil {
3✔
3580
                        srvrLog.Warnf("No channel policy found for "+
×
3581
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3582
                }
×
3583

3584
                // We'll now fetch the peer opposite from us within this
3585
                // channel so we can queue up a direct connection to them.
3586
                channelPeer, err := s.graphDB.FetchOtherNode(
3✔
3587
                        tx, chanInfo, selfPub,
3✔
3588
                )
3✔
3589
                if err != nil {
3✔
3590
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3591
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3592
                                err)
×
3593
                }
×
3594

3595
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3596

3✔
3597
                // Add all unique addresses from channel
3✔
3598
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3599
                // connect to for this peer.
3✔
3600
                addrSet := make(map[string]net.Addr)
3✔
3601
                for _, addr := range channelPeer.Addresses {
6✔
3602
                        switch addr.(type) {
3✔
3603
                        case *net.TCPAddr:
3✔
3604
                                addrSet[addr.String()] = addr
3✔
3605

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

3615
                // If this peer is also recorded as a link node, we'll add any
3616
                // additional addresses that have not already been selected.
3617
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3618
                if ok {
6✔
3619
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3620
                                switch lnAddress.(type) {
3✔
3621
                                case *net.TCPAddr:
3✔
3622
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3623

3624
                                // We'll only attempt to connect to Tor
3625
                                // addresses if Tor outbound support is enabled.
3626
                                case *tor.OnionAddr:
×
3627
                                        if s.cfg.Tor.Active {
×
3628
                                                addrSet[lnAddress.String()] = lnAddress
×
3629
                                        }
×
3630
                                }
3631
                        }
3632
                }
3633

3634
                // Construct a slice of the deduped addresses.
3635
                var addrs []net.Addr
3✔
3636
                for _, addr := range addrSet {
6✔
3637
                        addrs = append(addrs, addr)
3✔
3638
                }
3✔
3639

3640
                n := &nodeAddresses{
3✔
3641
                        addresses: addrs,
3✔
3642
                }
3✔
3643
                n.pubKey, err = channelPeer.PubKey()
3✔
3644
                if err != nil {
3✔
3645
                        return err
×
3646
                }
×
3647

3648
                nodeAddrsMap[pubStr] = n
3✔
3649
                return nil
3✔
3650
        })
3651
        if err != nil {
3✔
3652
                srvrLog.Errorf("Failed to iterate channels for node %x",
×
3653
                        sourceNode.PubKeyBytes)
×
3654

×
3655
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3656
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3657

×
3658
                        return err
×
3659
                }
×
3660
        }
3661

3662
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3663
                len(nodeAddrsMap))
3✔
3664

3✔
3665
        // Acquire and hold server lock until all persistent connection requests
3✔
3666
        // have been recorded and sent to the connection manager.
3✔
3667
        s.mu.Lock()
3✔
3668
        defer s.mu.Unlock()
3✔
3669

3✔
3670
        // Iterate through the combined list of addresses from prior links and
3✔
3671
        // node announcements and attempt to reconnect to each node.
3✔
3672
        var numOutboundConns int
3✔
3673
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3674
                // Add this peer to the set of peers we should maintain a
3✔
3675
                // persistent connection with. We set the value to false to
3✔
3676
                // indicate that we should not continue to reconnect if the
3✔
3677
                // number of channels returns to zero, since this peer has not
3✔
3678
                // been requested as perm by the user.
3✔
3679
                s.persistentPeers[pubStr] = false
3✔
3680
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3681
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3682
                }
3✔
3683

3684
                for _, address := range nodeAddr.addresses {
6✔
3685
                        // Create a wrapper address which couples the IP and
3✔
3686
                        // the pubkey so the brontide authenticated connection
3✔
3687
                        // can be established.
3✔
3688
                        lnAddr := &lnwire.NetAddress{
3✔
3689
                                IdentityKey: nodeAddr.pubKey,
3✔
3690
                                Address:     address,
3✔
3691
                        }
3✔
3692

3✔
3693
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3694
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3695
                }
3✔
3696

3697
                // We'll connect to the first 10 peers immediately, then
3698
                // randomly stagger any remaining connections if the
3699
                // stagger initial reconnect flag is set. This ensures
3700
                // that mobile nodes or nodes with a small number of
3701
                // channels obtain connectivity quickly, but larger
3702
                // nodes are able to disperse the costs of connecting to
3703
                // all peers at once.
3704
                if numOutboundConns < numInstantInitReconnect ||
3✔
3705
                        !s.cfg.StaggerInitialReconnect {
6✔
3706

3✔
3707
                        go s.connectToPersistentPeer(pubStr)
3✔
3708
                } else {
3✔
3709
                        go s.delayInitialReconnect(pubStr)
×
3710
                }
×
3711

3712
                numOutboundConns++
3✔
3713
        }
3714

3715
        return nil
3✔
3716
}
3717

3718
// delayInitialReconnect will attempt a reconnection to the given peer after
3719
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3720
//
3721
// NOTE: This method MUST be run as a goroutine.
3722
func (s *server) delayInitialReconnect(pubStr string) {
×
3723
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3724
        select {
×
3725
        case <-time.After(delay):
×
3726
                s.connectToPersistentPeer(pubStr)
×
3727
        case <-s.quit:
×
3728
        }
3729
}
3730

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

3✔
3737
        s.mu.Lock()
3✔
3738
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3739
                delete(s.persistentPeers, pubKeyStr)
3✔
3740
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3741
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3742
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3743
                s.mu.Unlock()
3✔
3744

3✔
3745
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3746
                        "peer has no open channels", compressedPubKey)
3✔
3747

3✔
3748
                return
3✔
3749
        }
3✔
3750
        s.mu.Unlock()
3✔
3751
}
3752

3753
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3754
// is instead used to remove persistent peer state for a peer that has been
3755
// disconnected for good cause by the server. Currently, a gossip ban from
3756
// sending garbage and the server running out of restricted-access
3757
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3758
// future, this function may expand when more ban criteria is added.
3759
//
3760
// NOTE: The server's write lock MUST be held when this is called.
3761
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3762
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3763
                delete(s.persistentPeers, remotePub)
×
3764
                delete(s.persistentPeersBackoff, remotePub)
×
3765
                delete(s.persistentPeerAddrs, remotePub)
×
3766
                s.cancelConnReqs(remotePub, nil)
×
3767
        }
×
3768
}
3769

3770
// BroadcastMessage sends a request to the server to broadcast a set of
3771
// messages to all peers other than the one specified by the `skips` parameter.
3772
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3773
// the target peers.
3774
//
3775
// NOTE: This function is safe for concurrent access.
3776
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3777
        msgs ...lnwire.Message) error {
3✔
3778

3✔
3779
        // Filter out peers found in the skips map. We synchronize access to
3✔
3780
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3781
        // exact set of peers present at the time of invocation.
3✔
3782
        s.mu.RLock()
3✔
3783
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3784
        for pubStr, sPeer := range s.peersByPub {
6✔
3785
                if skips != nil {
6✔
3786
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3787
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3788
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3789
                                continue
3✔
3790
                        }
3791
                }
3792

3793
                peers = append(peers, sPeer)
3✔
3794
        }
3795
        s.mu.RUnlock()
3✔
3796

3✔
3797
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3798
        // all messages to each of peers.
3✔
3799
        var wg sync.WaitGroup
3✔
3800
        for _, sPeer := range peers {
6✔
3801
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3802
                        sPeer.PubKey())
3✔
3803

3✔
3804
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3805
                wg.Add(1)
3✔
3806
                s.wg.Add(1)
3✔
3807
                go func(p lnpeer.Peer) {
6✔
3808
                        defer s.wg.Done()
3✔
3809
                        defer wg.Done()
3✔
3810

3✔
3811
                        p.SendMessageLazy(false, msgs...)
3✔
3812
                }(sPeer)
3✔
3813
        }
3814

3815
        // Wait for all messages to have been dispatched before returning to
3816
        // caller.
3817
        wg.Wait()
3✔
3818

3✔
3819
        return nil
3✔
3820
}
3821

3822
// NotifyWhenOnline can be called by other subsystems to get notified when a
3823
// particular peer comes online. The peer itself is sent across the peerChan.
3824
//
3825
// NOTE: This function is safe for concurrent access.
3826
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3827
        peerChan chan<- lnpeer.Peer) {
3✔
3828

3✔
3829
        s.mu.Lock()
3✔
3830

3✔
3831
        // Compute the target peer's identifier.
3✔
3832
        pubStr := string(peerKey[:])
3✔
3833

3✔
3834
        // Check if peer is connected.
3✔
3835
        peer, ok := s.peersByPub[pubStr]
3✔
3836
        if ok {
6✔
3837
                // Unlock here so that the mutex isn't held while we are
3✔
3838
                // waiting for the peer to become active.
3✔
3839
                s.mu.Unlock()
3✔
3840

3✔
3841
                // Wait until the peer signals that it is actually active
3✔
3842
                // rather than only in the server's maps.
3✔
3843
                select {
3✔
3844
                case <-peer.ActiveSignal():
3✔
3845
                case <-peer.QuitSignal():
×
3846
                        // The peer quit, so we'll add the channel to the slice
×
3847
                        // and return.
×
3848
                        s.mu.Lock()
×
3849
                        s.peerConnectedListeners[pubStr] = append(
×
3850
                                s.peerConnectedListeners[pubStr], peerChan,
×
3851
                        )
×
3852
                        s.mu.Unlock()
×
3853
                        return
×
3854
                }
3855

3856
                // Connected, can return early.
3857
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3858

3✔
3859
                select {
3✔
3860
                case peerChan <- peer:
3✔
3861
                case <-s.quit:
×
3862
                }
3863

3864
                return
3✔
3865
        }
3866

3867
        // Not connected, store this listener such that it can be notified when
3868
        // the peer comes online.
3869
        s.peerConnectedListeners[pubStr] = append(
3✔
3870
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3871
        )
3✔
3872
        s.mu.Unlock()
3✔
3873
}
3874

3875
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3876
// the given public key has been disconnected. The notification is signaled by
3877
// closing the channel returned.
3878
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3879
        s.mu.Lock()
3✔
3880
        defer s.mu.Unlock()
3✔
3881

3✔
3882
        c := make(chan struct{})
3✔
3883

3✔
3884
        // If the peer is already offline, we can immediately trigger the
3✔
3885
        // notification.
3✔
3886
        peerPubKeyStr := string(peerPubKey[:])
3✔
3887
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3888
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3889
                close(c)
×
3890
                return c
×
3891
        }
×
3892

3893
        // Otherwise, the peer is online, so we'll keep track of the channel to
3894
        // trigger the notification once the server detects the peer
3895
        // disconnects.
3896
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3897
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3898
        )
3✔
3899

3✔
3900
        return c
3✔
3901
}
3902

3903
// FindPeer will return the peer that corresponds to the passed in public key.
3904
// This function is used by the funding manager, allowing it to update the
3905
// daemon's local representation of the remote peer.
3906
//
3907
// NOTE: This function is safe for concurrent access.
3908
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3909
        s.mu.RLock()
3✔
3910
        defer s.mu.RUnlock()
3✔
3911

3✔
3912
        pubStr := string(peerKey.SerializeCompressed())
3✔
3913

3✔
3914
        return s.findPeerByPubStr(pubStr)
3✔
3915
}
3✔
3916

3917
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3918
// which should be a string representation of the peer's serialized, compressed
3919
// public key.
3920
//
3921
// NOTE: This function is safe for concurrent access.
3922
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3923
        s.mu.RLock()
3✔
3924
        defer s.mu.RUnlock()
3✔
3925

3✔
3926
        return s.findPeerByPubStr(pubStr)
3✔
3927
}
3✔
3928

3929
// findPeerByPubStr is an internal method that retrieves the specified peer from
3930
// the server's internal state using.
3931
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3932
        peer, ok := s.peersByPub[pubStr]
3✔
3933
        if !ok {
6✔
3934
                return nil, ErrPeerNotConnected
3✔
3935
        }
3✔
3936

3937
        return peer, nil
3✔
3938
}
3939

3940
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3941
// exponential backoff. If no previous backoff was known, the default is
3942
// returned.
3943
func (s *server) nextPeerBackoff(pubStr string,
3944
        startTime time.Time) time.Duration {
3✔
3945

3✔
3946
        // Now, determine the appropriate backoff to use for the retry.
3✔
3947
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3948
        if !ok {
6✔
3949
                // If an existing backoff was unknown, use the default.
3✔
3950
                return s.cfg.MinBackoff
3✔
3951
        }
3✔
3952

3953
        // If the peer failed to start properly, we'll just use the previous
3954
        // backoff to compute the subsequent randomized exponential backoff
3955
        // duration. This will roughly double on average.
3956
        if startTime.IsZero() {
3✔
3957
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3958
        }
×
3959

3960
        // The peer succeeded in starting. If the connection didn't last long
3961
        // enough to be considered stable, we'll continue to back off retries
3962
        // with this peer.
3963
        connDuration := time.Since(startTime)
3✔
3964
        if connDuration < defaultStableConnDuration {
6✔
3965
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3966
        }
3✔
3967

3968
        // The peer succeed in starting and this was stable peer, so we'll
3969
        // reduce the timeout duration by the length of the connection after
3970
        // applying randomized exponential backoff. We'll only apply this in the
3971
        // case that:
3972
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3973
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3974
        if relaxedBackoff > s.cfg.MinBackoff {
×
3975
                return relaxedBackoff
×
3976
        }
×
3977

3978
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3979
        // the stable connection lasted much longer than our previous backoff.
3980
        // To reward such good behavior, we'll reconnect after the default
3981
        // timeout.
3982
        return s.cfg.MinBackoff
×
3983
}
3984

3985
// shouldDropLocalConnection determines if our local connection to a remote peer
3986
// should be dropped in the case of concurrent connection establishment. In
3987
// order to deterministically decide which connection should be dropped, we'll
3988
// utilize the ordering of the local and remote public key. If we didn't use
3989
// such a tie breaker, then we risk _both_ connections erroneously being
3990
// dropped.
3991
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3992
        localPubBytes := local.SerializeCompressed()
×
3993
        remotePubPbytes := remote.SerializeCompressed()
×
3994

×
3995
        // The connection that comes from the node with a "smaller" pubkey
×
3996
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3997
        // should drop our established connection.
×
3998
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3999
}
×
4000

4001
// InboundPeerConnected initializes a new peer in response to a new inbound
4002
// connection.
4003
//
4004
// NOTE: This function is safe for concurrent access.
4005
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
4006
        // Exit early if we have already been instructed to shutdown, this
3✔
4007
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4008
        if s.Stopped() {
3✔
4009
                return
×
4010
        }
×
4011

4012
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4013
        pubSer := nodePub.SerializeCompressed()
3✔
4014
        pubStr := string(pubSer)
3✔
4015

3✔
4016
        var pubBytes [33]byte
3✔
4017
        copy(pubBytes[:], pubSer)
3✔
4018

3✔
4019
        s.mu.Lock()
3✔
4020
        defer s.mu.Unlock()
3✔
4021

3✔
4022
        // If the remote node's public key is banned, drop the connection.
3✔
4023
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
3✔
4024
        if err != nil {
3✔
4025
                // Clean up the persistent peer maps if we're dropping this
×
4026
                // connection.
×
4027
                s.bannedPersistentPeerConnection(pubStr)
×
4028

×
4029
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4030
                        "of restricted-access connection slots: %v.", pubSer,
×
4031
                        err)
×
4032

×
4033
                conn.Close()
×
4034

×
4035
                return
×
4036
        }
×
4037

4038
        // If we already have an outbound connection to this peer, then ignore
4039
        // this new connection.
4040
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
4041
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
4042
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
4043
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4044

3✔
4045
                conn.Close()
3✔
4046
                return
3✔
4047
        }
3✔
4048

4049
        // If we already have a valid connection that is scheduled to take
4050
        // precedence once the prior peer has finished disconnecting, we'll
4051
        // ignore this connection.
4052
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
4053
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4054
                        "scheduled", conn.RemoteAddr(), p)
×
4055
                conn.Close()
×
4056
                return
×
4057
        }
×
4058

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

3✔
4061
        // Check to see if we already have a connection with this peer. If so,
3✔
4062
        // we may need to drop our existing connection. This prevents us from
3✔
4063
        // having duplicate connections to the same peer. We forgo adding a
3✔
4064
        // default case as we expect these to be the only error values returned
3✔
4065
        // from findPeerByPubStr.
3✔
4066
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4067
        switch err {
3✔
4068
        case ErrPeerNotConnected:
3✔
4069
                // We were unable to locate an existing connection with the
3✔
4070
                // target peer, proceed to connect.
3✔
4071
                s.cancelConnReqs(pubStr, nil)
3✔
4072
                s.peerConnected(conn, nil, true, access)
3✔
4073

4074
        case nil:
×
4075
                // We already have a connection with the incoming peer. If the
×
4076
                // connection we've already established should be kept and is
×
4077
                // not of the same type of the new connection (inbound), then
×
4078
                // we'll close out the new connection s.t there's only a single
×
4079
                // connection between us.
×
4080
                localPub := s.identityECDH.PubKey()
×
4081
                if !connectedPeer.Inbound() &&
×
4082
                        !shouldDropLocalConnection(localPub, nodePub) {
×
4083

×
4084
                        srvrLog.Warnf("Received inbound connection from "+
×
4085
                                "peer %v, but already have outbound "+
×
4086
                                "connection, dropping conn", connectedPeer)
×
4087
                        conn.Close()
×
4088
                        return
×
4089
                }
×
4090

4091
                // Otherwise, if we should drop the connection, then we'll
4092
                // disconnect our already connected peer.
4093
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4094
                        connectedPeer)
×
4095

×
4096
                s.cancelConnReqs(pubStr, nil)
×
4097

×
4098
                // Remove the current peer from the server's internal state and
×
4099
                // signal that the peer termination watcher does not need to
×
4100
                // execute for this peer.
×
4101
                s.removePeer(connectedPeer)
×
4102
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4103
                s.scheduledPeerConnection[pubStr] = func() {
×
4104
                        s.peerConnected(conn, nil, true, access)
×
4105
                }
×
4106
        }
4107
}
4108

4109
// OutboundPeerConnected initializes a new peer in response to a new outbound
4110
// connection.
4111
// NOTE: This function is safe for concurrent access.
4112
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4113
        // Exit early if we have already been instructed to shutdown, this
3✔
4114
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4115
        if s.Stopped() {
3✔
4116
                return
×
4117
        }
×
4118

4119
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4120
        pubSer := nodePub.SerializeCompressed()
3✔
4121
        pubStr := string(pubSer)
3✔
4122

3✔
4123
        var pubBytes [33]byte
3✔
4124
        copy(pubBytes[:], pubSer)
3✔
4125

3✔
4126
        s.mu.Lock()
3✔
4127
        defer s.mu.Unlock()
3✔
4128

3✔
4129
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
3✔
4130
        if err != nil {
3✔
4131
                // Clean up the persistent peer maps if we're dropping this
×
4132
                // connection.
×
4133
                s.bannedPersistentPeerConnection(pubStr)
×
4134

×
4135
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4136
                        "of restricted-access connection slots: %v.", pubSer,
×
4137
                        err)
×
4138

×
4139
                if connReq != nil {
×
4140
                        s.connMgr.Remove(connReq.ID())
×
4141
                }
×
4142

4143
                conn.Close()
×
4144

×
4145
                return
×
4146
        }
4147

4148
        // If we already have an inbound connection to this peer, then ignore
4149
        // this new connection.
4150
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4151
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4152
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4153
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4154

3✔
4155
                if connReq != nil {
6✔
4156
                        s.connMgr.Remove(connReq.ID())
3✔
4157
                }
3✔
4158
                conn.Close()
3✔
4159
                return
3✔
4160
        }
4161
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4162
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4163
                s.connMgr.Remove(connReq.ID())
×
4164
                conn.Close()
×
4165
                return
×
4166
        }
×
4167

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

×
4174
                if connReq != nil {
×
4175
                        s.connMgr.Remove(connReq.ID())
×
4176
                }
×
4177

4178
                conn.Close()
×
4179
                return
×
4180
        }
4181

4182
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
3✔
4183
                conn.RemoteAddr())
3✔
4184

3✔
4185
        if connReq != nil {
6✔
4186
                // A successful connection was returned by the connmgr.
3✔
4187
                // Immediately cancel all pending requests, excluding the
3✔
4188
                // outbound connection we just established.
3✔
4189
                ignore := connReq.ID()
3✔
4190
                s.cancelConnReqs(pubStr, &ignore)
3✔
4191
        } else {
6✔
4192
                // This was a successful connection made by some other
3✔
4193
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4194
                s.cancelConnReqs(pubStr, nil)
3✔
4195
        }
3✔
4196

4197
        // If we already have a connection with this peer, decide whether or not
4198
        // we need to drop the stale connection. We forgo adding a default case
4199
        // as we expect these to be the only error values returned from
4200
        // findPeerByPubStr.
4201
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4202
        switch err {
3✔
4203
        case ErrPeerNotConnected:
3✔
4204
                // We were unable to locate an existing connection with the
3✔
4205
                // target peer, proceed to connect.
3✔
4206
                s.peerConnected(conn, connReq, false, access)
3✔
4207

4208
        case nil:
×
4209
                // We already have a connection with the incoming peer. If the
×
4210
                // connection we've already established should be kept and is
×
4211
                // not of the same type of the new connection (outbound), then
×
4212
                // we'll close out the new connection s.t there's only a single
×
4213
                // connection between us.
×
4214
                localPub := s.identityECDH.PubKey()
×
4215
                if connectedPeer.Inbound() &&
×
4216
                        shouldDropLocalConnection(localPub, nodePub) {
×
4217

×
4218
                        srvrLog.Warnf("Established outbound connection to "+
×
4219
                                "peer %v, but already have inbound "+
×
4220
                                "connection, dropping conn", connectedPeer)
×
4221
                        if connReq != nil {
×
4222
                                s.connMgr.Remove(connReq.ID())
×
4223
                        }
×
4224
                        conn.Close()
×
4225
                        return
×
4226
                }
4227

4228
                // Otherwise, _their_ connection should be dropped. So we'll
4229
                // disconnect the peer and send the now obsolete peer to the
4230
                // server for garbage collection.
4231
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4232
                        connectedPeer)
×
4233

×
4234
                // Remove the current peer from the server's internal state and
×
4235
                // signal that the peer termination watcher does not need to
×
4236
                // execute for this peer.
×
4237
                s.removePeer(connectedPeer)
×
4238
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4239
                s.scheduledPeerConnection[pubStr] = func() {
×
4240
                        s.peerConnected(conn, connReq, false, access)
×
4241
                }
×
4242
        }
4243
}
4244

4245
// UnassignedConnID is the default connection ID that a request can have before
4246
// it actually is submitted to the connmgr.
4247
// TODO(conner): move into connmgr package, or better, add connmgr method for
4248
// generating atomic IDs
4249
const UnassignedConnID uint64 = 0
4250

4251
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4252
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4253
// Afterwards, each connection request removed from the connmgr. The caller can
4254
// optionally specify a connection ID to ignore, which prevents us from
4255
// canceling a successful request. All persistent connreqs for the provided
4256
// pubkey are discarded after the operationjw.
4257
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4258
        // First, cancel any lingering persistent retry attempts, which will
3✔
4259
        // prevent retries for any with backoffs that are still maturing.
3✔
4260
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4261
                close(cancelChan)
3✔
4262
                delete(s.persistentRetryCancels, pubStr)
3✔
4263
        }
3✔
4264

4265
        // Next, check to see if we have any outstanding persistent connection
4266
        // requests to this peer. If so, then we'll remove all of these
4267
        // connection requests, and also delete the entry from the map.
4268
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4269
        if !ok {
6✔
4270
                return
3✔
4271
        }
3✔
4272

4273
        for _, connReq := range connReqs {
6✔
4274
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4275

3✔
4276
                // Atomically capture the current request identifier.
3✔
4277
                connID := connReq.ID()
3✔
4278

3✔
4279
                // Skip any zero IDs, this indicates the request has not
3✔
4280
                // yet been schedule.
3✔
4281
                if connID == UnassignedConnID {
3✔
4282
                        continue
×
4283
                }
4284

4285
                // Skip a particular connection ID if instructed.
4286
                if skip != nil && connID == *skip {
6✔
4287
                        continue
3✔
4288
                }
4289

4290
                s.connMgr.Remove(connID)
3✔
4291
        }
4292

4293
        delete(s.persistentConnReqs, pubStr)
3✔
4294
}
4295

4296
// handleCustomMessage dispatches an incoming custom peers message to
4297
// subscribers.
4298
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4299
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4300
                peer, msg.Type)
3✔
4301

3✔
4302
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4303
                Peer: peer,
3✔
4304
                Msg:  msg,
3✔
4305
        })
3✔
4306
}
3✔
4307

4308
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4309
// messages.
4310
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4311
        return s.customMessageServer.Subscribe()
3✔
4312
}
3✔
4313

4314
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4315
// the channelNotifier's NotifyOpenChannelEvent.
4316
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4317
        remotePub *btcec.PublicKey) error {
3✔
4318

3✔
4319
        // Call newOpenChan to update the access manager's maps for this peer.
3✔
4320
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
6✔
4321
                return err
3✔
4322
        }
3✔
4323

4324
        // Notify subscribers about this open channel event.
4325
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4326

3✔
4327
        return nil
3✔
4328
}
4329

4330
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4331
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4332
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4333
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) error {
3✔
4334

3✔
4335
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4336
        // peer.
3✔
4337
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4338
                return err
×
4339
        }
×
4340

4341
        // Notify subscribers about this event.
4342
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4343

3✔
4344
        return nil
3✔
4345
}
4346

4347
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4348
// calls the channelNotifier's NotifyFundingTimeout.
4349
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4350
        remotePub *btcec.PublicKey) error {
3✔
4351

3✔
4352
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4353
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4354
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4355
                // If we encounter an error while attempting to disconnect the
×
4356
                // peer, log the error.
×
4357
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4358
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4359
                }
×
4360
        }
4361

4362
        // Notify subscribers about this event.
4363
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4364

3✔
4365
        return nil
3✔
4366
}
4367

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

3✔
4375
        brontideConn := conn.(*brontide.Conn)
3✔
4376
        addr := conn.RemoteAddr()
3✔
4377
        pubKey := brontideConn.RemotePub()
3✔
4378

3✔
4379
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4380
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4381

3✔
4382
        peerAddr := &lnwire.NetAddress{
3✔
4383
                IdentityKey: pubKey,
3✔
4384
                Address:     addr,
3✔
4385
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4386
        }
3✔
4387

3✔
4388
        // With the brontide connection established, we'll now craft the feature
3✔
4389
        // vectors to advertise to the remote node.
3✔
4390
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4391
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4392

3✔
4393
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4394
        // found, create a fresh buffer.
3✔
4395
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4396
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4397
        if !ok {
6✔
4398
                var err error
3✔
4399
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4400
                if err != nil {
3✔
4401
                        srvrLog.Errorf("unable to create peer %v", err)
×
4402
                        return
×
4403
                }
×
4404
        }
4405

4406
        // If we directly set the peer.Config TowerClient member to the
4407
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4408
        // the peer.Config's TowerClient member will not evaluate to nil even
4409
        // though the underlying value is nil. To avoid this gotcha which can
4410
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4411
        // TowerClient if needed.
4412
        var towerClient wtclient.ClientManager
3✔
4413
        if s.towerClientMgr != nil {
6✔
4414
                towerClient = s.towerClientMgr
3✔
4415
        }
3✔
4416

4417
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4418
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4419

3✔
4420
        // Now that we've established a connection, create a peer, and it to the
3✔
4421
        // set of currently active peers. Configure the peer with the incoming
3✔
4422
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
3✔
4423
        // offered that would trigger channel closure. In case of outgoing
3✔
4424
        // htlcs, an extra block is added to prevent the channel from being
3✔
4425
        // closed when the htlc is outstanding and a new block comes in.
3✔
4426
        pCfg := peer.Config{
3✔
4427
                Conn:                    brontideConn,
3✔
4428
                ConnReq:                 connReq,
3✔
4429
                Addr:                    peerAddr,
3✔
4430
                Inbound:                 inbound,
3✔
4431
                Features:                initFeatures,
3✔
4432
                LegacyFeatures:          legacyFeatures,
3✔
4433
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
3✔
4434
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
3✔
4435
                ErrorBuffer:             errBuffer,
3✔
4436
                WritePool:               s.writePool,
3✔
4437
                ReadPool:                s.readPool,
3✔
4438
                Switch:                  s.htlcSwitch,
3✔
4439
                InterceptSwitch:         s.interceptableSwitch,
3✔
4440
                ChannelDB:               s.chanStateDB,
3✔
4441
                ChannelGraph:            s.graphDB,
3✔
4442
                ChainArb:                s.chainArb,
3✔
4443
                AuthGossiper:            s.authGossiper,
3✔
4444
                ChanStatusMgr:           s.chanStatusMgr,
3✔
4445
                ChainIO:                 s.cc.ChainIO,
3✔
4446
                FeeEstimator:            s.cc.FeeEstimator,
3✔
4447
                Signer:                  s.cc.Wallet.Cfg.Signer,
3✔
4448
                SigPool:                 s.sigPool,
3✔
4449
                Wallet:                  s.cc.Wallet,
3✔
4450
                ChainNotifier:           s.cc.ChainNotifier,
3✔
4451
                BestBlockView:           s.cc.BestBlockTracker,
3✔
4452
                RoutingPolicy:           s.cc.RoutingPolicy,
3✔
4453
                Sphinx:                  s.sphinx,
3✔
4454
                WitnessBeacon:           s.witnessBeacon,
3✔
4455
                Invoices:                s.invoices,
3✔
4456
                ChannelNotifier:         s.channelNotifier,
3✔
4457
                HtlcNotifier:            s.htlcNotifier,
3✔
4458
                TowerClient:             towerClient,
3✔
4459
                DisconnectPeer:          s.DisconnectPeer,
3✔
4460
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
3✔
4461
                        lnwire.NodeAnnouncement, error) {
6✔
4462

3✔
4463
                        return s.genNodeAnnouncement(nil)
3✔
4464
                },
3✔
4465

4466
                PongBuf: s.pongBuf,
4467

4468
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4469

4470
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4471

4472
                FundingManager: s.fundingMgr,
4473

4474
                Hodl:                    s.cfg.Hodl,
4475
                UnsafeReplay:            s.cfg.UnsafeReplay,
4476
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4477
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4478
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4479
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4480
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4481
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4482
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4483
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4484
                HandleCustomMessage:    s.handleCustomMessage,
4485
                GetAliases:             s.aliasMgr.GetAliases,
4486
                RequestAlias:           s.aliasMgr.RequestAlias,
4487
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4488
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4489
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4490
                MaxFeeExposure:         thresholdMSats,
4491
                Quit:                   s.quit,
4492
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4493
                AuxSigner:              s.implCfg.AuxSigner,
4494
                MsgRouter:              s.implCfg.MsgRouter,
4495
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4496
                AuxResolver:            s.implCfg.AuxContractResolver,
4497
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4498
                ShouldFwdExpEndorsement: func() bool {
3✔
4499
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4500
                                return false
3✔
4501
                        }
3✔
4502

4503
                        return clock.NewDefaultClock().Now().Before(
3✔
4504
                                EndorsementExperimentEnd,
3✔
4505
                        )
3✔
4506
                },
4507
        }
4508

4509
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4510
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4511

3✔
4512
        p := peer.NewBrontide(pCfg)
3✔
4513

3✔
4514
        // Update the access manager with the access permission for this peer.
3✔
4515
        s.peerAccessMan.addPeerAccess(pubKey, access)
3✔
4516

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

3✔
4520
        s.addPeer(p)
3✔
4521

3✔
4522
        // Once we have successfully added the peer to the server, we can
3✔
4523
        // delete the previous error buffer from the server's map of error
3✔
4524
        // buffers.
3✔
4525
        delete(s.peerErrors, pkStr)
3✔
4526

3✔
4527
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4528
        // includes sending and receiving Init messages, which would be a DOS
3✔
4529
        // vector if we held the server's mutex throughout the procedure.
3✔
4530
        s.wg.Add(1)
3✔
4531
        go s.peerInitializer(p)
3✔
4532
}
4533

4534
// addPeer adds the passed peer to the server's global state of all active
4535
// peers.
4536
func (s *server) addPeer(p *peer.Brontide) {
3✔
4537
        if p == nil {
3✔
4538
                return
×
4539
        }
×
4540

4541
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4542

3✔
4543
        // Ignore new peers if we're shutting down.
3✔
4544
        if s.Stopped() {
3✔
4545
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4546
                        pubBytes)
×
4547
                p.Disconnect(ErrServerShuttingDown)
×
4548

×
4549
                return
×
4550
        }
×
4551

4552
        // Track the new peer in our indexes so we can quickly look it up either
4553
        // according to its public key, or its peer ID.
4554
        // TODO(roasbeef): pipe all requests through to the
4555
        // queryHandler/peerManager
4556

4557
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4558
        // be human-readable.
4559
        pubStr := string(pubBytes)
3✔
4560

3✔
4561
        s.peersByPub[pubStr] = p
3✔
4562

3✔
4563
        if p.Inbound() {
6✔
4564
                s.inboundPeers[pubStr] = p
3✔
4565
        } else {
6✔
4566
                s.outboundPeers[pubStr] = p
3✔
4567
        }
3✔
4568

4569
        // Inform the peer notifier of a peer online event so that it can be reported
4570
        // to clients listening for peer events.
4571
        var pubKey [33]byte
3✔
4572
        copy(pubKey[:], pubBytes)
3✔
4573

3✔
4574
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4575
}
4576

4577
// peerInitializer asynchronously starts a newly connected peer after it has
4578
// been added to the server's peer map. This method sets up a
4579
// peerTerminationWatcher for the given peer, and ensures that it executes even
4580
// if the peer failed to start. In the event of a successful connection, this
4581
// method reads the negotiated, local feature-bits and spawns the appropriate
4582
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4583
// be signaled of the new peer once the method returns.
4584
//
4585
// NOTE: This MUST be launched as a goroutine.
4586
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4587
        defer s.wg.Done()
3✔
4588

3✔
4589
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4590

3✔
4591
        // Avoid initializing peers while the server is exiting.
3✔
4592
        if s.Stopped() {
3✔
4593
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4594
                        pubBytes)
×
4595
                return
×
4596
        }
×
4597

4598
        // Create a channel that will be used to signal a successful start of
4599
        // the link. This prevents the peer termination watcher from beginning
4600
        // its duty too early.
4601
        ready := make(chan struct{})
3✔
4602

3✔
4603
        // Before starting the peer, launch a goroutine to watch for the
3✔
4604
        // unexpected termination of this peer, which will ensure all resources
3✔
4605
        // are properly cleaned up, and re-establish persistent connections when
3✔
4606
        // necessary. The peer termination watcher will be short circuited if
3✔
4607
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4608
        // that the server has already handled the removal of this peer.
3✔
4609
        s.wg.Add(1)
3✔
4610
        go s.peerTerminationWatcher(p, ready)
3✔
4611

3✔
4612
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4613
        // will unblock the peerTerminationWatcher.
3✔
4614
        if err := p.Start(); err != nil {
6✔
4615
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4616

3✔
4617
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4618
                return
3✔
4619
        }
3✔
4620

4621
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4622
        // was successful, and to begin watching the peer's wait group.
4623
        close(ready)
3✔
4624

3✔
4625
        s.mu.Lock()
3✔
4626
        defer s.mu.Unlock()
3✔
4627

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

3✔
4631
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4632
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4633
        pubStr := string(pubBytes)
3✔
4634
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4635
                select {
3✔
4636
                case peerChan <- p:
3✔
4637
                case <-s.quit:
×
4638
                        return
×
4639
                }
4640
        }
4641
        delete(s.peerConnectedListeners, pubStr)
3✔
4642
}
4643

4644
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4645
// and then cleans up all resources allocated to the peer, notifies relevant
4646
// sub-systems of its demise, and finally handles re-connecting to the peer if
4647
// it's persistent. If the server intentionally disconnects a peer, it should
4648
// have a corresponding entry in the ignorePeerTermination map which will cause
4649
// the cleanup routine to exit early. The passed `ready` chan is used to
4650
// synchronize when WaitForDisconnect should begin watching on the peer's
4651
// waitgroup. The ready chan should only be signaled if the peer starts
4652
// successfully, otherwise the peer should be disconnected instead.
4653
//
4654
// NOTE: This MUST be launched as a goroutine.
4655
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4656
        defer s.wg.Done()
3✔
4657

3✔
4658
        p.WaitForDisconnect(ready)
3✔
4659

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

3✔
4662
        // If the server is exiting then we can bail out early ourselves as all
3✔
4663
        // the other sub-systems will already be shutting down.
3✔
4664
        if s.Stopped() {
6✔
4665
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
3✔
4666
                return
3✔
4667
        }
3✔
4668

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

3✔
4675
        pubKey := p.IdentityKey()
3✔
4676

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

3✔
4681
        // Tell the switch to remove all links associated with this peer.
3✔
4682
        // Passing nil as the target link indicates that all links associated
3✔
4683
        // with this interface should be closed.
3✔
4684
        //
3✔
4685
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4686
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4687
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4688
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4689
        }
×
4690

4691
        for _, link := range links {
6✔
4692
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4693
        }
3✔
4694

4695
        s.mu.Lock()
3✔
4696
        defer s.mu.Unlock()
3✔
4697

3✔
4698
        // If there were any notification requests for when this peer
3✔
4699
        // disconnected, we can trigger them now.
3✔
4700
        srvrLog.Debugf("Notifying that peer %v is offline", p)
3✔
4701
        pubStr := string(pubKey.SerializeCompressed())
3✔
4702
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4703
                close(offlineChan)
3✔
4704
        }
3✔
4705
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4706

3✔
4707
        // If the server has already removed this peer, we can short circuit the
3✔
4708
        // peer termination watcher and skip cleanup.
3✔
4709
        if _, ok := s.ignorePeerTermination[p]; ok {
3✔
4710
                delete(s.ignorePeerTermination, p)
×
4711

×
4712
                pubKey := p.PubKey()
×
4713
                pubStr := string(pubKey[:])
×
4714

×
4715
                // If a connection callback is present, we'll go ahead and
×
4716
                // execute it now that previous peer has fully disconnected. If
×
4717
                // the callback is not present, this likely implies the peer was
×
4718
                // purposefully disconnected via RPC, and that no reconnect
×
4719
                // should be attempted.
×
4720
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4721
                if ok {
×
4722
                        delete(s.scheduledPeerConnection, pubStr)
×
4723
                        connCallback()
×
4724
                }
×
4725
                return
×
4726
        }
4727

4728
        // First, cleanup any remaining state the server has regarding the peer
4729
        // in question.
4730
        s.removePeer(p)
3✔
4731

3✔
4732
        // Next, check to see if this is a persistent peer or not.
3✔
4733
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4734
                return
3✔
4735
        }
3✔
4736

4737
        // Get the last address that we used to connect to the peer.
4738
        addrs := []net.Addr{
3✔
4739
                p.NetAddress().Address,
3✔
4740
        }
3✔
4741

3✔
4742
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4743
        // reconnection purposes.
3✔
4744
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
3✔
4745
        switch {
3✔
4746
        // We found advertised addresses, so use them.
4747
        case err == nil:
3✔
4748
                addrs = advertisedAddrs
3✔
4749

4750
        // The peer doesn't have an advertised address.
4751
        case err == errNoAdvertisedAddr:
3✔
4752
                // If it is an outbound peer then we fall back to the existing
3✔
4753
                // peer address.
3✔
4754
                if !p.Inbound() {
6✔
4755
                        break
3✔
4756
                }
4757

4758
                // Fall back to the existing peer address if
4759
                // we're not accepting connections over Tor.
4760
                if s.torController == nil {
6✔
4761
                        break
3✔
4762
                }
4763

4764
                // If we are, the peer's address won't be known
4765
                // to us (we'll see a private address, which is
4766
                // the address used by our onion service to dial
4767
                // to lnd), so we don't have enough information
4768
                // to attempt a reconnect.
4769
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4770
                        "to inbound peer %v without "+
×
4771
                        "advertised address", p)
×
4772
                return
×
4773

4774
        // We came across an error retrieving an advertised
4775
        // address, log it, and fall back to the existing peer
4776
        // address.
4777
        default:
3✔
4778
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4779
                        "address for node %x: %v", p.PubKey(),
3✔
4780
                        err)
3✔
4781
        }
4782

4783
        // Make an easy lookup map so that we can check if an address
4784
        // is already in the address list that we have stored for this peer.
4785
        existingAddrs := make(map[string]bool)
3✔
4786
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4787
                existingAddrs[addr.String()] = true
3✔
4788
        }
3✔
4789

4790
        // Add any missing addresses for this peer to persistentPeerAddr.
4791
        for _, addr := range addrs {
6✔
4792
                if existingAddrs[addr.String()] {
3✔
4793
                        continue
×
4794
                }
4795

4796
                s.persistentPeerAddrs[pubStr] = append(
3✔
4797
                        s.persistentPeerAddrs[pubStr],
3✔
4798
                        &lnwire.NetAddress{
3✔
4799
                                IdentityKey: p.IdentityKey(),
3✔
4800
                                Address:     addr,
3✔
4801
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4802
                        },
3✔
4803
                )
3✔
4804
        }
4805

4806
        // Record the computed backoff in the backoff map.
4807
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4808
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4809

3✔
4810
        // Initialize a retry canceller for this peer if one does not
3✔
4811
        // exist.
3✔
4812
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4813
        if !ok {
6✔
4814
                cancelChan = make(chan struct{})
3✔
4815
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4816
        }
3✔
4817

4818
        // We choose not to wait group this go routine since the Connect
4819
        // call can stall for arbitrarily long if we shutdown while an
4820
        // outbound connection attempt is being made.
4821
        go func() {
6✔
4822
                srvrLog.Debugf("Scheduling connection re-establishment to "+
3✔
4823
                        "persistent peer %x in %s",
3✔
4824
                        p.IdentityKey().SerializeCompressed(), backoff)
3✔
4825

3✔
4826
                select {
3✔
4827
                case <-time.After(backoff):
3✔
4828
                case <-cancelChan:
3✔
4829
                        return
3✔
4830
                case <-s.quit:
3✔
4831
                        return
3✔
4832
                }
4833

4834
                srvrLog.Debugf("Attempting to re-establish persistent "+
3✔
4835
                        "connection to peer %x",
3✔
4836
                        p.IdentityKey().SerializeCompressed())
3✔
4837

3✔
4838
                s.connectToPersistentPeer(pubStr)
3✔
4839
        }()
4840
}
4841

4842
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4843
// to connect to the peer. It creates connection requests if there are
4844
// currently none for a given address and it removes old connection requests
4845
// if the associated address is no longer in the latest address list for the
4846
// peer.
4847
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4848
        s.mu.Lock()
3✔
4849
        defer s.mu.Unlock()
3✔
4850

3✔
4851
        // Create an easy lookup map of the addresses we have stored for the
3✔
4852
        // peer. We will remove entries from this map if we have existing
3✔
4853
        // connection requests for the associated address and then any leftover
3✔
4854
        // entries will indicate which addresses we should create new
3✔
4855
        // connection requests for.
3✔
4856
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4857
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4858
                addrMap[addr.String()] = addr
3✔
4859
        }
3✔
4860

4861
        // Go through each of the existing connection requests and
4862
        // check if they correspond to the latest set of addresses. If
4863
        // there is a connection requests that does not use one of the latest
4864
        // advertised addresses then remove that connection request.
4865
        var updatedConnReqs []*connmgr.ConnReq
3✔
4866
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4867
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4868

3✔
4869
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4870
                // If the existing connection request is using one of the
4871
                // latest advertised addresses for the peer then we add it to
4872
                // updatedConnReqs and remove the associated address from
4873
                // addrMap so that we don't recreate this connReq later on.
4874
                case true:
×
4875
                        updatedConnReqs = append(
×
4876
                                updatedConnReqs, connReq,
×
4877
                        )
×
4878
                        delete(addrMap, lnAddr)
×
4879

4880
                // If the existing connection request is using an address that
4881
                // is not one of the latest advertised addresses for the peer
4882
                // then we remove the connecting request from the connection
4883
                // manager.
4884
                case false:
3✔
4885
                        srvrLog.Info(
3✔
4886
                                "Removing conn req:", connReq.Addr.String(),
3✔
4887
                        )
3✔
4888
                        s.connMgr.Remove(connReq.ID())
3✔
4889
                }
4890
        }
4891

4892
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4893

3✔
4894
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4895
        if !ok {
6✔
4896
                cancelChan = make(chan struct{})
3✔
4897
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4898
        }
3✔
4899

4900
        // Any addresses left in addrMap are new ones that we have not made
4901
        // connection requests for. So create new connection requests for those.
4902
        // If there is more than one address in the address map, stagger the
4903
        // creation of the connection requests for those.
4904
        go func() {
6✔
4905
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4906
                defer ticker.Stop()
3✔
4907

3✔
4908
                for _, addr := range addrMap {
6✔
4909
                        // Send the persistent connection request to the
3✔
4910
                        // connection manager, saving the request itself so we
3✔
4911
                        // can cancel/restart the process as needed.
3✔
4912
                        connReq := &connmgr.ConnReq{
3✔
4913
                                Addr:      addr,
3✔
4914
                                Permanent: true,
3✔
4915
                        }
3✔
4916

3✔
4917
                        s.mu.Lock()
3✔
4918
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4919
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4920
                        )
3✔
4921
                        s.mu.Unlock()
3✔
4922

3✔
4923
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4924
                                "channel peer %v", addr)
3✔
4925

3✔
4926
                        go s.connMgr.Connect(connReq)
3✔
4927

3✔
4928
                        select {
3✔
4929
                        case <-s.quit:
3✔
4930
                                return
3✔
4931
                        case <-cancelChan:
3✔
4932
                                return
3✔
4933
                        case <-ticker.C:
3✔
4934
                        }
4935
                }
4936
        }()
4937
}
4938

4939
// removePeer removes the passed peer from the server's state of all active
4940
// peers.
4941
func (s *server) removePeer(p *peer.Brontide) {
3✔
4942
        if p == nil {
3✔
4943
                return
×
4944
        }
×
4945

4946
        srvrLog.Debugf("removing peer %v", p)
3✔
4947

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

3✔
4952
        // If this peer had an active persistent connection request, remove it.
3✔
4953
        if p.ConnReq() != nil {
6✔
4954
                s.connMgr.Remove(p.ConnReq().ID())
3✔
4955
        }
3✔
4956

4957
        // Ignore deleting peers if we're shutting down.
4958
        if s.Stopped() {
3✔
4959
                return
×
4960
        }
×
4961

4962
        pKey := p.PubKey()
3✔
4963
        pubSer := pKey[:]
3✔
4964
        pubStr := string(pubSer)
3✔
4965

3✔
4966
        delete(s.peersByPub, pubStr)
3✔
4967

3✔
4968
        if p.Inbound() {
6✔
4969
                delete(s.inboundPeers, pubStr)
3✔
4970
        } else {
6✔
4971
                delete(s.outboundPeers, pubStr)
3✔
4972
        }
3✔
4973

4974
        // Remove the peer's access permission from the access manager.
4975
        s.peerAccessMan.removePeerAccess(p.IdentityKey())
3✔
4976

3✔
4977
        // Copy the peer's error buffer across to the server if it has any items
3✔
4978
        // in it so that we can restore peer errors across connections.
3✔
4979
        if p.ErrorBuffer().Total() > 0 {
6✔
4980
                s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4981
        }
3✔
4982

4983
        // Inform the peer notifier of a peer offline event so that it can be
4984
        // reported to clients listening for peer events.
4985
        var pubKey [33]byte
3✔
4986
        copy(pubKey[:], pubSer)
3✔
4987

3✔
4988
        s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4989
}
4990

4991
// ConnectToPeer requests that the server connect to a Lightning Network peer
4992
// at the specified address. This function will *block* until either a
4993
// connection is established, or the initial handshake process fails.
4994
//
4995
// NOTE: This function is safe for concurrent access.
4996
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4997
        perm bool, timeout time.Duration) error {
3✔
4998

3✔
4999
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
5000

3✔
5001
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
5002
        // better granularity.  In certain conditions, this method requires
3✔
5003
        // making an outbound connection to a remote peer, which requires the
3✔
5004
        // lock to be released, and subsequently reacquired.
3✔
5005
        s.mu.Lock()
3✔
5006

3✔
5007
        // Ensure we're not already connected to this peer.
3✔
5008
        peer, err := s.findPeerByPubStr(targetPub)
3✔
5009
        if err == nil {
6✔
5010
                s.mu.Unlock()
3✔
5011
                return &errPeerAlreadyConnected{peer: peer}
3✔
5012
        }
3✔
5013

5014
        // Peer was not found, continue to pursue connection with peer.
5015

5016
        // If there's already a pending connection request for this pubkey,
5017
        // then we ignore this request to ensure we don't create a redundant
5018
        // connection.
5019
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
5020
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
5021
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
5022
        }
3✔
5023

5024
        // If there's not already a pending or active connection to this node,
5025
        // then instruct the connection manager to attempt to establish a
5026
        // persistent connection to the peer.
5027
        srvrLog.Debugf("Connecting to %v", addr)
3✔
5028
        if perm {
6✔
5029
                connReq := &connmgr.ConnReq{
3✔
5030
                        Addr:      addr,
3✔
5031
                        Permanent: true,
3✔
5032
                }
3✔
5033

3✔
5034
                // Since the user requested a permanent connection, we'll set
3✔
5035
                // the entry to true which will tell the server to continue
3✔
5036
                // reconnecting even if the number of channels with this peer is
3✔
5037
                // zero.
3✔
5038
                s.persistentPeers[targetPub] = true
3✔
5039
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
5040
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
5041
                }
3✔
5042
                s.persistentConnReqs[targetPub] = append(
3✔
5043
                        s.persistentConnReqs[targetPub], connReq,
3✔
5044
                )
3✔
5045
                s.mu.Unlock()
3✔
5046

3✔
5047
                go s.connMgr.Connect(connReq)
3✔
5048

3✔
5049
                return nil
3✔
5050
        }
5051
        s.mu.Unlock()
3✔
5052

3✔
5053
        // If we're not making a persistent connection, then we'll attempt to
3✔
5054
        // connect to the target peer. If the we can't make the connection, or
3✔
5055
        // the crypto negotiation breaks down, then return an error to the
3✔
5056
        // caller.
3✔
5057
        errChan := make(chan error, 1)
3✔
5058
        s.connectToPeer(addr, errChan, timeout)
3✔
5059

3✔
5060
        select {
3✔
5061
        case err := <-errChan:
3✔
5062
                return err
3✔
5063
        case <-s.quit:
×
5064
                return ErrServerShuttingDown
×
5065
        }
5066
}
5067

5068
// connectToPeer establishes a connection to a remote peer. errChan is used to
5069
// notify the caller if the connection attempt has failed. Otherwise, it will be
5070
// closed.
5071
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5072
        errChan chan<- error, timeout time.Duration) {
3✔
5073

3✔
5074
        conn, err := brontide.Dial(
3✔
5075
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5076
        )
3✔
5077
        if err != nil {
6✔
5078
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5079
                select {
3✔
5080
                case errChan <- err:
3✔
5081
                case <-s.quit:
×
5082
                }
5083
                return
3✔
5084
        }
5085

5086
        close(errChan)
3✔
5087

3✔
5088
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5089
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5090

3✔
5091
        s.OutboundPeerConnected(nil, conn)
3✔
5092
}
5093

5094
// DisconnectPeer sends the request to server to close the connection with peer
5095
// identified by public key.
5096
//
5097
// NOTE: This function is safe for concurrent access.
5098
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5099
        pubBytes := pubKey.SerializeCompressed()
3✔
5100
        pubStr := string(pubBytes)
3✔
5101

3✔
5102
        s.mu.Lock()
3✔
5103
        defer s.mu.Unlock()
3✔
5104

3✔
5105
        // Check that were actually connected to this peer. If not, then we'll
3✔
5106
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5107
        // currently connected to.
3✔
5108
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5109
        if err == ErrPeerNotConnected {
6✔
5110
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5111
        }
3✔
5112

5113
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5114

3✔
5115
        s.cancelConnReqs(pubStr, nil)
3✔
5116

3✔
5117
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5118
        // them from this map so we don't attempt to re-connect after we
3✔
5119
        // disconnect.
3✔
5120
        delete(s.persistentPeers, pubStr)
3✔
5121
        delete(s.persistentPeersBackoff, pubStr)
3✔
5122

3✔
5123
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5124
        // removePeer, which bypassed the peerTerminationWatcher.
3✔
5125
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5126

3✔
5127
        return nil
3✔
5128
}
5129

5130
// OpenChannel sends a request to the server to open a channel to the specified
5131
// peer identified by nodeKey with the passed channel funding parameters.
5132
//
5133
// NOTE: This function is safe for concurrent access.
5134
func (s *server) OpenChannel(
5135
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5136

3✔
5137
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5138
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5139
        // not blocked if the caller is not reading the updates.
3✔
5140
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5141
        req.Err = make(chan error, 1)
3✔
5142

3✔
5143
        // First attempt to locate the target peer to open a channel with, if
3✔
5144
        // we're unable to locate the peer then this request will fail.
3✔
5145
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5146
        s.mu.RLock()
3✔
5147
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5148
        if !ok {
3✔
5149
                s.mu.RUnlock()
×
5150

×
5151
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5152
                return req.Updates, req.Err
×
5153
        }
×
5154
        req.Peer = peer
3✔
5155
        s.mu.RUnlock()
3✔
5156

3✔
5157
        // We'll wait until the peer is active before beginning the channel
3✔
5158
        // opening process.
3✔
5159
        select {
3✔
5160
        case <-peer.ActiveSignal():
3✔
5161
        case <-peer.QuitSignal():
×
5162
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5163
                return req.Updates, req.Err
×
5164
        case <-s.quit:
×
5165
                req.Err <- ErrServerShuttingDown
×
5166
                return req.Updates, req.Err
×
5167
        }
5168

5169
        // If the fee rate wasn't specified at this point we fail the funding
5170
        // because of the missing fee rate information. The caller of the
5171
        // `OpenChannel` method needs to make sure that default values for the
5172
        // fee rate are set beforehand.
5173
        if req.FundingFeePerKw == 0 {
3✔
5174
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5175
                        "the channel opening transaction")
×
5176

×
5177
                return req.Updates, req.Err
×
5178
        }
×
5179

5180
        // Spawn a goroutine to send the funding workflow request to the funding
5181
        // manager. This allows the server to continue handling queries instead
5182
        // of blocking on this request which is exported as a synchronous
5183
        // request to the outside world.
5184
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5185

3✔
5186
        return req.Updates, req.Err
3✔
5187
}
5188

5189
// Peers returns a slice of all active peers.
5190
//
5191
// NOTE: This function is safe for concurrent access.
5192
func (s *server) Peers() []*peer.Brontide {
3✔
5193
        s.mu.RLock()
3✔
5194
        defer s.mu.RUnlock()
3✔
5195

3✔
5196
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5197
        for _, peer := range s.peersByPub {
6✔
5198
                peers = append(peers, peer)
3✔
5199
        }
3✔
5200

5201
        return peers
3✔
5202
}
5203

5204
// computeNextBackoff uses a truncated exponential backoff to compute the next
5205
// backoff using the value of the exiting backoff. The returned duration is
5206
// randomized in either direction by 1/20 to prevent tight loops from
5207
// stabilizing.
5208
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5209
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5210
        nextBackoff := 2 * currBackoff
3✔
5211
        if nextBackoff > maxBackoff {
6✔
5212
                nextBackoff = maxBackoff
3✔
5213
        }
3✔
5214

5215
        // Using 1/10 of our duration as a margin, compute a random offset to
5216
        // avoid the nodes entering connection cycles.
5217
        margin := nextBackoff / 10
3✔
5218

3✔
5219
        var wiggle big.Int
3✔
5220
        wiggle.SetUint64(uint64(margin))
3✔
5221
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5222
                // Randomizing is not mission critical, so we'll just return the
×
5223
                // current backoff.
×
5224
                return nextBackoff
×
5225
        }
×
5226

5227
        // Otherwise add in our wiggle, but subtract out half of the margin so
5228
        // that the backoff can tweaked by 1/20 in either direction.
5229
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5230
}
5231

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

5236
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5237
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
5238
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5239
        if err != nil {
3✔
5240
                return nil, err
×
5241
        }
×
5242

5243
        node, err := s.graphDB.FetchLightningNode(vertex)
3✔
5244
        if err != nil {
6✔
5245
                return nil, err
3✔
5246
        }
3✔
5247

5248
        if len(node.Addresses) == 0 {
6✔
5249
                return nil, errNoAdvertisedAddr
3✔
5250
        }
3✔
5251

5252
        return node.Addresses, nil
3✔
5253
}
5254

5255
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5256
// channel update for a target channel.
5257
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5258
        *lnwire.ChannelUpdate1, error) {
3✔
5259

3✔
5260
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5261
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5262
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5263
                if err != nil {
6✔
5264
                        return nil, err
3✔
5265
                }
3✔
5266

5267
                return netann.ExtractChannelUpdate(
3✔
5268
                        ourPubKey[:], info, edge1, edge2,
3✔
5269
                )
3✔
5270
        }
5271
}
5272

5273
// applyChannelUpdate applies the channel update to the different sub-systems of
5274
// the server. The useAlias boolean denotes whether or not to send an alias in
5275
// place of the real SCID.
5276
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5277
        op *wire.OutPoint, useAlias bool) error {
3✔
5278

3✔
5279
        var (
3✔
5280
                peerAlias    *lnwire.ShortChannelID
3✔
5281
                defaultAlias lnwire.ShortChannelID
3✔
5282
        )
3✔
5283

3✔
5284
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5285

3✔
5286
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5287
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5288
        if useAlias {
6✔
5289
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5290
                if foundAlias != defaultAlias {
6✔
5291
                        peerAlias = &foundAlias
3✔
5292
                }
3✔
5293
        }
5294

5295
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5296
                update, discovery.RemoteAlias(peerAlias),
3✔
5297
        )
3✔
5298
        select {
3✔
5299
        case err := <-errChan:
3✔
5300
                return err
3✔
5301
        case <-s.quit:
×
5302
                return ErrServerShuttingDown
×
5303
        }
5304
}
5305

5306
// SendCustomMessage sends a custom message to the peer with the specified
5307
// pubkey.
5308
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5309
        data []byte) error {
3✔
5310

3✔
5311
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5312
        if err != nil {
3✔
5313
                return err
×
5314
        }
×
5315

5316
        // We'll wait until the peer is active.
5317
        select {
3✔
5318
        case <-peer.ActiveSignal():
3✔
5319
        case <-peer.QuitSignal():
×
5320
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5321
        case <-s.quit:
×
5322
                return ErrServerShuttingDown
×
5323
        }
5324

5325
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5326
        if err != nil {
6✔
5327
                return err
3✔
5328
        }
3✔
5329

5330
        // Send the message as low-priority. For now we assume that all
5331
        // application-defined message are low priority.
5332
        return peer.SendMessageLazy(true, msg)
3✔
5333
}
5334

5335
// newSweepPkScriptGen creates closure that generates a new public key script
5336
// which should be used to sweep any funds into the on-chain wallet.
5337
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5338
// (p2wkh) output.
5339
func newSweepPkScriptGen(
5340
        wallet lnwallet.WalletController,
5341
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5342

3✔
5343
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5344
                sweepAddr, err := wallet.NewAddress(
3✔
5345
                        lnwallet.TaprootPubkey, false,
3✔
5346
                        lnwallet.DefaultAccountName,
3✔
5347
                )
3✔
5348
                if err != nil {
3✔
5349
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5350
                }
×
5351

5352
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5353
                if err != nil {
3✔
5354
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5355
                }
×
5356

5357
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5358
                        wallet, netParams, addr,
3✔
5359
                )
3✔
5360
                if err != nil {
3✔
5361
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5362
                }
×
5363

5364
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5365
                        DeliveryAddress: addr,
3✔
5366
                        InternalKey:     internalKeyDesc,
3✔
5367
                })
3✔
5368
        }
5369
}
5370

5371
// shouldPeerBootstrap returns true if we should attempt to perform peer
5372
// bootstrapping to actively seek our peers using the set of active network
5373
// bootstrappers.
5374
func shouldPeerBootstrap(cfg *Config) bool {
3✔
5375
        isSimnet := cfg.Bitcoin.SimNet
3✔
5376
        isSignet := cfg.Bitcoin.SigNet
3✔
5377
        isRegtest := cfg.Bitcoin.RegTest
3✔
5378
        isDevNetwork := isSimnet || isSignet || isRegtest
3✔
5379

3✔
5380
        // TODO(yy): remove the check on simnet/regtest such that the itest is
3✔
5381
        // covering the bootstrapping process.
3✔
5382
        return !cfg.NoNetBootstrap && !isDevNetwork
3✔
5383
}
3✔
5384

5385
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5386
// finished.
5387
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5388
        // Get a list of closed channels.
3✔
5389
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5390
        if err != nil {
3✔
5391
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5392
                return nil
×
5393
        }
×
5394

5395
        // Save the SCIDs in a map.
5396
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5397
        for _, c := range channels {
6✔
5398
                // If the channel is not pending, its FC has been finalized.
3✔
5399
                if !c.IsPending {
6✔
5400
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5401
                }
3✔
5402
        }
5403

5404
        // Double check whether the reported closed channel has indeed finished
5405
        // closing.
5406
        //
5407
        // NOTE: There are misalignments regarding when a channel's FC is
5408
        // marked as finalized. We double check the pending channels to make
5409
        // sure the returned SCIDs are indeed terminated.
5410
        //
5411
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5412
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5413
        if err != nil {
3✔
5414
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5415
                return nil
×
5416
        }
×
5417

5418
        for _, c := range pendings {
6✔
5419
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5420
                        continue
3✔
5421
                }
5422

5423
                // If the channel is still reported as pending, remove it from
5424
                // the map.
5425
                delete(closedSCIDs, c.ShortChannelID)
×
5426

×
5427
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5428
                        c.ShortChannelID)
×
5429
        }
5430

5431
        return closedSCIDs
3✔
5432
}
5433

5434
// getStartingBeat returns the current beat. This is used during the startup to
5435
// initialize blockbeat consumers.
5436
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5437
        // beat is the current blockbeat.
3✔
5438
        var beat *chainio.Beat
3✔
5439

3✔
5440
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5441
        // we will skip fetching the best block.
3✔
5442
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5443
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5444
                        "mode")
×
5445

×
5446
                return &chainio.Beat{}, nil
×
5447
        }
×
5448

5449
        // We should get a notification with the current best block immediately
5450
        // by passing a nil block.
5451
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5452
        if err != nil {
3✔
5453
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5454
        }
×
5455
        defer blockEpochs.Cancel()
3✔
5456

3✔
5457
        // We registered for the block epochs with a nil request. The notifier
3✔
5458
        // should send us the current best block immediately. So we need to
3✔
5459
        // wait for it here because we need to know the current best height.
3✔
5460
        select {
3✔
5461
        case bestBlock := <-blockEpochs.Epochs:
3✔
5462
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5463
                        bestBlock.Hash, bestBlock.Height)
3✔
5464

3✔
5465
                // Update the current blockbeat.
3✔
5466
                beat = chainio.NewBeat(*bestBlock)
3✔
5467

5468
        case <-s.quit:
×
5469
                srvrLog.Debug("LND shutting down")
×
5470
        }
5471

5472
        return beat, nil
3✔
5473
}
5474

5475
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5476
// point has an active RBF chan closer.
5477
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5478
        chanPoint wire.OutPoint) bool {
3✔
5479

3✔
5480
        pubBytes := peerPub.SerializeCompressed()
3✔
5481

3✔
5482
        s.mu.RLock()
3✔
5483
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5484
        s.mu.RUnlock()
3✔
5485
        if !ok {
3✔
5486
                return false
×
5487
        }
×
5488

5489
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5490
}
5491

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

3✔
5500
        // First, we'll attempt to look up the channel based on it's
3✔
5501
        // ChannelPoint.
3✔
5502
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5503
        if err != nil {
3✔
5504
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5505
        }
×
5506

5507
        // From the channel, we can now get the pubkey of the peer, then use
5508
        // that to eventually get the chan closer.
5509
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5510

3✔
5511
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5512
        s.mu.RLock()
3✔
5513
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5514
        s.mu.RUnlock()
3✔
5515
        if !ok {
3✔
5516
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5517
                        "not online", chanPoint)
×
5518
        }
×
5519

5520
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5521
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5522
        )
3✔
5523
        if err != nil {
3✔
5524
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5525
                        "%w", err)
×
5526
        }
×
5527

5528
        return closeUpdates, nil
3✔
5529
}
5530

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

3✔
5539
        // If the channel is present in the switch, then the request should flow
3✔
5540
        // through the switch instead.
3✔
5541
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5542
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5543
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5544
                        "invalid request", chanPoint)
×
5545
        }
×
5546

5547
        // At this point, we know that the channel isn't present in the link, so
5548
        // we'll check to see if we have an entry in the active chan closer map.
5549
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5550
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5551
        )
3✔
5552
        if err != nil {
3✔
5553
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5554
                        "ChannelPoint(%v)", chanPoint)
×
5555
        }
×
5556

5557
        return updates, nil
3✔
5558
}
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