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

lightningnetwork / lnd / 15280233992

27 May 2025 04:07PM UTC coverage: 58.56% (+0.6%) from 57.977%
15280233992

Pull #9455

github

web-flow
Merge 015c776a9 into 93a6ab875
Pull Request #9455: discovery+lnwire: add support for DNS host name in NodeAnnouncement msg

145 of 291 new or added lines in 7 files covered. (49.83%)

120 existing lines in 10 files now uncovered.

97608 of 166681 relevant lines covered (58.56%)

1.82 hits per line

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

64.41
/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/lncfg"
55
        "github.com/lightningnetwork/lnd/lnencrypt"
56
        "github.com/lightningnetwork/lnd/lnpeer"
57
        "github.com/lightningnetwork/lnd/lnrpc"
58
        "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
59
        "github.com/lightningnetwork/lnd/lnwallet"
60
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
61
        "github.com/lightningnetwork/lnd/lnwallet/chanfunding"
62
        "github.com/lightningnetwork/lnd/lnwallet/rpcwallet"
63
        "github.com/lightningnetwork/lnd/lnwire"
64
        "github.com/lightningnetwork/lnd/nat"
65
        "github.com/lightningnetwork/lnd/netann"
66
        "github.com/lightningnetwork/lnd/peer"
67
        "github.com/lightningnetwork/lnd/peernotifier"
68
        "github.com/lightningnetwork/lnd/pool"
69
        "github.com/lightningnetwork/lnd/queue"
70
        "github.com/lightningnetwork/lnd/routing"
71
        "github.com/lightningnetwork/lnd/routing/localchans"
72
        "github.com/lightningnetwork/lnd/routing/route"
73
        "github.com/lightningnetwork/lnd/subscribe"
74
        "github.com/lightningnetwork/lnd/sweep"
75
        "github.com/lightningnetwork/lnd/ticker"
76
        "github.com/lightningnetwork/lnd/tor"
77
        "github.com/lightningnetwork/lnd/walletunlocker"
78
        "github.com/lightningnetwork/lnd/watchtower/blob"
79
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
80
        "github.com/lightningnetwork/lnd/watchtower/wtpolicy"
81
        "github.com/lightningnetwork/lnd/watchtower/wtserver"
82
)
83

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

211
        start sync.Once
212
        stop  sync.Once
213

214
        cfg *Config
215

216
        implCfg *ImplementationCfg
217

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

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

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

229
        chanStatusMgr *netann.ChanStatusManager
230

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

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

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

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

251
        mu sync.RWMutex
252

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

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

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

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

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

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

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

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

303
        cc *chainreg.ChainControl
304

305
        fundingMgr *funding.Manager
306

307
        graphDB *graphdb.ChannelGraph
308

309
        chanStateDB *channeldb.ChannelStateDB
310

311
        addrSource channeldb.AddrSource
312

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

317
        invoicesDB invoices.InvoiceDB
318

319
        aliasMgr *aliasmgr.Manager
320

321
        htlcSwitch *htlcswitch.Switch
322

323
        interceptableSwitch *htlcswitch.InterceptableSwitch
324

325
        invoices *invoices.InvoiceRegistry
326

327
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
328

329
        channelNotifier *channelnotifier.ChannelNotifier
330

331
        peerNotifier *peernotifier.PeerNotifier
332

333
        htlcNotifier *htlcswitch.HtlcNotifier
334

335
        witnessBeacon contractcourt.WitnessBeacon
336

337
        breachArbitrator *contractcourt.BreachArbitrator
338

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

342
        graphBuilder *graph.Builder
343

344
        chanRouter *routing.ChannelRouter
345

346
        controlTower routing.ControlTower
347

348
        authGossiper *discovery.AuthenticatedGossiper
349

350
        localChanMgr *localchans.Manager
351

352
        utxoNursery *contractcourt.UtxoNursery
353

354
        sweeper *sweep.UtxoSweeper
355

356
        chainArb *contractcourt.ChainArbitrator
357

358
        sphinx *hop.OnionProcessor
359

360
        towerClientMgr *wtclient.Manager
361

362
        connMgr *connmgr.ConnManager
363

364
        sigPool *lnwallet.SigPool
365

366
        writePool *pool.Write
367

368
        readPool *pool.Read
369

370
        tlsManager *TLSManager
371

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

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

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

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

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

394
        hostAnn *netann.HostAnnouncer
395

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

399
        customMessageServer *subscribe.Server
400

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

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

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

411
        quit chan struct{}
412

413
        wg sync.WaitGroup
414
}
415

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

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

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

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

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

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

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

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

471
                                        s.mu.Lock()
3✔
472

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

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

487
                                        s.mu.Unlock()
3✔
488

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

495
        return nil
3✔
496
}
497

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

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

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

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

531
        // Handle the Onion address type.
532
        if tor.IsOnionHost(host) {
3✔
533
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
534
        }
×
535

536
        // For loopback or IP addresses: Use ResolveTCPAddr to properly
537
        // resolve these through Tor or other proxies, preventing IP leakage.
538
        if lncfg.IsLoopback(host) || isIP(host) || lnwire.IsIPv4Like(host) {
6✔
539
                hostPort := net.JoinHostPort(host, strconv.Itoa(port))
3✔
540
                return netCfg.ResolveTCPAddr("tcp", hostPort)
3✔
541
        }
3✔
542

543
        // Attempt to parse as a DNS address. The validation performed by
544
        // NewDNSAddr ensures compliance with BOLT-07 specifications.
545
        addr, err := lnwire.NewDNSAddr(host, port)
3✔
546
        if err != nil {
3✔
NEW
547
                return nil, err
×
NEW
548
        }
×
549

550
        return addr, nil
3✔
551
}
552

553
// parseDNSAddr parses a raw DNS address and returns a properly
554
// formatted lnwire.DNSHostnameAddress or an error.
555
func parseDNSAddr(rawAddress string,
556
        netCfg tor.Net) (*lnwire.DNSAddr, error) {
3✔
557

3✔
558
        addr, err := parseAddr(rawAddress, netCfg)
3✔
559
        if err != nil {
3✔
NEW
560
                return nil, err
×
NEW
561
        }
×
562

563
        // Check if the parsed address is a DNS address.
564
        dnsAddr, ok := addr.(*lnwire.DNSAddr)
3✔
565
        if !ok {
3✔
NEW
566
                return nil, fmt.Errorf("expected DNS hostname address, "+
×
NEW
567
                        "got %T", addr)
×
NEW
568
        }
×
569

570
        return dnsAddr, nil
3✔
571
}
572

573
// isIP checks if the provided host is an IP address (IPv4 or IPv6).
574
func isIP(host string) bool {
3✔
575
        // Try parsing the host as an IP address.
3✔
576
        ip := net.ParseIP(host)
3✔
577
        return ip != nil
3✔
578
}
3✔
579

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

3✔
585
        return func(a net.Addr) (net.Conn, error) {
6✔
586
                lnAddr := a.(*lnwire.NetAddress)
3✔
587
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
588
        }
3✔
589
}
590

591
// newServer creates a new instance of the server which is to listen using the
592
// passed listener address.
593
//
594
//nolint:funlen
595
func newServer(_ context.Context, cfg *Config, listenAddrs []net.Addr,
596
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
597
        nodeKeyDesc *keychain.KeyDescriptor,
598
        chansToRestore walletunlocker.ChannelsToRecover,
599
        chanPredicate chanacceptor.ChannelAcceptor,
600
        torController *tor.Controller, tlsManager *TLSManager,
601
        leaderElector cluster.LeaderElector,
602
        implCfg *ImplementationCfg) (*server, error) {
3✔
603

3✔
604
        var (
3✔
605
                err         error
3✔
606
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
607

3✔
608
                // We just derived the full descriptor, so we know the public
3✔
609
                // key is set on it.
3✔
610
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
3✔
611
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
3✔
612
                )
3✔
613
        )
3✔
614

3✔
615
        var serializedPubKey [33]byte
3✔
616
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
617

3✔
618
        netParams := cfg.ActiveNetParams.Params
3✔
619

3✔
620
        // Initialize the sphinx router.
3✔
621
        replayLog := htlcswitch.NewDecayedLog(
3✔
622
                dbs.DecayedLogDB, cc.ChainNotifier,
3✔
623
        )
3✔
624
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
3✔
625

3✔
626
        writeBufferPool := pool.NewWriteBuffer(
3✔
627
                pool.DefaultWriteBufferGCInterval,
3✔
628
                pool.DefaultWriteBufferExpiryInterval,
3✔
629
        )
3✔
630

3✔
631
        writePool := pool.NewWrite(
3✔
632
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
633
        )
3✔
634

3✔
635
        readBufferPool := pool.NewReadBuffer(
3✔
636
                pool.DefaultReadBufferGCInterval,
3✔
637
                pool.DefaultReadBufferExpiryInterval,
3✔
638
        )
3✔
639

3✔
640
        readPool := pool.NewRead(
3✔
641
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
642
        )
3✔
643

3✔
644
        // If the taproot overlay flag is set, but we don't have an aux funding
3✔
645
        // controller, then we'll exit as this is incompatible.
3✔
646
        if cfg.ProtocolOptions.TaprootOverlayChans &&
3✔
647
                implCfg.AuxFundingController.IsNone() {
3✔
648

×
649
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
650
                        "aux controllers")
×
651
        }
×
652

653
        //nolint:ll
654
        featureMgr, err := feature.NewManager(feature.Config{
3✔
655
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
3✔
656
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
3✔
657
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
3✔
658
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
3✔
659
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
3✔
660
                NoKeysend:                 !cfg.AcceptKeySend,
3✔
661
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
3✔
662
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
3✔
663
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
3✔
664
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
3✔
665
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
3✔
666
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
3✔
667
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
3✔
668
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
3✔
669
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
3✔
670
                NoRbfCoopClose:            !cfg.ProtocolOptions.RbfCoopClose,
3✔
671
        })
3✔
672
        if err != nil {
3✔
673
                return nil, err
×
674
        }
×
675

676
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
677
        registryConfig := invoices.RegistryConfig{
3✔
678
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
679
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
680
                Clock:                       clock.NewDefaultClock(),
3✔
681
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
682
                AcceptAMP:                   cfg.AcceptAMP,
3✔
683
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
684
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
685
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
686
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
687
        }
3✔
688

3✔
689
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
690

3✔
691
        s := &server{
3✔
692
                cfg:            cfg,
3✔
693
                implCfg:        implCfg,
3✔
694
                graphDB:        dbs.GraphDB,
3✔
695
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
696
                addrSource:     addrSource,
3✔
697
                miscDB:         dbs.ChanStateDB,
3✔
698
                invoicesDB:     dbs.InvoiceDB,
3✔
699
                cc:             cc,
3✔
700
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
701
                writePool:      writePool,
3✔
702
                readPool:       readPool,
3✔
703
                chansToRestore: chansToRestore,
3✔
704

3✔
705
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
706
                        cc.ChainNotifier,
3✔
707
                ),
3✔
708
                channelNotifier: channelnotifier.New(
3✔
709
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
710
                ),
3✔
711

3✔
712
                identityECDH:   nodeKeyECDH,
3✔
713
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
714
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
715

3✔
716
                listenAddrs: listenAddrs,
3✔
717

3✔
718
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
719
                // schedule
3✔
720
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
721

3✔
722
                torController: torController,
3✔
723

3✔
724
                persistentPeers:         make(map[string]bool),
3✔
725
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
726
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
727
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
728
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
729
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
730
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
731
                scheduledPeerConnection: make(map[string]func()),
3✔
732
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
733

3✔
734
                peersByPub:                make(map[string]*peer.Brontide),
3✔
735
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
736
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
737
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
738
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
739

3✔
740
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
741

3✔
742
                customMessageServer: subscribe.NewServer(),
3✔
743

3✔
744
                tlsManager: tlsManager,
3✔
745

3✔
746
                featureMgr: featureMgr,
3✔
747
                quit:       make(chan struct{}),
3✔
748
        }
3✔
749

3✔
750
        // Start the low-level services once they are initialized.
3✔
751
        //
3✔
752
        // TODO(yy): break the server startup into four steps,
3✔
753
        // 1. init the low-level services.
3✔
754
        // 2. start the low-level services.
3✔
755
        // 3. init the high-level services.
3✔
756
        // 4. start the high-level services.
3✔
757
        if err := s.startLowLevelServices(); err != nil {
3✔
758
                return nil, err
×
759
        }
×
760

761
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
762
        if err != nil {
3✔
763
                return nil, err
×
764
        }
×
765

766
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
767
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
768
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
769
        )
3✔
770
        s.invoices = invoices.NewRegistry(
3✔
771
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
772
        )
3✔
773

3✔
774
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
775

3✔
776
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
777
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
778

3✔
779
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
780
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
781
                if err != nil {
3✔
782
                        return err
×
783
                }
×
784

785
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
786

3✔
787
                return nil
3✔
788
        }
789

790
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
791
        if err != nil {
3✔
792
                return nil, err
×
793
        }
×
794

795
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
796
                DB:                   dbs.ChanStateDB,
3✔
797
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
798
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
799
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
800
                LocalChannelClose: func(pubKey []byte,
3✔
801
                        request *htlcswitch.ChanClose) {
6✔
802

3✔
803
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
804
                        if err != nil {
3✔
805
                                srvrLog.Errorf("unable to close channel, peer"+
×
806
                                        " with %v id can't be found: %v",
×
807
                                        pubKey, err,
×
808
                                )
×
809
                                return
×
810
                        }
×
811

812
                        peer.HandleLocalCloseChanReqs(request)
3✔
813
                },
814
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
815
                SwitchPackager:         channeldb.NewSwitchPackager(),
816
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
817
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
818
                Notifier:               s.cc.ChainNotifier,
819
                HtlcNotifier:           s.htlcNotifier,
820
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
821
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
822
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
823
                AllowCircularRoute:     cfg.AllowCircularRoute,
824
                RejectHTLC:             cfg.RejectHTLC,
825
                Clock:                  clock.NewDefaultClock(),
826
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
827
                MaxFeeExposure:         thresholdMSats,
828
                SignAliasUpdate:        s.signAliasUpdate,
829
                IsAlias:                aliasmgr.IsAlias,
830
        }, uint32(currentHeight))
831
        if err != nil {
3✔
832
                return nil, err
×
833
        }
×
834
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
3✔
835
                &htlcswitch.InterceptableSwitchConfig{
3✔
836
                        Switch:             s.htlcSwitch,
3✔
837
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
3✔
838
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
3✔
839
                        RequireInterceptor: s.cfg.RequireInterceptor,
3✔
840
                        Notifier:           s.cc.ChainNotifier,
3✔
841
                },
3✔
842
        )
3✔
843
        if err != nil {
3✔
844
                return nil, err
×
845
        }
×
846

847
        s.witnessBeacon = newPreimageBeacon(
3✔
848
                dbs.ChanStateDB.NewWitnessCache(),
3✔
849
                s.interceptableSwitch.ForwardPacket,
3✔
850
        )
3✔
851

3✔
852
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
853
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
854
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
855
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
856
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
857
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
858
                MessageSigner:            s.nodeSigner,
3✔
859
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
860
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
861
                DB:                       s.chanStateDB,
3✔
862
                Graph:                    dbs.GraphDB,
3✔
863
        }
3✔
864

3✔
865
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
866
        if err != nil {
3✔
867
                return nil, err
×
868
        }
×
869
        s.chanStatusMgr = chanStatusMgr
3✔
870

3✔
871
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
872
        // port forwarding for users behind a NAT.
3✔
873
        if cfg.NAT {
3✔
874
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
875

×
876
                discoveryTimeout := time.Duration(10 * time.Second)
×
877

×
878
                ctx, cancel := context.WithTimeout(
×
879
                        context.Background(), discoveryTimeout,
×
880
                )
×
881
                defer cancel()
×
882
                upnp, err := nat.DiscoverUPnP(ctx)
×
883
                if err == nil {
×
884
                        s.natTraversal = upnp
×
885
                } else {
×
886
                        // If we were not able to discover a UPnP enabled device
×
887
                        // on the local network, we'll fall back to attempting
×
888
                        // to discover a NAT-PMP enabled device.
×
889
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
890
                                "device on the local network: %v", err)
×
891

×
892
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
893
                                "enabled device")
×
894

×
895
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
896
                        if err != nil {
×
897
                                err := fmt.Errorf("unable to discover a "+
×
898
                                        "NAT-PMP enabled device on the local "+
×
899
                                        "network: %v", err)
×
900
                                srvrLog.Error(err)
×
901
                                return nil, err
×
902
                        }
×
903

904
                        s.natTraversal = pmp
×
905
                }
906
        }
907

908
        // If we were requested to automatically configure port forwarding,
909
        // we'll use the ports that the server will be listening on.
910
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
3✔
911
        for idx, ip := range cfg.ExternalIPs {
6✔
912
                externalIPStrings[idx] = ip.String()
3✔
913
        }
3✔
914
        if s.natTraversal != nil {
3✔
915
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
916
                for _, listenAddr := range listenAddrs {
×
917
                        // At this point, the listen addresses should have
×
918
                        // already been normalized, so it's safe to ignore the
×
919
                        // errors.
×
920
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
921
                        port, _ := strconv.Atoi(portStr)
×
922

×
923
                        listenPorts = append(listenPorts, uint16(port))
×
924
                }
×
925

926
                ips, err := s.configurePortForwarding(listenPorts...)
×
927
                if err != nil {
×
928
                        srvrLog.Errorf("Unable to automatically set up port "+
×
929
                                "forwarding using %s: %v",
×
930
                                s.natTraversal.Name(), err)
×
931
                } else {
×
932
                        srvrLog.Infof("Automatically set up port forwarding "+
×
933
                                "using %s to advertise external IP",
×
934
                                s.natTraversal.Name())
×
935
                        externalIPStrings = append(externalIPStrings, ips...)
×
936
                }
×
937
        }
938

939
        // If external IP addresses have been specified, add those to the list
940
        // of this server's addresses.
941
        externalIPs, err := lncfg.NormalizeAddresses(
3✔
942
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
943
                cfg.net.ResolveTCPAddr,
3✔
944
        )
3✔
945
        if err != nil {
3✔
946
                return nil, err
×
947
        }
×
948

949
        addrsLen := len(externalIPs)
3✔
950
        if cfg.ExternalDNSAddress != nil {
6✔
951
                addrsLen++
3✔
952
        }
3✔
953

954
        selfAddrs := make([]net.Addr, 0, addrsLen)
3✔
955
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
956

3✔
957
        if cfg.ExternalDNSAddress != nil {
6✔
958
                selfAddrs = append(selfAddrs, cfg.ExternalDNSAddress)
3✔
959
        }
3✔
960

961
        // We'll now reconstruct a node announcement based on our current
962
        // configuration so we can send it out as a sort of heart beat within
963
        // the network.
964
        //
965
        // We'll start by parsing the node color from configuration.
966
        color, err := lncfg.ParseHexColor(cfg.Color)
3✔
967
        if err != nil {
3✔
968
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
969
                return nil, err
×
970
        }
×
971

972
        // If no alias is provided, default to first 10 characters of public
973
        // key.
974
        alias := cfg.Alias
3✔
975
        if alias == "" {
6✔
976
                alias = hex.EncodeToString(serializedPubKey[:10])
3✔
977
        }
3✔
978
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
979
        if err != nil {
3✔
980
                return nil, err
×
981
        }
×
982
        selfNode := &models.LightningNode{
3✔
983
                HaveNodeAnnouncement: true,
3✔
984
                LastUpdate:           time.Now(),
3✔
985
                Addresses:            selfAddrs,
3✔
986
                Alias:                nodeAlias.String(),
3✔
987
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
988
                Color:                color,
3✔
989
        }
3✔
990
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
991

3✔
992
        // Based on the disk representation of the node announcement generated
3✔
993
        // above, we'll generate a node announcement that can go out on the
3✔
994
        // network so we can properly sign it.
3✔
995
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
996
        if err != nil {
3✔
997
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
998
        }
×
999

1000
        // With the announcement generated, we'll sign it to properly
1001
        // authenticate the message on the network.
1002
        authSig, err := netann.SignAnnouncement(
3✔
1003
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
3✔
1004
        )
3✔
1005
        if err != nil {
3✔
1006
                return nil, fmt.Errorf("unable to generate signature for "+
×
1007
                        "self node announcement: %v", err)
×
1008
        }
×
1009
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
1010
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
1011
                selfNode.AuthSigBytes,
3✔
1012
        )
3✔
1013
        if err != nil {
3✔
1014
                return nil, err
×
1015
        }
×
1016

1017
        // Finally, we'll update the representation on disk, and update our
1018
        // cached in-memory version as well.
1019
        if err := dbs.GraphDB.SetSourceNode(selfNode); err != nil {
3✔
1020
                return nil, fmt.Errorf("can't set self node: %w", err)
×
1021
        }
×
1022
        s.currentNodeAnn = nodeAnn
3✔
1023

3✔
1024
        // The router will get access to the payment ID sequencer, such that it
3✔
1025
        // can generate unique payment IDs.
3✔
1026
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
1027
        if err != nil {
3✔
1028
                return nil, err
×
1029
        }
×
1030

1031
        // Instantiate mission control with config from the sub server.
1032
        //
1033
        // TODO(joostjager): When we are further in the process of moving to sub
1034
        // servers, the mission control instance itself can be moved there too.
1035
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
1036

3✔
1037
        // We only initialize a probability estimator if there's no custom one.
3✔
1038
        var estimator routing.Estimator
3✔
1039
        if cfg.Estimator != nil {
3✔
1040
                estimator = cfg.Estimator
×
1041
        } else {
3✔
1042
                switch routingConfig.ProbabilityEstimatorType {
3✔
1043
                case routing.AprioriEstimatorName:
3✔
1044
                        aCfg := routingConfig.AprioriConfig
3✔
1045
                        aprioriConfig := routing.AprioriConfig{
3✔
1046
                                AprioriHopProbability: aCfg.HopProbability,
3✔
1047
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
1048
                                AprioriWeight:         aCfg.Weight,
3✔
1049
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
1050
                        }
3✔
1051

3✔
1052
                        estimator, err = routing.NewAprioriEstimator(
3✔
1053
                                aprioriConfig,
3✔
1054
                        )
3✔
1055
                        if err != nil {
3✔
1056
                                return nil, err
×
1057
                        }
×
1058

1059
                case routing.BimodalEstimatorName:
×
1060
                        bCfg := routingConfig.BimodalConfig
×
1061
                        bimodalConfig := routing.BimodalConfig{
×
1062
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1063
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1064
                                        bCfg.Scale,
×
1065
                                ),
×
1066
                                BimodalDecayTime: bCfg.DecayTime,
×
1067
                        }
×
1068

×
1069
                        estimator, err = routing.NewBimodalEstimator(
×
1070
                                bimodalConfig,
×
1071
                        )
×
1072
                        if err != nil {
×
1073
                                return nil, err
×
1074
                        }
×
1075

1076
                default:
×
1077
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1078
                                routingConfig.ProbabilityEstimatorType)
×
1079
                }
1080
        }
1081

1082
        mcCfg := &routing.MissionControlConfig{
3✔
1083
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
1084
                Estimator:               estimator,
3✔
1085
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
1086
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
1087
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
1088
        }
3✔
1089

3✔
1090
        s.missionController, err = routing.NewMissionController(
3✔
1091
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
1092
        )
3✔
1093
        if err != nil {
3✔
1094
                return nil, fmt.Errorf("can't create mission control "+
×
1095
                        "manager: %w", err)
×
1096
        }
×
1097
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
1098
                routing.DefaultMissionControlNamespace,
3✔
1099
        )
3✔
1100
        if err != nil {
3✔
1101
                return nil, fmt.Errorf("can't create mission control in the "+
×
1102
                        "default namespace: %w", err)
×
1103
        }
×
1104

1105
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1106
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1107
                int64(routingConfig.AttemptCost),
3✔
1108
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1109
                routingConfig.MinRouteProbability)
3✔
1110

3✔
1111
        pathFindingConfig := routing.PathFindingConfig{
3✔
1112
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1113
                        routingConfig.AttemptCost,
3✔
1114
                ),
3✔
1115
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1116
                MinProbability: routingConfig.MinRouteProbability,
3✔
1117
        }
3✔
1118

3✔
1119
        sourceNode, err := dbs.GraphDB.SourceNode()
3✔
1120
        if err != nil {
3✔
1121
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1122
        }
×
1123
        paymentSessionSource := &routing.SessionSource{
3✔
1124
                GraphSessionFactory: dbs.GraphDB,
3✔
1125
                SourceNode:          sourceNode,
3✔
1126
                MissionControl:      s.defaultMC,
3✔
1127
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1128
                PathFindingConfig:   pathFindingConfig,
3✔
1129
        }
3✔
1130

3✔
1131
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1132

3✔
1133
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1134

3✔
1135
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1136
                cfg.Routing.StrictZombiePruning
3✔
1137

3✔
1138
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1139
                SelfNode:            selfNode.PubKeyBytes,
3✔
1140
                Graph:               dbs.GraphDB,
3✔
1141
                Chain:               cc.ChainIO,
3✔
1142
                ChainView:           cc.ChainView,
3✔
1143
                Notifier:            cc.ChainNotifier,
3✔
1144
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1145
                GraphPruneInterval:  time.Hour,
3✔
1146
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1147
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1148
                StrictZombiePruning: strictPruning,
3✔
1149
                IsAlias:             aliasmgr.IsAlias,
3✔
1150
        })
3✔
1151
        if err != nil {
3✔
1152
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1153
        }
×
1154

1155
        s.chanRouter, err = routing.New(routing.Config{
3✔
1156
                SelfNode:           selfNode.PubKeyBytes,
3✔
1157
                RoutingGraph:       dbs.GraphDB,
3✔
1158
                Chain:              cc.ChainIO,
3✔
1159
                Payer:              s.htlcSwitch,
3✔
1160
                Control:            s.controlTower,
3✔
1161
                MissionControl:     s.defaultMC,
3✔
1162
                SessionSource:      paymentSessionSource,
3✔
1163
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1164
                NextPaymentID:      sequencer.NextID,
3✔
1165
                PathFindingConfig:  pathFindingConfig,
3✔
1166
                Clock:              clock.NewDefaultClock(),
3✔
1167
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1168
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1169
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1170
        })
3✔
1171
        if err != nil {
3✔
1172
                return nil, fmt.Errorf("can't create router: %w", err)
×
1173
        }
×
1174

1175
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1176
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1177
        if err != nil {
3✔
1178
                return nil, err
×
1179
        }
×
1180
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1181
        if err != nil {
3✔
1182
                return nil, err
×
1183
        }
×
1184

1185
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1186

3✔
1187
        s.authGossiper = discovery.New(discovery.Config{
3✔
1188
                Graph:                 s.graphBuilder,
3✔
1189
                ChainIO:               s.cc.ChainIO,
3✔
1190
                Notifier:              s.cc.ChainNotifier,
3✔
1191
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1192
                Broadcast:             s.BroadcastMessage,
3✔
1193
                ChanSeries:            chanSeries,
3✔
1194
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1195
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1196
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1197
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1198
                        error) {
3✔
1199

×
1200
                        return s.genNodeAnnouncement(nil)
×
1201
                },
×
1202
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1203
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1204
                RetransmitTicker:        ticker.New(time.Minute * 30),
1205
                RebroadcastInterval:     time.Hour * 24,
1206
                WaitingProofStore:       waitingProofStore,
1207
                MessageStore:            gossipMessageStore,
1208
                AnnSigner:               s.nodeSigner,
1209
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1210
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1211
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1212
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1213
                MinimumBatchSize:        10,
1214
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1215
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1216
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1217
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1218
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1219
                IsAlias:                 aliasmgr.IsAlias,
1220
                SignAliasUpdate:         s.signAliasUpdate,
1221
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1222
                GetAlias:                s.aliasMgr.GetPeerAlias,
1223
                FindChannel:             s.findChannel,
1224
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1225
                ScidCloser:              scidCloserMan,
1226
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1227
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1228
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1229
        }, nodeKeyDesc)
1230

1231
        accessCfg := &accessManConfig{
3✔
1232
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1233
                        error) {
6✔
1234

3✔
1235
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1236
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1237
                                genesisHash[:],
3✔
1238
                        )
3✔
1239
                },
3✔
1240
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1241
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1242
        }
1243

1244
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1245
        if err != nil {
3✔
1246
                return nil, err
×
1247
        }
×
1248

1249
        s.peerAccessMan = peerAccessMan
3✔
1250

3✔
1251
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1252
        //nolint:ll
3✔
1253
        s.localChanMgr = &localchans.Manager{
3✔
1254
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1255
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1256
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
3✔
1257
                        *models.ChannelEdgePolicy) error) error {
6✔
1258

3✔
1259
                        return s.graphDB.ForEachNodeChannel(selfVertex,
3✔
1260
                                func(c *models.ChannelEdgeInfo,
3✔
1261
                                        e *models.ChannelEdgePolicy,
3✔
1262
                                        _ *models.ChannelEdgePolicy) error {
6✔
1263

3✔
1264
                                        // NOTE: The invoked callback here may
3✔
1265
                                        // receive a nil channel policy.
3✔
1266
                                        return cb(c, e)
3✔
1267
                                },
3✔
1268
                        )
1269
                },
1270
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1271
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1272
                FetchChannel:              s.chanStateDB.FetchChannel,
1273
                AddEdge: func(edge *models.ChannelEdgeInfo) error {
×
1274
                        return s.graphBuilder.AddEdge(edge)
×
1275
                },
×
1276
        }
1277

1278
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1279
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1280
        )
3✔
1281
        if err != nil {
3✔
1282
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1283
                return nil, err
×
1284
        }
×
1285

1286
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1287
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1288
        )
3✔
1289
        if err != nil {
3✔
1290
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1291
                return nil, err
×
1292
        }
×
1293

1294
        aggregator := sweep.NewBudgetAggregator(
3✔
1295
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1296
                s.implCfg.AuxSweeper,
3✔
1297
        )
3✔
1298

3✔
1299
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1300
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1301
                Wallet:     cc.Wallet,
3✔
1302
                Estimator:  cc.FeeEstimator,
3✔
1303
                Notifier:   cc.ChainNotifier,
3✔
1304
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1305
        })
3✔
1306

3✔
1307
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1308
                FeeEstimator: cc.FeeEstimator,
3✔
1309
                GenSweepScript: newSweepPkScriptGen(
3✔
1310
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1311
                ),
3✔
1312
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1313
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1314
                Mempool:              cc.MempoolNotifier,
3✔
1315
                Notifier:             cc.ChainNotifier,
3✔
1316
                Store:                sweeperStore,
3✔
1317
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1318
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1319
                Aggregator:           aggregator,
3✔
1320
                Publisher:            s.txPublisher,
3✔
1321
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1322
        })
3✔
1323

3✔
1324
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1325
                ChainIO:             cc.ChainIO,
3✔
1326
                ConfDepth:           1,
3✔
1327
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1328
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1329
                Notifier:            cc.ChainNotifier,
3✔
1330
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1331
                Store:               utxnStore,
3✔
1332
                SweepInput:          s.sweeper.SweepInput,
3✔
1333
                Budget:              s.cfg.Sweeper.Budget,
3✔
1334
        })
3✔
1335

3✔
1336
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1337
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1338
                closureType contractcourt.ChannelCloseType) {
6✔
1339
                // TODO(conner): Properly respect the update and error channels
3✔
1340
                // returned by CloseLink.
3✔
1341

3✔
1342
                // Instruct the switch to close the channel.  Provide no close out
3✔
1343
                // delivery script or target fee per kw because user input is not
3✔
1344
                // available when the remote peer closes the channel.
3✔
1345
                s.htlcSwitch.CloseLink(
3✔
1346
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1347
                )
3✔
1348
        }
3✔
1349

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

3✔
1354
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1355
                &contractcourt.BreachConfig{
3✔
1356
                        CloseLink: closeLink,
3✔
1357
                        DB:        s.chanStateDB,
3✔
1358
                        Estimator: s.cc.FeeEstimator,
3✔
1359
                        GenSweepScript: newSweepPkScriptGen(
3✔
1360
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1361
                        ),
3✔
1362
                        Notifier:           cc.ChainNotifier,
3✔
1363
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1364
                        ContractBreaches:   contractBreaches,
3✔
1365
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1366
                        Store: contractcourt.NewRetributionStore(
3✔
1367
                                dbs.ChanStateDB,
3✔
1368
                        ),
3✔
1369
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1370
                },
3✔
1371
        )
3✔
1372

3✔
1373
        //nolint:ll
3✔
1374
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1375
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1376
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1377
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1378
                NewSweepAddr: func() ([]byte, error) {
3✔
1379
                        addr, err := newSweepPkScriptGen(
×
1380
                                cc.Wallet, netParams,
×
1381
                        )().Unpack()
×
1382
                        if err != nil {
×
1383
                                return nil, err
×
1384
                        }
×
1385

1386
                        return addr.DeliveryAddress, nil
×
1387
                },
1388
                PublishTx: cc.Wallet.PublishTransaction,
1389
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1390
                        for _, msg := range msgs {
6✔
1391
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1392
                                if err != nil {
3✔
1393
                                        return err
×
1394
                                }
×
1395
                        }
1396
                        return nil
3✔
1397
                },
1398
                IncubateOutputs: func(chanPoint wire.OutPoint,
1399
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1400
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1401
                        broadcastHeight uint32,
1402
                        deadlineHeight fn.Option[int32]) error {
3✔
1403

3✔
1404
                        return s.utxoNursery.IncubateOutputs(
3✔
1405
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1406
                                broadcastHeight, deadlineHeight,
3✔
1407
                        )
3✔
1408
                },
3✔
1409
                PreimageDB:   s.witnessBeacon,
1410
                Notifier:     cc.ChainNotifier,
1411
                Mempool:      cc.MempoolNotifier,
1412
                Signer:       cc.Wallet.Cfg.Signer,
1413
                FeeEstimator: cc.FeeEstimator,
1414
                ChainIO:      cc.ChainIO,
1415
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1416
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1417
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1418
                        return nil
3✔
1419
                },
3✔
1420
                IsOurAddress: cc.Wallet.IsOurAddress,
1421
                ContractBreach: func(chanPoint wire.OutPoint,
1422
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1423

3✔
1424
                        // processACK will handle the BreachArbitrator ACKing
3✔
1425
                        // the event.
3✔
1426
                        finalErr := make(chan error, 1)
3✔
1427
                        processACK := func(brarErr error) {
6✔
1428
                                if brarErr != nil {
3✔
1429
                                        finalErr <- brarErr
×
1430
                                        return
×
1431
                                }
×
1432

1433
                                // If the BreachArbitrator successfully handled
1434
                                // the event, we can signal that the handoff
1435
                                // was successful.
1436
                                finalErr <- nil
3✔
1437
                        }
1438

1439
                        event := &contractcourt.ContractBreachEvent{
3✔
1440
                                ChanPoint:         chanPoint,
3✔
1441
                                ProcessACK:        processACK,
3✔
1442
                                BreachRetribution: breachRet,
3✔
1443
                        }
3✔
1444

3✔
1445
                        // Send the contract breach event to the
3✔
1446
                        // BreachArbitrator.
3✔
1447
                        select {
3✔
1448
                        case contractBreaches <- event:
3✔
1449
                        case <-s.quit:
×
1450
                                return ErrServerShuttingDown
×
1451
                        }
1452

1453
                        // We'll wait for a final error to be available from
1454
                        // the BreachArbitrator.
1455
                        select {
3✔
1456
                        case err := <-finalErr:
3✔
1457
                                return err
3✔
1458
                        case <-s.quit:
×
1459
                                return ErrServerShuttingDown
×
1460
                        }
1461
                },
1462
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1463
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1464
                },
3✔
1465
                Sweeper:                       s.sweeper,
1466
                Registry:                      s.invoices,
1467
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1468
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1469
                OnionProcessor:                s.sphinx,
1470
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1471
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1472
                Clock:                         clock.NewDefaultClock(),
1473
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1474
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1475
                HtlcNotifier:                  s.htlcNotifier,
1476
                Budget:                        *s.cfg.Sweeper.Budget,
1477

1478
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1479
                QueryIncomingCircuit: func(
1480
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1481

3✔
1482
                        // Get the circuit map.
3✔
1483
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1484

3✔
1485
                        // Lookup the outgoing circuit.
3✔
1486
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1487
                        if pc == nil {
5✔
1488
                                return nil
2✔
1489
                        }
2✔
1490

1491
                        return &pc.Incoming
3✔
1492
                },
1493
                AuxLeafStore: implCfg.AuxLeafStore,
1494
                AuxSigner:    implCfg.AuxSigner,
1495
                AuxResolver:  implCfg.AuxContractResolver,
1496
        }, dbs.ChanStateDB)
1497

1498
        // Select the configuration and funding parameters for Bitcoin.
1499
        chainCfg := cfg.Bitcoin
3✔
1500
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1501
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1502

3✔
1503
        var chanIDSeed [32]byte
3✔
1504
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1505
                return nil, err
×
1506
        }
×
1507

1508
        // Wrap the DeleteChannelEdges method so that the funding manager can
1509
        // use it without depending on several layers of indirection.
1510
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1511
                *models.ChannelEdgePolicy, error) {
6✔
1512

3✔
1513
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1514
                        scid.ToUint64(),
3✔
1515
                )
3✔
1516
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1517
                        // This is unlikely but there is a slim chance of this
×
1518
                        // being hit if lnd was killed via SIGKILL and the
×
1519
                        // funding manager was stepping through the delete
×
1520
                        // alias edge logic.
×
1521
                        return nil, nil
×
1522
                } else if err != nil {
3✔
1523
                        return nil, err
×
1524
                }
×
1525

1526
                // Grab our key to find our policy.
1527
                var ourKey [33]byte
3✔
1528
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1529

3✔
1530
                var ourPolicy *models.ChannelEdgePolicy
3✔
1531
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1532
                        ourPolicy = e1
3✔
1533
                } else {
6✔
1534
                        ourPolicy = e2
3✔
1535
                }
3✔
1536

1537
                if ourPolicy == nil {
3✔
1538
                        // Something is wrong, so return an error.
×
1539
                        return nil, fmt.Errorf("we don't have an edge")
×
1540
                }
×
1541

1542
                err = s.graphDB.DeleteChannelEdges(
3✔
1543
                        false, false, scid.ToUint64(),
3✔
1544
                )
3✔
1545
                return ourPolicy, err
3✔
1546
        }
1547

1548
        // For the reservationTimeout and the zombieSweeperInterval different
1549
        // values are set in case we are in a dev environment so enhance test
1550
        // capacilities.
1551
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1552
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1553

3✔
1554
        // Get the development config for funding manager. If we are not in
3✔
1555
        // development mode, this would be nil.
3✔
1556
        var devCfg *funding.DevConfig
3✔
1557
        if lncfg.IsDevBuild() {
6✔
1558
                devCfg = &funding.DevConfig{
3✔
1559
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1560
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1561
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1562
                }
3✔
1563

3✔
1564
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1565
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1566

3✔
1567
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1568
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1569
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1570
        }
3✔
1571

1572
        //nolint:ll
1573
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1574
                Dev:                devCfg,
3✔
1575
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1576
                IDKey:              nodeKeyDesc.PubKey,
3✔
1577
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1578
                Wallet:             cc.Wallet,
3✔
1579
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1580
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1581
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1582
                },
3✔
1583
                Notifier:     cc.ChainNotifier,
1584
                ChannelDB:    s.chanStateDB,
1585
                FeeEstimator: cc.FeeEstimator,
1586
                SignMessage:  cc.MsgSigner.SignMessage,
1587
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1588
                        error) {
3✔
1589

3✔
1590
                        return s.genNodeAnnouncement(nil)
3✔
1591
                },
3✔
1592
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1593
                NotifyWhenOnline:     s.NotifyWhenOnline,
1594
                TempChanIDSeed:       chanIDSeed,
1595
                FindChannel:          s.findChannel,
1596
                DefaultRoutingPolicy: cc.RoutingPolicy,
1597
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1598
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1599
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1600
                        // For large channels we increase the number
3✔
1601
                        // of confirmations we require for the
3✔
1602
                        // channel to be considered open. As it is
3✔
1603
                        // always the responder that gets to choose
3✔
1604
                        // value, the pushAmt is value being pushed
3✔
1605
                        // to us. This means we have more to lose
3✔
1606
                        // in the case this gets re-orged out, and
3✔
1607
                        // we will require more confirmations before
3✔
1608
                        // we consider it open.
3✔
1609

3✔
1610
                        // In case the user has explicitly specified
3✔
1611
                        // a default value for the number of
3✔
1612
                        // confirmations, we use it.
3✔
1613
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1614
                        if defaultConf != 0 {
6✔
1615
                                return defaultConf
3✔
1616
                        }
3✔
1617

1618
                        minConf := uint64(3)
×
1619
                        maxConf := uint64(6)
×
1620

×
1621
                        // If this is a wumbo channel, then we'll require the
×
1622
                        // max amount of confirmations.
×
1623
                        if chanAmt > MaxFundingAmount {
×
1624
                                return uint16(maxConf)
×
1625
                        }
×
1626

1627
                        // If not we return a value scaled linearly
1628
                        // between 3 and 6, depending on channel size.
1629
                        // TODO(halseth): Use 1 as minimum?
1630
                        maxChannelSize := uint64(
×
1631
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1632
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1633
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1634
                        if conf < minConf {
×
1635
                                conf = minConf
×
1636
                        }
×
1637
                        if conf > maxConf {
×
1638
                                conf = maxConf
×
1639
                        }
×
1640
                        return uint16(conf)
×
1641
                },
1642
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1643
                        // We scale the remote CSV delay (the time the
3✔
1644
                        // remote have to claim funds in case of a unilateral
3✔
1645
                        // close) linearly from minRemoteDelay blocks
3✔
1646
                        // for small channels, to maxRemoteDelay blocks
3✔
1647
                        // for channels of size MaxFundingAmount.
3✔
1648

3✔
1649
                        // In case the user has explicitly specified
3✔
1650
                        // a default value for the remote delay, we
3✔
1651
                        // use it.
3✔
1652
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1653
                        if defaultDelay > 0 {
6✔
1654
                                return defaultDelay
3✔
1655
                        }
3✔
1656

1657
                        // If this is a wumbo channel, then we'll require the
1658
                        // max value.
1659
                        if chanAmt > MaxFundingAmount {
×
1660
                                return maxRemoteDelay
×
1661
                        }
×
1662

1663
                        // If not we scale according to channel size.
1664
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1665
                                chanAmt / MaxFundingAmount)
×
1666
                        if delay < minRemoteDelay {
×
1667
                                delay = minRemoteDelay
×
1668
                        }
×
1669
                        if delay > maxRemoteDelay {
×
1670
                                delay = maxRemoteDelay
×
1671
                        }
×
1672
                        return delay
×
1673
                },
1674
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1675
                        peerKey *btcec.PublicKey) error {
3✔
1676

3✔
1677
                        // First, we'll mark this new peer as a persistent peer
3✔
1678
                        // for re-connection purposes. If the peer is not yet
3✔
1679
                        // tracked or the user hasn't requested it to be perm,
3✔
1680
                        // we'll set false to prevent the server from continuing
3✔
1681
                        // to connect to this peer even if the number of
3✔
1682
                        // channels with this peer is zero.
3✔
1683
                        s.mu.Lock()
3✔
1684
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1685
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1686
                                s.persistentPeers[pubStr] = false
3✔
1687
                        }
3✔
1688
                        s.mu.Unlock()
3✔
1689

3✔
1690
                        // With that taken care of, we'll send this channel to
3✔
1691
                        // the chain arb so it can react to on-chain events.
3✔
1692
                        return s.chainArb.WatchNewChannel(channel)
3✔
1693
                },
1694
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1695
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1696
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1697
                },
3✔
1698
                RequiredRemoteChanReserve: func(chanAmt,
1699
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1700

3✔
1701
                        // By default, we'll require the remote peer to maintain
3✔
1702
                        // at least 1% of the total channel capacity at all
3✔
1703
                        // times. If this value ends up dipping below the dust
3✔
1704
                        // limit, then we'll use the dust limit itself as the
3✔
1705
                        // reserve as required by BOLT #2.
3✔
1706
                        reserve := chanAmt / 100
3✔
1707
                        if reserve < dustLimit {
6✔
1708
                                reserve = dustLimit
3✔
1709
                        }
3✔
1710

1711
                        return reserve
3✔
1712
                },
1713
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1714
                        // By default, we'll allow the remote peer to fully
3✔
1715
                        // utilize the full bandwidth of the channel, minus our
3✔
1716
                        // required reserve.
3✔
1717
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1718
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1719
                },
3✔
1720
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1721
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1722
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1723
                        }
3✔
1724

1725
                        // By default, we'll permit them to utilize the full
1726
                        // channel bandwidth.
1727
                        return uint16(input.MaxHTLCNumber / 2)
×
1728
                },
1729
                ZombieSweeperInterval:         zombieSweeperInterval,
1730
                ReservationTimeout:            reservationTimeout,
1731
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1732
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1733
                MaxPendingChannels:            cfg.MaxPendingChannels,
1734
                RejectPush:                    cfg.RejectPush,
1735
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1736
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1737
                OpenChannelPredicate:          chanPredicate,
1738
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1739
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1740
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1741
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1742
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1743
                DeleteAliasEdge:      deleteAliasEdge,
1744
                AliasManager:         s.aliasMgr,
1745
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1746
                AuxFundingController: implCfg.AuxFundingController,
1747
                AuxSigner:            implCfg.AuxSigner,
1748
                AuxResolver:          implCfg.AuxContractResolver,
1749
        })
1750
        if err != nil {
3✔
1751
                return nil, err
×
1752
        }
×
1753

1754
        // Next, we'll assemble the sub-system that will maintain an on-disk
1755
        // static backup of the latest channel state.
1756
        chanNotifier := &channelNotifier{
3✔
1757
                chanNotifier: s.channelNotifier,
3✔
1758
                addrs:        s.addrSource,
3✔
1759
        }
3✔
1760
        backupFile := chanbackup.NewMultiFile(
3✔
1761
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1762
        )
3✔
1763
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1764
                s.chanStateDB, s.addrSource,
3✔
1765
        )
3✔
1766
        if err != nil {
3✔
1767
                return nil, err
×
1768
        }
×
1769
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1770
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1771
        )
3✔
1772
        if err != nil {
3✔
1773
                return nil, err
×
1774
        }
×
1775

1776
        // Assemble a peer notifier which will provide clients with subscriptions
1777
        // to peer online and offline events.
1778
        s.peerNotifier = peernotifier.New()
3✔
1779

3✔
1780
        // Create a channel event store which monitors all open channels.
3✔
1781
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1782
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1783
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1784
                },
3✔
1785
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1786
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1787
                },
3✔
1788
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1789
                Clock:           clock.NewDefaultClock(),
1790
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1791
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1792
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1793
        })
1794

1795
        if cfg.WtClient.Active {
6✔
1796
                policy := wtpolicy.DefaultPolicy()
3✔
1797
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1798

3✔
1799
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1800
                // protocol operations on sat/kw.
3✔
1801
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1802
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1803
                )
3✔
1804

3✔
1805
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1806

3✔
1807
                if err := policy.Validate(); err != nil {
3✔
1808
                        return nil, err
×
1809
                }
×
1810

1811
                // authDial is the wrapper around the btrontide.Dial for the
1812
                // watchtower.
1813
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1814
                        netAddr *lnwire.NetAddress,
3✔
1815
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1816

3✔
1817
                        return brontide.Dial(
3✔
1818
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1819
                        )
3✔
1820
                }
3✔
1821

1822
                // buildBreachRetribution is a call-back that can be used to
1823
                // query the BreachRetribution info and channel type given a
1824
                // channel ID and commitment height.
1825
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1826
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1827
                        channeldb.ChannelType, error) {
6✔
1828

3✔
1829
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1830
                                nil, chanID,
3✔
1831
                        )
3✔
1832
                        if err != nil {
3✔
1833
                                return nil, 0, err
×
1834
                        }
×
1835

1836
                        br, err := lnwallet.NewBreachRetribution(
3✔
1837
                                channel, commitHeight, 0, nil,
3✔
1838
                                implCfg.AuxLeafStore,
3✔
1839
                                implCfg.AuxContractResolver,
3✔
1840
                        )
3✔
1841
                        if err != nil {
3✔
1842
                                return nil, 0, err
×
1843
                        }
×
1844

1845
                        return br, channel.ChanType, nil
3✔
1846
                }
1847

1848
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1849

3✔
1850
                // Copy the policy for legacy channels and set the blob flag
3✔
1851
                // signalling support for anchor channels.
3✔
1852
                anchorPolicy := policy
3✔
1853
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1854

3✔
1855
                // Copy the policy for legacy channels and set the blob flag
3✔
1856
                // signalling support for taproot channels.
3✔
1857
                taprootPolicy := policy
3✔
1858
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1859
                        blob.FlagTaprootChannel,
3✔
1860
                )
3✔
1861

3✔
1862
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1863
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1864
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1865
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1866
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1867
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1868
                                error) {
6✔
1869

3✔
1870
                                return s.channelNotifier.
3✔
1871
                                        SubscribeChannelEvents()
3✔
1872
                        },
3✔
1873
                        Signer: cc.Wallet.Cfg.Signer,
1874
                        NewAddress: func() ([]byte, error) {
3✔
1875
                                addr, err := newSweepPkScriptGen(
3✔
1876
                                        cc.Wallet, netParams,
3✔
1877
                                )().Unpack()
3✔
1878
                                if err != nil {
3✔
1879
                                        return nil, err
×
1880
                                }
×
1881

1882
                                return addr.DeliveryAddress, nil
3✔
1883
                        },
1884
                        SecretKeyRing:      s.cc.KeyRing,
1885
                        Dial:               cfg.net.Dial,
1886
                        AuthDial:           authDial,
1887
                        DB:                 dbs.TowerClientDB,
1888
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1889
                        MinBackoff:         10 * time.Second,
1890
                        MaxBackoff:         5 * time.Minute,
1891
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1892
                }, policy, anchorPolicy, taprootPolicy)
1893
                if err != nil {
3✔
1894
                        return nil, err
×
1895
                }
×
1896
        }
1897

1898
        if len(cfg.ExternalHosts) != 0 {
3✔
1899
                advertisedIPs := make(map[string]struct{})
×
1900
                for _, addr := range s.currentNodeAnn.Addresses {
×
1901
                        advertisedIPs[addr.String()] = struct{}{}
×
1902
                }
×
1903

1904
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1905
                        Hosts:         cfg.ExternalHosts,
×
1906
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1907
                        LookupHost: func(host string) (net.Addr, error) {
×
1908
                                return lncfg.ParseAddressString(
×
1909
                                        host, strconv.Itoa(defaultPeerPort),
×
1910
                                        cfg.net.ResolveTCPAddr,
×
1911
                                )
×
1912
                        },
×
1913
                        AdvertisedIPs: advertisedIPs,
1914
                        AnnounceNewIPs: netann.IPAnnouncer(
1915
                                func(modifier ...netann.NodeAnnModifier) (
1916
                                        lnwire.NodeAnnouncement, error) {
×
1917

×
1918
                                        return s.genNodeAnnouncement(
×
1919
                                                nil, modifier...,
×
1920
                                        )
×
1921
                                }),
×
1922
                })
1923
        }
1924

1925
        // Create liveness monitor.
1926
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1927

3✔
1928
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1929
        for i, listenAddr := range listenAddrs {
6✔
1930
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1931
                // doesn't need to call the general lndResolveTCP function
3✔
1932
                // since we are resolving a local address.
3✔
1933

3✔
1934
                // RESOLVE: We are actually partially accepting inbound
3✔
1935
                // connection requests when we call NewListener.
3✔
1936
                listeners[i], err = brontide.NewListener(
3✔
1937
                        nodeKeyECDH, listenAddr.String(),
3✔
1938
                        s.peerAccessMan.checkIncomingConnBanScore,
3✔
1939
                )
3✔
1940
                if err != nil {
3✔
1941
                        return nil, err
×
1942
                }
×
1943
        }
1944

1945
        // Create the connection manager which will be responsible for
1946
        // maintaining persistent outbound connections and also accepting new
1947
        // incoming connections
1948
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1949
                Listeners:      listeners,
3✔
1950
                OnAccept:       s.InboundPeerConnected,
3✔
1951
                RetryDuration:  time.Second * 5,
3✔
1952
                TargetOutbound: 100,
3✔
1953
                Dial: noiseDial(
3✔
1954
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1955
                ),
3✔
1956
                OnConnection: s.OutboundPeerConnected,
3✔
1957
        })
3✔
1958
        if err != nil {
3✔
1959
                return nil, err
×
1960
        }
×
1961
        s.connMgr = cmgr
3✔
1962

3✔
1963
        // Finally, register the subsystems in blockbeat.
3✔
1964
        s.registerBlockConsumers()
3✔
1965

3✔
1966
        return s, nil
3✔
1967
}
1968

1969
// UpdateRoutingConfig is a callback function to update the routing config
1970
// values in the main cfg.
1971
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1972
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1973

3✔
1974
        switch c := cfg.Estimator.Config().(type) {
3✔
1975
        case routing.AprioriConfig:
3✔
1976
                routerCfg.ProbabilityEstimatorType =
3✔
1977
                        routing.AprioriEstimatorName
3✔
1978

3✔
1979
                targetCfg := routerCfg.AprioriConfig
3✔
1980
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1981
                targetCfg.Weight = c.AprioriWeight
3✔
1982
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1983
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1984

1985
        case routing.BimodalConfig:
3✔
1986
                routerCfg.ProbabilityEstimatorType =
3✔
1987
                        routing.BimodalEstimatorName
3✔
1988

3✔
1989
                targetCfg := routerCfg.BimodalConfig
3✔
1990
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1991
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1992
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1993
        }
1994

1995
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1996
}
1997

1998
// registerBlockConsumers registers the subsystems that consume block events.
1999
// By calling `RegisterQueue`, a list of subsystems are registered in the
2000
// blockbeat for block notifications. When a new block arrives, the subsystems
2001
// in the same queue are notified sequentially, and different queues are
2002
// notified concurrently.
2003
//
2004
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
2005
// a new `RegisterQueue` call.
2006
func (s *server) registerBlockConsumers() {
3✔
2007
        // In this queue, when a new block arrives, it will be received and
3✔
2008
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
2009
        consumers := []chainio.Consumer{
3✔
2010
                s.chainArb,
3✔
2011
                s.sweeper,
3✔
2012
                s.txPublisher,
3✔
2013
        }
3✔
2014
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
2015
}
3✔
2016

2017
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
2018
// used for option_scid_alias channels where the ChannelUpdate to be sent back
2019
// may differ from what is on disk.
2020
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
2021
        error) {
3✔
2022

3✔
2023
        data, err := u.DataToSign()
3✔
2024
        if err != nil {
3✔
2025
                return nil, err
×
2026
        }
×
2027

2028
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
2029
}
2030

2031
// createLivenessMonitor creates a set of health checks using our configured
2032
// values and uses these checks to create a liveness monitor. Available
2033
// health checks,
2034
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
2035
//   - diskCheck
2036
//   - tlsHealthCheck
2037
//   - torController, only created when tor is enabled.
2038
//
2039
// If a health check has been disabled by setting attempts to 0, our monitor
2040
// will not run it.
2041
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
2042
        leaderElector cluster.LeaderElector) {
3✔
2043

3✔
2044
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
2045
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
2046
                srvrLog.Info("Disabling chain backend checks for " +
×
2047
                        "nochainbackend mode")
×
2048

×
2049
                chainBackendAttempts = 0
×
2050
        }
×
2051

2052
        chainHealthCheck := healthcheck.NewObservation(
3✔
2053
                "chain backend",
3✔
2054
                cc.HealthCheck,
3✔
2055
                cfg.HealthChecks.ChainCheck.Interval,
3✔
2056
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
2057
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
2058
                chainBackendAttempts,
3✔
2059
        )
3✔
2060

3✔
2061
        diskCheck := healthcheck.NewObservation(
3✔
2062
                "disk space",
3✔
2063
                func() error {
3✔
2064
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2065
                                cfg.LndDir,
×
2066
                        )
×
2067
                        if err != nil {
×
2068
                                return err
×
2069
                        }
×
2070

2071
                        // If we have more free space than we require,
2072
                        // we return a nil error.
2073
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2074
                                return nil
×
2075
                        }
×
2076

2077
                        return fmt.Errorf("require: %v free space, got: %v",
×
2078
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2079
                                free)
×
2080
                },
2081
                cfg.HealthChecks.DiskCheck.Interval,
2082
                cfg.HealthChecks.DiskCheck.Timeout,
2083
                cfg.HealthChecks.DiskCheck.Backoff,
2084
                cfg.HealthChecks.DiskCheck.Attempts,
2085
        )
2086

2087
        tlsHealthCheck := healthcheck.NewObservation(
3✔
2088
                "tls",
3✔
2089
                func() error {
3✔
2090
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2091
                                s.cc.KeyRing,
×
2092
                        )
×
2093
                        if err != nil {
×
2094
                                return err
×
2095
                        }
×
2096
                        if expired {
×
2097
                                return fmt.Errorf("TLS certificate is "+
×
2098
                                        "expired as of %v", expTime)
×
2099
                        }
×
2100

2101
                        // If the certificate is not outdated, no error needs
2102
                        // to be returned
2103
                        return nil
×
2104
                },
2105
                cfg.HealthChecks.TLSCheck.Interval,
2106
                cfg.HealthChecks.TLSCheck.Timeout,
2107
                cfg.HealthChecks.TLSCheck.Backoff,
2108
                cfg.HealthChecks.TLSCheck.Attempts,
2109
        )
2110

2111
        checks := []*healthcheck.Observation{
3✔
2112
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2113
        }
3✔
2114

3✔
2115
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2116
        if s.torController != nil {
3✔
2117
                torConnectionCheck := healthcheck.NewObservation(
×
2118
                        "tor connection",
×
2119
                        func() error {
×
2120
                                return healthcheck.CheckTorServiceStatus(
×
2121
                                        s.torController,
×
2122
                                        s.createNewHiddenService,
×
2123
                                )
×
2124
                        },
×
2125
                        cfg.HealthChecks.TorConnection.Interval,
2126
                        cfg.HealthChecks.TorConnection.Timeout,
2127
                        cfg.HealthChecks.TorConnection.Backoff,
2128
                        cfg.HealthChecks.TorConnection.Attempts,
2129
                )
2130
                checks = append(checks, torConnectionCheck)
×
2131
        }
2132

2133
        // If remote signing is enabled, add the healthcheck for the remote
2134
        // signing RPC interface.
2135
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2136
                // Because we have two cascading timeouts here, we need to add
3✔
2137
                // some slack to the "outer" one of them in case the "inner"
3✔
2138
                // returns exactly on time.
3✔
2139
                overhead := time.Millisecond * 10
3✔
2140

3✔
2141
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2142
                        "remote signer connection",
3✔
2143
                        rpcwallet.HealthCheck(
3✔
2144
                                s.cfg.RemoteSigner,
3✔
2145

3✔
2146
                                // For the health check we might to be even
3✔
2147
                                // stricter than the initial/normal connect, so
3✔
2148
                                // we use the health check timeout here.
3✔
2149
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2150
                        ),
3✔
2151
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2152
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2153
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2154
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2155
                )
3✔
2156
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2157
        }
3✔
2158

2159
        // If we have a leader elector, we add a health check to ensure we are
2160
        // still the leader. During normal operation, we should always be the
2161
        // leader, but there are circumstances where this may change, such as
2162
        // when we lose network connectivity for long enough expiring out lease.
2163
        if leaderElector != nil {
3✔
2164
                leaderCheck := healthcheck.NewObservation(
×
2165
                        "leader status",
×
2166
                        func() error {
×
2167
                                // Check if we are still the leader. Note that
×
2168
                                // we don't need to use a timeout context here
×
2169
                                // as the healthcheck observer will handle the
×
2170
                                // timeout case for us.
×
2171
                                timeoutCtx, cancel := context.WithTimeout(
×
2172
                                        context.Background(),
×
2173
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2174
                                )
×
2175
                                defer cancel()
×
2176

×
2177
                                leader, err := leaderElector.IsLeader(
×
2178
                                        timeoutCtx,
×
2179
                                )
×
2180
                                if err != nil {
×
2181
                                        return fmt.Errorf("unable to check if "+
×
2182
                                                "still leader: %v", err)
×
2183
                                }
×
2184

2185
                                if !leader {
×
2186
                                        srvrLog.Debug("Not the current leader")
×
2187
                                        return fmt.Errorf("not the current " +
×
2188
                                                "leader")
×
2189
                                }
×
2190

2191
                                return nil
×
2192
                        },
2193
                        cfg.HealthChecks.LeaderCheck.Interval,
2194
                        cfg.HealthChecks.LeaderCheck.Timeout,
2195
                        cfg.HealthChecks.LeaderCheck.Backoff,
2196
                        cfg.HealthChecks.LeaderCheck.Attempts,
2197
                )
2198

2199
                checks = append(checks, leaderCheck)
×
2200
        }
2201

2202
        // If we have not disabled all of our health checks, we create a
2203
        // liveness monitor with our configured checks.
2204
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2205
                &healthcheck.Config{
3✔
2206
                        Checks:   checks,
3✔
2207
                        Shutdown: srvrLog.Criticalf,
3✔
2208
                },
3✔
2209
        )
3✔
2210
}
2211

2212
// Started returns true if the server has been started, and false otherwise.
2213
// NOTE: This function is safe for concurrent access.
2214
func (s *server) Started() bool {
3✔
2215
        return atomic.LoadInt32(&s.active) != 0
3✔
2216
}
3✔
2217

2218
// cleaner is used to aggregate "cleanup" functions during an operation that
2219
// starts several subsystems. In case one of the subsystem fails to start
2220
// and a proper resource cleanup is required, the "run" method achieves this
2221
// by running all these added "cleanup" functions.
2222
type cleaner []func() error
2223

2224
// add is used to add a cleanup function to be called when
2225
// the run function is executed.
2226
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2227
        return append(c, cleanup)
3✔
2228
}
3✔
2229

2230
// run is used to run all the previousely added cleanup functions.
2231
func (c cleaner) run() {
×
2232
        for i := len(c) - 1; i >= 0; i-- {
×
2233
                if err := c[i](); err != nil {
×
2234
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2235
                }
×
2236
        }
2237
}
2238

2239
// startLowLevelServices starts the low-level services of the server. These
2240
// services must be started successfully before running the main server. The
2241
// services are,
2242
// 1. the chain notifier.
2243
//
2244
// TODO(yy): identify and add more low-level services here.
2245
func (s *server) startLowLevelServices() error {
3✔
2246
        var startErr error
3✔
2247

3✔
2248
        cleanup := cleaner{}
3✔
2249

3✔
2250
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2251
        if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2252
                startErr = err
×
2253
        }
×
2254

2255
        if startErr != nil {
3✔
2256
                cleanup.run()
×
2257
        }
×
2258

2259
        return startErr
3✔
2260
}
2261

2262
// Start starts the main daemon server, all requested listeners, and any helper
2263
// goroutines.
2264
// NOTE: This function is safe for concurrent access.
2265
//
2266
//nolint:funlen
2267
func (s *server) Start(ctx context.Context) error {
3✔
2268
        // Get the current blockbeat.
3✔
2269
        beat, err := s.getStartingBeat()
3✔
2270
        if err != nil {
3✔
2271
                return err
×
2272
        }
×
2273

2274
        var startErr error
3✔
2275

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

3✔
2281
        s.start.Do(func() {
6✔
2282
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2283
                if err := s.customMessageServer.Start(); err != nil {
3✔
2284
                        startErr = err
×
2285
                        return
×
2286
                }
×
2287

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

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

2304
                // Start the notification server. This is used so channel
2305
                // management goroutines can be notified when a funding
2306
                // transaction reaches a sufficient number of confirmations, or
2307
                // when the input for the funding transaction is spent in an
2308
                // attempt at an uncooperative close by the counterparty.
2309
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2310
                if err := s.sigPool.Start(); err != nil {
3✔
2311
                        startErr = err
×
2312
                        return
×
2313
                }
×
2314

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

2321
                cleanup = cleanup.add(s.readPool.Stop)
3✔
2322
                if err := s.readPool.Start(); err != nil {
3✔
2323
                        startErr = err
×
2324
                        return
×
2325
                }
×
2326

2327
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
2328
                if err := s.cc.BestBlockTracker.Start(); err != nil {
3✔
2329
                        startErr = err
×
2330
                        return
×
2331
                }
×
2332

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

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

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

2353
                if s.towerClientMgr != nil {
6✔
2354
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
3✔
2355
                        if err := s.towerClientMgr.Start(); err != nil {
3✔
2356
                                startErr = err
×
2357
                                return
×
2358
                        }
×
2359
                }
2360

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

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

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

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

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

2391
                // htlcSwitch must be started before chainArb since the latter
2392
                // relies on htlcSwitch to deliver resolution message upon
2393
                // start.
2394
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2395
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2396
                        startErr = err
×
2397
                        return
×
2398
                }
×
2399

2400
                cleanup = cleanup.add(s.interceptableSwitch.Stop)
3✔
2401
                if err := s.interceptableSwitch.Start(); err != nil {
3✔
2402
                        startErr = err
×
2403
                        return
×
2404
                }
×
2405

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

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

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

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

2430
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2431
                if err := s.chanRouter.Start(); err != nil {
3✔
2432
                        startErr = err
×
2433
                        return
×
2434
                }
×
2435
                // The authGossiper depends on the chanRouter and therefore
2436
                // should be started after it.
2437
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2438
                if err := s.authGossiper.Start(); err != nil {
3✔
2439
                        startErr = err
×
2440
                        return
×
2441
                }
×
2442

2443
                cleanup = cleanup.add(s.invoices.Stop)
3✔
2444
                if err := s.invoices.Start(); err != nil {
3✔
2445
                        startErr = err
×
2446
                        return
×
2447
                }
×
2448

2449
                cleanup = cleanup.add(s.sphinx.Stop)
3✔
2450
                if err := s.sphinx.Start(); err != nil {
3✔
2451
                        startErr = err
×
2452
                        return
×
2453
                }
×
2454

2455
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
2456
                if err := s.chanStatusMgr.Start(); err != nil {
3✔
2457
                        startErr = err
×
2458
                        return
×
2459
                }
×
2460

2461
                cleanup = cleanup.add(s.chanEventStore.Stop)
3✔
2462
                if err := s.chanEventStore.Start(); err != nil {
3✔
2463
                        startErr = err
×
2464
                        return
×
2465
                }
×
2466

2467
                cleanup.add(func() error {
3✔
2468
                        s.missionController.StopStoreTickers()
×
2469
                        return nil
×
2470
                })
×
2471
                s.missionController.RunStoreTickers()
3✔
2472

3✔
2473
                // Before we start the connMgr, we'll check to see if we have
3✔
2474
                // any backups to recover. We do this now as we want to ensure
3✔
2475
                // that have all the information we need to handle channel
3✔
2476
                // recovery _before_ we even accept connections from any peers.
3✔
2477
                chanRestorer := &chanDBRestorer{
3✔
2478
                        db:         s.chanStateDB,
3✔
2479
                        secretKeys: s.cc.KeyRing,
3✔
2480
                        chainArb:   s.chainArb,
3✔
2481
                }
3✔
2482
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2483
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2484
                                s.chansToRestore.PackedSingleChanBackups,
×
2485
                                s.cc.KeyRing, chanRestorer, s,
×
2486
                        )
×
2487
                        if err != nil {
×
2488
                                startErr = fmt.Errorf("unable to unpack single "+
×
2489
                                        "backups: %v", err)
×
2490
                                return
×
2491
                        }
×
2492
                }
2493
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2494
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2495
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2496
                                s.cc.KeyRing, chanRestorer, s,
3✔
2497
                        )
3✔
2498
                        if err != nil {
3✔
2499
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2500
                                        "backup: %v", err)
×
2501
                                return
×
2502
                        }
×
2503
                }
2504

2505
                // chanSubSwapper must be started after the `channelNotifier`
2506
                // because it depends on channel events as a synchronization
2507
                // point.
2508
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2509
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2510
                        startErr = err
×
2511
                        return
×
2512
                }
×
2513

2514
                if s.torController != nil {
3✔
2515
                        cleanup = cleanup.add(s.torController.Stop)
×
2516
                        if err := s.createNewHiddenService(); err != nil {
×
2517
                                startErr = err
×
2518
                                return
×
2519
                        }
×
2520
                }
2521

2522
                if s.natTraversal != nil {
3✔
2523
                        s.wg.Add(1)
×
2524
                        go s.watchExternalIP()
×
2525
                }
×
2526

2527
                // Start connmgr last to prevent connections before init.
2528
                cleanup = cleanup.add(func() error {
3✔
2529
                        s.connMgr.Stop()
×
2530
                        return nil
×
2531
                })
×
2532

2533
                // RESOLVE: s.connMgr.Start() is called here, but
2534
                // brontide.NewListener() is called in newServer. This means
2535
                // that we are actually listening and partially accepting
2536
                // inbound connections even before the connMgr starts.
2537
                //
2538
                // TODO(yy): move the log into the connMgr's `Start` method.
2539
                srvrLog.Info("connMgr starting...")
3✔
2540
                s.connMgr.Start()
3✔
2541
                srvrLog.Debug("connMgr started")
3✔
2542

3✔
2543
                // If peers are specified as a config option, we'll add those
3✔
2544
                // peers first.
3✔
2545
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2546
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2547
                                peerAddrCfg,
3✔
2548
                        )
3✔
2549
                        if err != nil {
3✔
2550
                                startErr = fmt.Errorf("unable to parse peer "+
×
2551
                                        "pubkey from config: %v", err)
×
2552
                                return
×
2553
                        }
×
2554
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2555
                        if err != nil {
3✔
2556
                                startErr = fmt.Errorf("unable to parse peer "+
×
2557
                                        "address provided as a config option: "+
×
2558
                                        "%v", err)
×
2559
                                return
×
2560
                        }
×
2561

2562
                        peerAddr := &lnwire.NetAddress{
3✔
2563
                                IdentityKey: parsedPubkey,
3✔
2564
                                Address:     addr,
3✔
2565
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2566
                        }
3✔
2567

3✔
2568
                        err = s.ConnectToPeer(
3✔
2569
                                peerAddr, true,
3✔
2570
                                s.cfg.ConnectionTimeout,
3✔
2571
                        )
3✔
2572
                        if err != nil {
3✔
2573
                                startErr = fmt.Errorf("unable to connect to "+
×
2574
                                        "peer address provided as a config "+
×
2575
                                        "option: %v", err)
×
2576
                                return
×
2577
                        }
×
2578
                }
2579

2580
                // Subscribe to NodeAnnouncements that advertise new addresses
2581
                // our persistent peers.
2582
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2583
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2584
                                "addr: %v", err)
×
2585

×
2586
                        startErr = err
×
2587
                        return
×
2588
                }
×
2589

2590
                // With all the relevant sub-systems started, we'll now attempt
2591
                // to establish persistent connections to our direct channel
2592
                // collaborators within the network. Before doing so however,
2593
                // we'll prune our set of link nodes found within the database
2594
                // to ensure we don't reconnect to any nodes we no longer have
2595
                // open channels with.
2596
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2597
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2598

×
2599
                        startErr = err
×
2600
                        return
×
2601
                }
×
2602

2603
                if err := s.establishPersistentConnections(); err != nil {
3✔
2604
                        srvrLog.Errorf("Failed to establish persistent "+
×
2605
                                "connections: %v", err)
×
2606
                }
×
2607

2608
                // setSeedList is a helper function that turns multiple DNS seed
2609
                // server tuples from the command line or config file into the
2610
                // data structure we need and does a basic formal sanity check
2611
                // in the process.
2612
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2613
                        if len(tuples) == 0 {
×
2614
                                return
×
2615
                        }
×
2616

2617
                        result := make([][2]string, len(tuples))
×
2618
                        for idx, tuple := range tuples {
×
2619
                                tuple = strings.TrimSpace(tuple)
×
2620
                                if len(tuple) == 0 {
×
2621
                                        return
×
2622
                                }
×
2623

2624
                                servers := strings.Split(tuple, ",")
×
2625
                                if len(servers) > 2 || len(servers) == 0 {
×
2626
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2627
                                                "seed tuple: %v", servers)
×
2628
                                        return
×
2629
                                }
×
2630

2631
                                copy(result[idx][:], servers)
×
2632
                        }
2633

2634
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2635
                }
2636

2637
                // Let users overwrite the DNS seed nodes. We only allow them
2638
                // for bitcoin mainnet/testnet/signet.
2639
                if s.cfg.Bitcoin.MainNet {
3✔
2640
                        setSeedList(
×
2641
                                s.cfg.Bitcoin.DNSSeeds,
×
2642
                                chainreg.BitcoinMainnetGenesis,
×
2643
                        )
×
2644
                }
×
2645
                if s.cfg.Bitcoin.TestNet3 {
3✔
2646
                        setSeedList(
×
2647
                                s.cfg.Bitcoin.DNSSeeds,
×
2648
                                chainreg.BitcoinTestnetGenesis,
×
2649
                        )
×
2650
                }
×
2651
                if s.cfg.Bitcoin.TestNet4 {
3✔
2652
                        setSeedList(
×
2653
                                s.cfg.Bitcoin.DNSSeeds,
×
2654
                                chainreg.BitcoinTestnet4Genesis,
×
2655
                        )
×
2656
                }
×
2657
                if s.cfg.Bitcoin.SigNet {
3✔
2658
                        setSeedList(
×
2659
                                s.cfg.Bitcoin.DNSSeeds,
×
2660
                                chainreg.BitcoinSignetGenesis,
×
2661
                        )
×
2662
                }
×
2663

2664
                // If network bootstrapping hasn't been disabled, then we'll
2665
                // configure the set of active bootstrappers, and launch a
2666
                // dedicated goroutine to maintain a set of persistent
2667
                // connections.
2668
                if shouldPeerBootstrap(s.cfg) {
3✔
2669
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2670
                        if err != nil {
×
2671
                                startErr = err
×
2672
                                return
×
2673
                        }
×
2674

2675
                        s.wg.Add(1)
×
2676
                        go s.peerBootstrapper(
×
2677
                                ctx, defaultMinPeers, bootstrappers,
×
2678
                        )
×
2679
                } else {
3✔
2680
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2681
                }
3✔
2682

2683
                // Start the blockbeat after all other subsystems have been
2684
                // started so they are ready to receive new blocks.
2685
                cleanup = cleanup.add(func() error {
3✔
2686
                        s.blockbeatDispatcher.Stop()
×
2687
                        return nil
×
2688
                })
×
2689
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2690
                        startErr = err
×
2691
                        return
×
2692
                }
×
2693

2694
                // Set the active flag now that we've completed the full
2695
                // startup.
2696
                atomic.StoreInt32(&s.active, 1)
3✔
2697
        })
2698

2699
        if startErr != nil {
3✔
2700
                cleanup.run()
×
2701
        }
×
2702
        return startErr
3✔
2703
}
2704

2705
// Stop gracefully shutsdown the main daemon server. This function will signal
2706
// any active goroutines, or helper objects to exit, then blocks until they've
2707
// all successfully exited. Additionally, any/all listeners are closed.
2708
// NOTE: This function is safe for concurrent access.
2709
func (s *server) Stop() error {
3✔
2710
        s.stop.Do(func() {
6✔
2711
                atomic.StoreInt32(&s.stopping, 1)
3✔
2712

3✔
2713
                close(s.quit)
3✔
2714

3✔
2715
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2716
                s.connMgr.Stop()
3✔
2717

3✔
2718
                // Stop dispatching blocks to other systems immediately.
3✔
2719
                s.blockbeatDispatcher.Stop()
3✔
2720

3✔
2721
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2722
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2723
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2724
                }
×
2725
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2726
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2727
                }
×
2728
                if err := s.sphinx.Stop(); err != nil {
3✔
2729
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2730
                }
×
2731
                if err := s.invoices.Stop(); err != nil {
3✔
2732
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2733
                }
×
2734
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2735
                        srvrLog.Warnf("failed to stop interceptable "+
×
2736
                                "switch: %v", err)
×
2737
                }
×
2738
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2739
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2740
                                "modifier: %v", err)
×
2741
                }
×
2742
                if err := s.chanRouter.Stop(); err != nil {
3✔
2743
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2744
                }
×
2745
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2746
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2747
                }
×
2748
                if err := s.graphDB.Stop(); err != nil {
3✔
2749
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2750
                }
×
2751
                if err := s.chainArb.Stop(); err != nil {
3✔
2752
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2753
                }
×
2754
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2755
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2756
                }
×
2757
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2758
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2759
                                err)
×
2760
                }
×
2761
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2762
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2763
                }
×
2764
                if err := s.authGossiper.Stop(); err != nil {
3✔
2765
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2766
                }
×
2767
                if err := s.sweeper.Stop(); err != nil {
3✔
2768
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2769
                }
×
2770
                if err := s.txPublisher.Stop(); err != nil {
3✔
2771
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2772
                }
×
2773
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2774
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2775
                }
×
2776
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2777
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2778
                }
×
2779
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2780
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2781
                }
×
2782

2783
                // Update channel.backup file. Make sure to do it before
2784
                // stopping chanSubSwapper.
2785
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2786
                        s.chanStateDB, s.addrSource,
3✔
2787
                )
3✔
2788
                if err != nil {
3✔
2789
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2790
                                err)
×
2791
                } else {
3✔
2792
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2793
                        if err != nil {
6✔
2794
                                srvrLog.Warnf("Manual update of channel "+
3✔
2795
                                        "backup failed: %v", err)
3✔
2796
                        }
3✔
2797
                }
2798

2799
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2800
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2801
                }
×
2802
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2803
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2804
                }
×
2805
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2806
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2807
                                err)
×
2808
                }
×
2809
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2810
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2811
                                err)
×
2812
                }
×
2813
                s.missionController.StopStoreTickers()
3✔
2814

3✔
2815
                // Disconnect from each active peers to ensure that
3✔
2816
                // peerTerminationWatchers signal completion to each peer.
3✔
2817
                for _, peer := range s.Peers() {
6✔
2818
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2819
                        if err != nil {
3✔
2820
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2821
                                        "received error: %v", peer.IdentityKey(),
×
2822
                                        err,
×
2823
                                )
×
2824
                        }
×
2825
                }
2826

2827
                // Now that all connections have been torn down, stop the tower
2828
                // client which will reliably flush all queued states to the
2829
                // tower. If this is halted for any reason, the force quit timer
2830
                // will kick in and abort to allow this method to return.
2831
                if s.towerClientMgr != nil {
6✔
2832
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2833
                                srvrLog.Warnf("Unable to shut down tower "+
×
2834
                                        "client manager: %v", err)
×
2835
                        }
×
2836
                }
2837

2838
                if s.hostAnn != nil {
3✔
2839
                        if err := s.hostAnn.Stop(); err != nil {
×
2840
                                srvrLog.Warnf("unable to shut down host "+
×
2841
                                        "annoucner: %v", err)
×
2842
                        }
×
2843
                }
2844

2845
                if s.livenessMonitor != nil {
6✔
2846
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2847
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2848
                                        "monitor: %v", err)
×
2849
                        }
×
2850
                }
2851

2852
                // Wait for all lingering goroutines to quit.
2853
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2854
                s.wg.Wait()
3✔
2855

3✔
2856
                srvrLog.Debug("Stopping buffer pools...")
3✔
2857
                s.sigPool.Stop()
3✔
2858
                s.writePool.Stop()
3✔
2859
                s.readPool.Stop()
3✔
2860
        })
2861

2862
        return nil
3✔
2863
}
2864

2865
// Stopped returns true if the server has been instructed to shutdown.
2866
// NOTE: This function is safe for concurrent access.
2867
func (s *server) Stopped() bool {
3✔
2868
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2869
}
3✔
2870

2871
// configurePortForwarding attempts to set up port forwarding for the different
2872
// ports that the server will be listening on.
2873
//
2874
// NOTE: This should only be used when using some kind of NAT traversal to
2875
// automatically set up forwarding rules.
2876
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2877
        ip, err := s.natTraversal.ExternalIP()
×
2878
        if err != nil {
×
2879
                return nil, err
×
2880
        }
×
2881
        s.lastDetectedIP = ip
×
2882

×
2883
        externalIPs := make([]string, 0, len(ports))
×
2884
        for _, port := range ports {
×
2885
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2886
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2887
                        continue
×
2888
                }
2889

2890
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2891
                externalIPs = append(externalIPs, hostIP)
×
2892
        }
2893

2894
        return externalIPs, nil
×
2895
}
2896

2897
// removePortForwarding attempts to clear the forwarding rules for the different
2898
// ports the server is currently listening on.
2899
//
2900
// NOTE: This should only be used when using some kind of NAT traversal to
2901
// automatically set up forwarding rules.
2902
func (s *server) removePortForwarding() {
×
2903
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2904
        for _, port := range forwardedPorts {
×
2905
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2906
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2907
                                "port %d: %v", port, err)
×
2908
                }
×
2909
        }
2910
}
2911

2912
// watchExternalIP continuously checks for an updated external IP address every
2913
// 15 minutes. Once a new IP address has been detected, it will automatically
2914
// handle port forwarding rules and send updated node announcements to the
2915
// currently connected peers.
2916
//
2917
// NOTE: This MUST be run as a goroutine.
2918
func (s *server) watchExternalIP() {
×
2919
        defer s.wg.Done()
×
2920

×
2921
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2922
        // up by the server.
×
2923
        defer s.removePortForwarding()
×
2924

×
2925
        // Keep track of the external IPs set by the user to avoid replacing
×
2926
        // them when detecting a new IP.
×
2927
        ipsSetByUser := make(map[string]struct{})
×
2928
        for _, ip := range s.cfg.ExternalIPs {
×
2929
                ipsSetByUser[ip.String()] = struct{}{}
×
2930
        }
×
2931

2932
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2933

×
2934
        ticker := time.NewTicker(15 * time.Minute)
×
2935
        defer ticker.Stop()
×
2936
out:
×
2937
        for {
×
2938
                select {
×
2939
                case <-ticker.C:
×
2940
                        // We'll start off by making sure a new IP address has
×
2941
                        // been detected.
×
2942
                        ip, err := s.natTraversal.ExternalIP()
×
2943
                        if err != nil {
×
2944
                                srvrLog.Debugf("Unable to retrieve the "+
×
2945
                                        "external IP address: %v", err)
×
2946
                                continue
×
2947
                        }
2948

2949
                        // Periodically renew the NAT port forwarding.
2950
                        for _, port := range forwardedPorts {
×
2951
                                err := s.natTraversal.AddPortMapping(port)
×
2952
                                if err != nil {
×
2953
                                        srvrLog.Warnf("Unable to automatically "+
×
2954
                                                "re-create port forwarding using %s: %v",
×
2955
                                                s.natTraversal.Name(), err)
×
2956
                                } else {
×
2957
                                        srvrLog.Debugf("Automatically re-created "+
×
2958
                                                "forwarding for port %d using %s to "+
×
2959
                                                "advertise external IP",
×
2960
                                                port, s.natTraversal.Name())
×
2961
                                }
×
2962
                        }
2963

2964
                        if ip.Equal(s.lastDetectedIP) {
×
2965
                                continue
×
2966
                        }
2967

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

×
2970
                        // Next, we'll craft the new addresses that will be
×
2971
                        // included in the new node announcement and advertised
×
2972
                        // to the network. Each address will consist of the new
×
2973
                        // IP detected and one of the currently advertised
×
2974
                        // ports.
×
2975
                        var newAddrs []net.Addr
×
2976
                        for _, port := range forwardedPorts {
×
2977
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2978
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2979
                                if err != nil {
×
2980
                                        srvrLog.Debugf("Unable to resolve "+
×
2981
                                                "host %v: %v", addr, err)
×
2982
                                        continue
×
2983
                                }
2984

2985
                                newAddrs = append(newAddrs, addr)
×
2986
                        }
2987

2988
                        // Skip the update if we weren't able to resolve any of
2989
                        // the new addresses.
2990
                        if len(newAddrs) == 0 {
×
2991
                                srvrLog.Debug("Skipping node announcement " +
×
2992
                                        "update due to not being able to " +
×
2993
                                        "resolve any new addresses")
×
2994
                                continue
×
2995
                        }
2996

2997
                        // Now, we'll need to update the addresses in our node's
2998
                        // announcement in order to propagate the update
2999
                        // throughout the network. We'll only include addresses
3000
                        // that have a different IP from the previous one, as
3001
                        // the previous IP is no longer valid.
3002
                        currentNodeAnn := s.getNodeAnnouncement()
×
3003

×
3004
                        for _, addr := range currentNodeAnn.Addresses {
×
3005
                                host, _, err := net.SplitHostPort(addr.String())
×
3006
                                if err != nil {
×
3007
                                        srvrLog.Debugf("Unable to determine "+
×
3008
                                                "host from address %v: %v",
×
3009
                                                addr, err)
×
3010
                                        continue
×
3011
                                }
3012

3013
                                // We'll also make sure to include external IPs
3014
                                // set manually by the user.
3015
                                _, setByUser := ipsSetByUser[addr.String()]
×
3016
                                if setByUser || host != s.lastDetectedIP.String() {
×
3017
                                        newAddrs = append(newAddrs, addr)
×
3018
                                }
×
3019
                        }
3020

3021
                        // Then, we'll generate a new timestamped node
3022
                        // announcement with the updated addresses and broadcast
3023
                        // it to our peers.
3024
                        newNodeAnn, err := s.genNodeAnnouncement(
×
3025
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
3026
                        )
×
3027
                        if err != nil {
×
3028
                                srvrLog.Debugf("Unable to generate new node "+
×
3029
                                        "announcement: %v", err)
×
3030
                                continue
×
3031
                        }
3032

3033
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3034
                        if err != nil {
×
3035
                                srvrLog.Debugf("Unable to broadcast new node "+
×
3036
                                        "announcement to peers: %v", err)
×
3037
                                continue
×
3038
                        }
3039

3040
                        // Finally, update the last IP seen to the current one.
3041
                        s.lastDetectedIP = ip
×
3042
                case <-s.quit:
×
3043
                        break out
×
3044
                }
3045
        }
3046
}
3047

3048
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3049
// based on the server, and currently active bootstrap mechanisms as defined
3050
// within the current configuration.
3051
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
3052
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
3053

×
3054
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
3055

×
3056
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
3057
        // this can be used by default if we've already partially seeded the
×
3058
        // network.
×
3059
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
3060
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
3061
        if err != nil {
×
3062
                return nil, err
×
3063
        }
×
3064
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
3065

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

×
3071
                // If we have a set of DNS seeds for this chain, then we'll add
×
3072
                // it as an additional bootstrapping source.
×
3073
                if ok {
×
3074
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3075
                                "seeds: %v", dnsSeeds)
×
3076

×
3077
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3078
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3079
                        )
×
3080
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3081
                }
×
3082
        }
3083

3084
        return bootStrappers, nil
×
3085
}
3086

3087
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3088
// needs to ignore, which is made of three parts,
3089
//   - the node itself needs to be skipped as it doesn't make sense to connect
3090
//     to itself.
3091
//   - the peers that already have connections with, as in s.peersByPub.
3092
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3093
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
3094
        s.mu.RLock()
×
3095
        defer s.mu.RUnlock()
×
3096

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

×
3099
        // We should ignore ourselves from bootstrapping.
×
3100
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
3101
        ignore[selfKey] = struct{}{}
×
3102

×
3103
        // Ignore all connected peers.
×
3104
        for _, peer := range s.peersByPub {
×
3105
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3106
                ignore[nID] = struct{}{}
×
3107
        }
×
3108

3109
        // Ignore all persistent peers as they have a dedicated reconnecting
3110
        // process.
3111
        for pubKeyStr := range s.persistentPeers {
×
3112
                var nID autopilot.NodeID
×
3113
                copy(nID[:], []byte(pubKeyStr))
×
3114
                ignore[nID] = struct{}{}
×
3115
        }
×
3116

3117
        return ignore
×
3118
}
3119

3120
// peerBootstrapper is a goroutine which is tasked with attempting to establish
3121
// and maintain a target minimum number of outbound connections. With this
3122
// invariant, we ensure that our node is connected to a diverse set of peers
3123
// and that nodes newly joining the network receive an up to date network view
3124
// as soon as possible.
3125
func (s *server) peerBootstrapper(ctx context.Context, numTargetPeers uint32,
3126
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3127

×
3128
        defer s.wg.Done()
×
3129

×
3130
        // Before we continue, init the ignore peers map.
×
3131
        ignoreList := s.createBootstrapIgnorePeers()
×
3132

×
3133
        // We'll start off by aggressively attempting connections to peers in
×
3134
        // order to be a part of the network as soon as possible.
×
3135
        s.initialPeerBootstrap(ctx, ignoreList, numTargetPeers, bootstrappers)
×
3136

×
3137
        // Once done, we'll attempt to maintain our target minimum number of
×
3138
        // peers.
×
3139
        //
×
3140
        // We'll use a 15 second backoff, and double the time every time an
×
3141
        // epoch fails up to a ceiling.
×
3142
        backOff := time.Second * 15
×
3143

×
3144
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
3145
        // see if we've reached our minimum number of peers.
×
3146
        sampleTicker := time.NewTicker(backOff)
×
3147
        defer sampleTicker.Stop()
×
3148

×
3149
        // We'll use the number of attempts and errors to determine if we need
×
3150
        // to increase the time between discovery epochs.
×
3151
        var epochErrors uint32 // To be used atomically.
×
3152
        var epochAttempts uint32
×
3153

×
3154
        for {
×
3155
                select {
×
3156
                // The ticker has just woken us up, so we'll need to check if
3157
                // we need to attempt to connect our to any more peers.
3158
                case <-sampleTicker.C:
×
3159
                        // Obtain the current number of peers, so we can gauge
×
3160
                        // if we need to sample more peers or not.
×
3161
                        s.mu.RLock()
×
3162
                        numActivePeers := uint32(len(s.peersByPub))
×
3163
                        s.mu.RUnlock()
×
3164

×
3165
                        // If we have enough peers, then we can loop back
×
3166
                        // around to the next round as we're done here.
×
3167
                        if numActivePeers >= numTargetPeers {
×
3168
                                continue
×
3169
                        }
3170

3171
                        // If all of our attempts failed during this last back
3172
                        // off period, then will increase our backoff to 5
3173
                        // minute ceiling to avoid an excessive number of
3174
                        // queries
3175
                        //
3176
                        // TODO(roasbeef): add reverse policy too?
3177

3178
                        if epochAttempts > 0 &&
×
3179
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3180

×
3181
                                sampleTicker.Stop()
×
3182

×
3183
                                backOff *= 2
×
3184
                                if backOff > bootstrapBackOffCeiling {
×
3185
                                        backOff = bootstrapBackOffCeiling
×
3186
                                }
×
3187

3188
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3189
                                        "%v", backOff)
×
3190
                                sampleTicker = time.NewTicker(backOff)
×
3191
                                continue
×
3192
                        }
3193

3194
                        atomic.StoreUint32(&epochErrors, 0)
×
3195
                        epochAttempts = 0
×
3196

×
3197
                        // Since we know need more peers, we'll compute the
×
3198
                        // exact number we need to reach our threshold.
×
3199
                        numNeeded := numTargetPeers - numActivePeers
×
3200

×
3201
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3202
                                "peers", numNeeded)
×
3203

×
3204
                        // With the number of peers we need calculated, we'll
×
3205
                        // query the network bootstrappers to sample a set of
×
3206
                        // random addrs for us.
×
3207
                        //
×
3208
                        // Before we continue, get a copy of the ignore peers
×
3209
                        // map.
×
3210
                        ignoreList = s.createBootstrapIgnorePeers()
×
3211

×
3212
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3213
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3214
                        )
×
3215
                        if err != nil {
×
3216
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3217
                                        "peers: %v", err)
×
3218
                                continue
×
3219
                        }
3220

3221
                        // Finally, we'll launch a new goroutine for each
3222
                        // prospective peer candidates.
3223
                        for _, addr := range peerAddrs {
×
3224
                                epochAttempts++
×
3225

×
3226
                                go func(a *lnwire.NetAddress) {
×
3227
                                        // TODO(roasbeef): can do AS, subnet,
×
3228
                                        // country diversity, etc
×
3229
                                        errChan := make(chan error, 1)
×
3230
                                        s.connectToPeer(
×
3231
                                                a, errChan,
×
3232
                                                s.cfg.ConnectionTimeout,
×
3233
                                        )
×
3234
                                        select {
×
3235
                                        case err := <-errChan:
×
3236
                                                if err == nil {
×
3237
                                                        return
×
3238
                                                }
×
3239

3240
                                                srvrLog.Errorf("Unable to "+
×
3241
                                                        "connect to %v: %v",
×
3242
                                                        a, err)
×
3243
                                                atomic.AddUint32(&epochErrors, 1)
×
3244
                                        case <-s.quit:
×
3245
                                        }
3246
                                }(addr)
3247
                        }
3248
                case <-s.quit:
×
3249
                        return
×
3250
                }
3251
        }
3252
}
3253

3254
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3255
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3256
// query back off each time we encounter a failure.
3257
const bootstrapBackOffCeiling = time.Minute * 5
3258

3259
// initialPeerBootstrap attempts to continuously connect to peers on startup
3260
// until the target number of peers has been reached. This ensures that nodes
3261
// receive an up to date network view as soon as possible.
3262
func (s *server) initialPeerBootstrap(ctx context.Context,
3263
        ignore map[autopilot.NodeID]struct{}, numTargetPeers uint32,
3264
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3265

×
3266
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3267
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3268

×
3269
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3270
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3271
        var delaySignal <-chan time.Time
×
3272
        delayTime := time.Second * 2
×
3273

×
3274
        // As want to be more aggressive, we'll use a lower back off celling
×
3275
        // then the main peer bootstrap logic.
×
3276
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3277

×
3278
        for attempts := 0; ; attempts++ {
×
3279
                // Check if the server has been requested to shut down in order
×
3280
                // to prevent blocking.
×
3281
                if s.Stopped() {
×
3282
                        return
×
3283
                }
×
3284

3285
                // We can exit our aggressive initial peer bootstrapping stage
3286
                // if we've reached out target number of peers.
3287
                s.mu.RLock()
×
3288
                numActivePeers := uint32(len(s.peersByPub))
×
3289
                s.mu.RUnlock()
×
3290

×
3291
                if numActivePeers >= numTargetPeers {
×
3292
                        return
×
3293
                }
×
3294

3295
                if attempts > 0 {
×
3296
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3297
                                "bootstrap peers (attempt #%v)", delayTime,
×
3298
                                attempts)
×
3299

×
3300
                        // We've completed at least one iterating and haven't
×
3301
                        // finished, so we'll start to insert a delay period
×
3302
                        // between each attempt.
×
3303
                        delaySignal = time.After(delayTime)
×
3304
                        select {
×
3305
                        case <-delaySignal:
×
3306
                        case <-s.quit:
×
3307
                                return
×
3308
                        }
3309

3310
                        // After our delay, we'll double the time we wait up to
3311
                        // the max back off period.
3312
                        delayTime *= 2
×
3313
                        if delayTime > backOffCeiling {
×
3314
                                delayTime = backOffCeiling
×
3315
                        }
×
3316
                }
3317

3318
                // Otherwise, we'll request for the remaining number of peers
3319
                // in order to reach our target.
3320
                peersNeeded := numTargetPeers - numActivePeers
×
3321
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3322
                        ctx, ignore, peersNeeded, bootstrappers...,
×
3323
                )
×
3324
                if err != nil {
×
3325
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3326
                                "peers: %v", err)
×
3327
                        continue
×
3328
                }
3329

3330
                // Then, we'll attempt to establish a connection to the
3331
                // different peer addresses retrieved by our bootstrappers.
3332
                var wg sync.WaitGroup
×
3333
                for _, bootstrapAddr := range bootstrapAddrs {
×
3334
                        wg.Add(1)
×
3335
                        go func(addr *lnwire.NetAddress) {
×
3336
                                defer wg.Done()
×
3337

×
3338
                                errChan := make(chan error, 1)
×
3339
                                go s.connectToPeer(
×
3340
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3341
                                )
×
3342

×
3343
                                // We'll only allow this connection attempt to
×
3344
                                // take up to 3 seconds. This allows us to move
×
3345
                                // quickly by discarding peers that are slowing
×
3346
                                // us down.
×
3347
                                select {
×
3348
                                case err := <-errChan:
×
3349
                                        if err == nil {
×
3350
                                                return
×
3351
                                        }
×
3352
                                        srvrLog.Errorf("Unable to connect to "+
×
3353
                                                "%v: %v", addr, err)
×
3354
                                // TODO: tune timeout? 3 seconds might be *too*
3355
                                // aggressive but works well.
3356
                                case <-time.After(3 * time.Second):
×
3357
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3358
                                                "to not establishing a "+
×
3359
                                                "connection within 3 seconds",
×
3360
                                                addr)
×
3361
                                case <-s.quit:
×
3362
                                }
3363
                        }(bootstrapAddr)
3364
                }
3365

3366
                wg.Wait()
×
3367
        }
3368
}
3369

3370
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3371
// order to listen for inbound connections over Tor.
3372
func (s *server) createNewHiddenService() error {
×
3373
        // Determine the different ports the server is listening on. The onion
×
3374
        // service's virtual port will map to these ports and one will be picked
×
3375
        // at random when the onion service is being accessed.
×
3376
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3377
        for _, listenAddr := range s.listenAddrs {
×
3378
                port := listenAddr.(*net.TCPAddr).Port
×
3379
                listenPorts = append(listenPorts, port)
×
3380
        }
×
3381

3382
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3383
        if err != nil {
×
3384
                return err
×
3385
        }
×
3386

3387
        // Once the port mapping has been set, we can go ahead and automatically
3388
        // create our onion service. The service's private key will be saved to
3389
        // disk in order to regain access to this service when restarting `lnd`.
3390
        onionCfg := tor.AddOnionConfig{
×
3391
                VirtualPort: defaultPeerPort,
×
3392
                TargetPorts: listenPorts,
×
3393
                Store: tor.NewOnionFile(
×
3394
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3395
                        encrypter,
×
3396
                ),
×
3397
        }
×
3398

×
3399
        switch {
×
3400
        case s.cfg.Tor.V2:
×
3401
                onionCfg.Type = tor.V2
×
3402
        case s.cfg.Tor.V3:
×
3403
                onionCfg.Type = tor.V3
×
3404
        }
3405

3406
        addr, err := s.torController.AddOnion(onionCfg)
×
3407
        if err != nil {
×
3408
                return err
×
3409
        }
×
3410

3411
        // Now that the onion service has been created, we'll add the onion
3412
        // address it can be reached at to our list of advertised addresses.
3413
        newNodeAnn, err := s.genNodeAnnouncement(
×
3414
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3415
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3416
                },
×
3417
        )
3418
        if err != nil {
×
3419
                return fmt.Errorf("unable to generate new node "+
×
3420
                        "announcement: %v", err)
×
3421
        }
×
3422

3423
        // Finally, we'll update the on-disk version of our announcement so it
3424
        // will eventually propagate to nodes in the network.
3425
        selfNode := &models.LightningNode{
×
3426
                HaveNodeAnnouncement: true,
×
3427
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3428
                Addresses:            newNodeAnn.Addresses,
×
3429
                Alias:                newNodeAnn.Alias.String(),
×
3430
                Features: lnwire.NewFeatureVector(
×
3431
                        newNodeAnn.Features, lnwire.Features,
×
3432
                ),
×
3433
                Color:        newNodeAnn.RGBColor,
×
3434
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3435
        }
×
3436
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3437
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3438
                return fmt.Errorf("can't set self node: %w", err)
×
3439
        }
×
3440

3441
        return nil
×
3442
}
3443

3444
// findChannel finds a channel given a public key and ChannelID. It is an
3445
// optimization that is quicker than seeking for a channel given only the
3446
// ChannelID.
3447
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3448
        *channeldb.OpenChannel, error) {
3✔
3449

3✔
3450
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3451
        if err != nil {
3✔
3452
                return nil, err
×
3453
        }
×
3454

3455
        for _, channel := range nodeChans {
6✔
3456
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3457
                        return channel, nil
3✔
3458
                }
3✔
3459
        }
3460

3461
        return nil, fmt.Errorf("unable to find channel")
3✔
3462
}
3463

3464
// getNodeAnnouncement fetches the current, fully signed node announcement.
3465
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3466
        s.mu.Lock()
3✔
3467
        defer s.mu.Unlock()
3✔
3468

3✔
3469
        return *s.currentNodeAnn
3✔
3470
}
3✔
3471

3472
// genNodeAnnouncement generates and returns the current fully signed node
3473
// announcement. The time stamp of the announcement will be updated in order
3474
// to ensure it propagates through the network.
3475
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3476
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3477

3✔
3478
        s.mu.Lock()
3✔
3479
        defer s.mu.Unlock()
3✔
3480

3✔
3481
        // First, try to update our feature manager with the updated set of
3✔
3482
        // features.
3✔
3483
        if features != nil {
6✔
3484
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3485
                        feature.SetNodeAnn: features,
3✔
3486
                }
3✔
3487
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3488
                if err != nil {
6✔
3489
                        return lnwire.NodeAnnouncement{}, err
3✔
3490
                }
3✔
3491

3492
                // If we could successfully update our feature manager, add
3493
                // an update modifier to include these new features to our
3494
                // set.
3495
                modifiers = append(
3✔
3496
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3497
                )
3✔
3498
        }
3499

3500
        // Always update the timestamp when refreshing to ensure the update
3501
        // propagates.
3502
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3503

3✔
3504
        // Apply the requested changes to the node announcement.
3✔
3505
        for _, modifier := range modifiers {
6✔
3506
                modifier(s.currentNodeAnn)
3✔
3507
        }
3✔
3508

3509
        // Sign a new update after applying all of the passed modifiers.
3510
        err := netann.SignNodeAnnouncement(
3✔
3511
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
3✔
3512
        )
3✔
3513
        if err != nil {
6✔
3514
                return lnwire.NodeAnnouncement{}, err
3✔
3515
        }
3✔
3516

3517
        return *s.currentNodeAnn, nil
3✔
3518
}
3519

3520
// updateAndBroadcastSelfNode generates a new node announcement
3521
// applying the giving modifiers and updating the time stamp
3522
// to ensure it propagates through the network. Then it broadcasts
3523
// it to the network.
3524
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
3525
        modifiers ...netann.NodeAnnModifier) error {
3✔
3526

3✔
3527
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3528
        if err != nil {
6✔
3529
                return fmt.Errorf("unable to generate new node "+
3✔
3530
                        "announcement: %v", err)
3✔
3531
        }
3✔
3532

3533
        // Update the on-disk version of our announcement.
3534
        // Load and modify self node istead of creating anew instance so we
3535
        // don't risk overwriting any existing values.
3536
        selfNode, err := s.graphDB.SourceNode()
3✔
3537
        if err != nil {
3✔
3538
                return fmt.Errorf("unable to get current source node: %w", err)
×
3539
        }
×
3540

3541
        selfNode.HaveNodeAnnouncement = true
3✔
3542
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3543
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3544
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3545
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3546
        selfNode.Color = newNodeAnn.RGBColor
3✔
3547
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3548

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

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

3555
        // Finally, propagate it to the nodes in the network.
3556
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3557
        if err != nil {
3✔
3558
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3559
                        "announcement to peers: %v", err)
×
3560
                return err
×
3561
        }
×
3562

3563
        return nil
3✔
3564
}
3565

3566
type nodeAddresses struct {
3567
        pubKey    *btcec.PublicKey
3568
        addresses []net.Addr
3569
}
3570

3571
// establishPersistentConnections attempts to establish persistent connections
3572
// to all our direct channel collaborators. In order to promote liveness of our
3573
// active channels, we instruct the connection manager to attempt to establish
3574
// and maintain persistent connections to all our direct channel counterparties.
3575
func (s *server) establishPersistentConnections() error {
3✔
3576
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3577
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3578
        // since other PubKey forms can't be compared.
3✔
3579
        nodeAddrsMap := map[string]*nodeAddresses{}
3✔
3580

3✔
3581
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3582
        // attempt to connect to based on our set of previous connections. Set
3✔
3583
        // the reconnection port to the default peer port.
3✔
3584
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3585
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3586
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3587
        }
×
3588

3589
        for _, node := range linkNodes {
6✔
3590
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3591
                nodeAddrs := &nodeAddresses{
3✔
3592
                        pubKey:    node.IdentityPub,
3✔
3593
                        addresses: node.Addresses,
3✔
3594
                }
3✔
3595
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3596
        }
3✔
3597

3598
        // After checking our previous connections for addresses to connect to,
3599
        // iterate through the nodes in our channel graph to find addresses
3600
        // that have been added via NodeAnnouncement messages.
3601
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3602
        // each of the nodes.
3603
        err = s.graphDB.ForEachSourceNodeChannel(func(chanPoint wire.OutPoint,
3✔
3604
                havePolicy bool, channelPeer *models.LightningNode) error {
6✔
3605

3✔
3606
                // If the remote party has announced the channel to us, but we
3✔
3607
                // haven't yet, then we won't have a policy. However, we don't
3✔
3608
                // need this to connect to the peer, so we'll log it and move on.
3✔
3609
                if !havePolicy {
3✔
3610
                        srvrLog.Warnf("No channel policy found for "+
×
3611
                                "ChannelPoint(%v): ", chanPoint)
×
3612
                }
×
3613

3614
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3615

3✔
3616
                // Add all unique addresses from channel
3✔
3617
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3618
                // connect to for this peer.
3✔
3619
                addrSet := make(map[string]net.Addr)
3✔
3620
                for _, addr := range channelPeer.Addresses {
6✔
3621
                        switch addr.(type) {
3✔
3622
                        case *net.TCPAddr:
3✔
3623
                                addrSet[addr.String()] = addr
3✔
3624

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

3634
                // If this peer is also recorded as a link node, we'll add any
3635
                // additional addresses that have not already been selected.
3636
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3637
                if ok {
6✔
3638
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3639
                                switch lnAddress.(type) {
3✔
3640
                                case *net.TCPAddr:
3✔
3641
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3642

3643
                                // We'll only attempt to connect to Tor
3644
                                // addresses if Tor outbound support is enabled.
3645
                                case *tor.OnionAddr:
×
3646
                                        if s.cfg.Tor.Active {
×
3647
                                                addrSet[lnAddress.String()] = lnAddress
×
3648
                                        }
×
3649
                                }
3650
                        }
3651
                }
3652

3653
                // Construct a slice of the deduped addresses.
3654
                var addrs []net.Addr
3✔
3655
                for _, addr := range addrSet {
6✔
3656
                        addrs = append(addrs, addr)
3✔
3657
                }
3✔
3658

3659
                n := &nodeAddresses{
3✔
3660
                        addresses: addrs,
3✔
3661
                }
3✔
3662
                n.pubKey, err = channelPeer.PubKey()
3✔
3663
                if err != nil {
3✔
3664
                        return err
×
3665
                }
×
3666

3667
                nodeAddrsMap[pubStr] = n
3✔
3668
                return nil
3✔
3669
        })
3670
        if err != nil {
3✔
3671
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3672
                        "%v", err)
×
3673

×
3674
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3675
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3676

×
3677
                        return err
×
3678
                }
×
3679
        }
3680

3681
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3682
                len(nodeAddrsMap))
3✔
3683

3✔
3684
        // Acquire and hold server lock until all persistent connection requests
3✔
3685
        // have been recorded and sent to the connection manager.
3✔
3686
        s.mu.Lock()
3✔
3687
        defer s.mu.Unlock()
3✔
3688

3✔
3689
        // Iterate through the combined list of addresses from prior links and
3✔
3690
        // node announcements and attempt to reconnect to each node.
3✔
3691
        var numOutboundConns int
3✔
3692
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3693
                // Add this peer to the set of peers we should maintain a
3✔
3694
                // persistent connection with. We set the value to false to
3✔
3695
                // indicate that we should not continue to reconnect if the
3✔
3696
                // number of channels returns to zero, since this peer has not
3✔
3697
                // been requested as perm by the user.
3✔
3698
                s.persistentPeers[pubStr] = false
3✔
3699
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3700
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3701
                }
3✔
3702

3703
                for _, address := range nodeAddr.addresses {
6✔
3704
                        // Create a wrapper address which couples the IP and
3✔
3705
                        // the pubkey so the brontide authenticated connection
3✔
3706
                        // can be established.
3✔
3707
                        lnAddr := &lnwire.NetAddress{
3✔
3708
                                IdentityKey: nodeAddr.pubKey,
3✔
3709
                                Address:     address,
3✔
3710
                        }
3✔
3711

3✔
3712
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3713
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3714
                }
3✔
3715

3716
                // We'll connect to the first 10 peers immediately, then
3717
                // randomly stagger any remaining connections if the
3718
                // stagger initial reconnect flag is set. This ensures
3719
                // that mobile nodes or nodes with a small number of
3720
                // channels obtain connectivity quickly, but larger
3721
                // nodes are able to disperse the costs of connecting to
3722
                // all peers at once.
3723
                if numOutboundConns < numInstantInitReconnect ||
3✔
3724
                        !s.cfg.StaggerInitialReconnect {
6✔
3725

3✔
3726
                        go s.connectToPersistentPeer(pubStr)
3✔
3727
                } else {
3✔
3728
                        go s.delayInitialReconnect(pubStr)
×
3729
                }
×
3730

3731
                numOutboundConns++
3✔
3732
        }
3733

3734
        return nil
3✔
3735
}
3736

3737
// delayInitialReconnect will attempt a reconnection to the given peer after
3738
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3739
//
3740
// NOTE: This method MUST be run as a goroutine.
3741
func (s *server) delayInitialReconnect(pubStr string) {
×
3742
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3743
        select {
×
3744
        case <-time.After(delay):
×
3745
                s.connectToPersistentPeer(pubStr)
×
3746
        case <-s.quit:
×
3747
        }
3748
}
3749

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

3✔
3756
        s.mu.Lock()
3✔
3757
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3758
                delete(s.persistentPeers, pubKeyStr)
3✔
3759
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3760
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3761
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3762
                s.mu.Unlock()
3✔
3763

3✔
3764
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3765
                        "peer has no open channels", compressedPubKey)
3✔
3766

3✔
3767
                return
3✔
3768
        }
3✔
3769
        s.mu.Unlock()
3✔
3770
}
3771

3772
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3773
// is instead used to remove persistent peer state for a peer that has been
3774
// disconnected for good cause by the server. Currently, a gossip ban from
3775
// sending garbage and the server running out of restricted-access
3776
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3777
// future, this function may expand when more ban criteria is added.
3778
//
3779
// NOTE: The server's write lock MUST be held when this is called.
3780
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3781
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3782
                delete(s.persistentPeers, remotePub)
×
3783
                delete(s.persistentPeersBackoff, remotePub)
×
3784
                delete(s.persistentPeerAddrs, remotePub)
×
3785
                s.cancelConnReqs(remotePub, nil)
×
3786
        }
×
3787
}
3788

3789
// BroadcastMessage sends a request to the server to broadcast a set of
3790
// messages to all peers other than the one specified by the `skips` parameter.
3791
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3792
// the target peers.
3793
//
3794
// NOTE: This function is safe for concurrent access.
3795
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3796
        msgs ...lnwire.Message) error {
3✔
3797

3✔
3798
        // Filter out peers found in the skips map. We synchronize access to
3✔
3799
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3800
        // exact set of peers present at the time of invocation.
3✔
3801
        s.mu.RLock()
3✔
3802
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3803
        for pubStr, sPeer := range s.peersByPub {
6✔
3804
                if skips != nil {
6✔
3805
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3806
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3807
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3808
                                continue
3✔
3809
                        }
3810
                }
3811

3812
                peers = append(peers, sPeer)
3✔
3813
        }
3814
        s.mu.RUnlock()
3✔
3815

3✔
3816
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3817
        // all messages to each of peers.
3✔
3818
        var wg sync.WaitGroup
3✔
3819
        for _, sPeer := range peers {
6✔
3820
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3821
                        sPeer.PubKey())
3✔
3822

3✔
3823
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3824
                wg.Add(1)
3✔
3825
                s.wg.Add(1)
3✔
3826
                go func(p lnpeer.Peer) {
6✔
3827
                        defer s.wg.Done()
3✔
3828
                        defer wg.Done()
3✔
3829

3✔
3830
                        p.SendMessageLazy(false, msgs...)
3✔
3831
                }(sPeer)
3✔
3832
        }
3833

3834
        // Wait for all messages to have been dispatched before returning to
3835
        // caller.
3836
        wg.Wait()
3✔
3837

3✔
3838
        return nil
3✔
3839
}
3840

3841
// NotifyWhenOnline can be called by other subsystems to get notified when a
3842
// particular peer comes online. The peer itself is sent across the peerChan.
3843
//
3844
// NOTE: This function is safe for concurrent access.
3845
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3846
        peerChan chan<- lnpeer.Peer) {
3✔
3847

3✔
3848
        s.mu.Lock()
3✔
3849

3✔
3850
        // Compute the target peer's identifier.
3✔
3851
        pubStr := string(peerKey[:])
3✔
3852

3✔
3853
        // Check if peer is connected.
3✔
3854
        peer, ok := s.peersByPub[pubStr]
3✔
3855
        if ok {
6✔
3856
                // Unlock here so that the mutex isn't held while we are
3✔
3857
                // waiting for the peer to become active.
3✔
3858
                s.mu.Unlock()
3✔
3859

3✔
3860
                // Wait until the peer signals that it is actually active
3✔
3861
                // rather than only in the server's maps.
3✔
3862
                select {
3✔
3863
                case <-peer.ActiveSignal():
3✔
3864
                case <-peer.QuitSignal():
1✔
3865
                        // The peer quit, so we'll add the channel to the slice
1✔
3866
                        // and return.
1✔
3867
                        s.mu.Lock()
1✔
3868
                        s.peerConnectedListeners[pubStr] = append(
1✔
3869
                                s.peerConnectedListeners[pubStr], peerChan,
1✔
3870
                        )
1✔
3871
                        s.mu.Unlock()
1✔
3872
                        return
1✔
3873
                }
3874

3875
                // Connected, can return early.
3876
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3877

3✔
3878
                select {
3✔
3879
                case peerChan <- peer:
3✔
3880
                case <-s.quit:
×
3881
                }
3882

3883
                return
3✔
3884
        }
3885

3886
        // Not connected, store this listener such that it can be notified when
3887
        // the peer comes online.
3888
        s.peerConnectedListeners[pubStr] = append(
3✔
3889
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3890
        )
3✔
3891
        s.mu.Unlock()
3✔
3892
}
3893

3894
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3895
// the given public key has been disconnected. The notification is signaled by
3896
// closing the channel returned.
3897
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3898
        s.mu.Lock()
3✔
3899
        defer s.mu.Unlock()
3✔
3900

3✔
3901
        c := make(chan struct{})
3✔
3902

3✔
3903
        // If the peer is already offline, we can immediately trigger the
3✔
3904
        // notification.
3✔
3905
        peerPubKeyStr := string(peerPubKey[:])
3✔
3906
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3907
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3908
                close(c)
×
3909
                return c
×
3910
        }
×
3911

3912
        // Otherwise, the peer is online, so we'll keep track of the channel to
3913
        // trigger the notification once the server detects the peer
3914
        // disconnects.
3915
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3916
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3917
        )
3✔
3918

3✔
3919
        return c
3✔
3920
}
3921

3922
// FindPeer will return the peer that corresponds to the passed in public key.
3923
// This function is used by the funding manager, allowing it to update the
3924
// daemon's local representation of the remote peer.
3925
//
3926
// NOTE: This function is safe for concurrent access.
3927
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3928
        s.mu.RLock()
3✔
3929
        defer s.mu.RUnlock()
3✔
3930

3✔
3931
        pubStr := string(peerKey.SerializeCompressed())
3✔
3932

3✔
3933
        return s.findPeerByPubStr(pubStr)
3✔
3934
}
3✔
3935

3936
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3937
// which should be a string representation of the peer's serialized, compressed
3938
// public key.
3939
//
3940
// NOTE: This function is safe for concurrent access.
3941
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3942
        s.mu.RLock()
3✔
3943
        defer s.mu.RUnlock()
3✔
3944

3✔
3945
        return s.findPeerByPubStr(pubStr)
3✔
3946
}
3✔
3947

3948
// findPeerByPubStr is an internal method that retrieves the specified peer from
3949
// the server's internal state using.
3950
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3951
        peer, ok := s.peersByPub[pubStr]
3✔
3952
        if !ok {
6✔
3953
                return nil, ErrPeerNotConnected
3✔
3954
        }
3✔
3955

3956
        return peer, nil
3✔
3957
}
3958

3959
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3960
// exponential backoff. If no previous backoff was known, the default is
3961
// returned.
3962
func (s *server) nextPeerBackoff(pubStr string,
3963
        startTime time.Time) time.Duration {
3✔
3964

3✔
3965
        // Now, determine the appropriate backoff to use for the retry.
3✔
3966
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3967
        if !ok {
6✔
3968
                // If an existing backoff was unknown, use the default.
3✔
3969
                return s.cfg.MinBackoff
3✔
3970
        }
3✔
3971

3972
        // If the peer failed to start properly, we'll just use the previous
3973
        // backoff to compute the subsequent randomized exponential backoff
3974
        // duration. This will roughly double on average.
3975
        if startTime.IsZero() {
3✔
3976
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3977
        }
×
3978

3979
        // The peer succeeded in starting. If the connection didn't last long
3980
        // enough to be considered stable, we'll continue to back off retries
3981
        // with this peer.
3982
        connDuration := time.Since(startTime)
3✔
3983
        if connDuration < defaultStableConnDuration {
6✔
3984
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3985
        }
3✔
3986

3987
        // The peer succeed in starting and this was stable peer, so we'll
3988
        // reduce the timeout duration by the length of the connection after
3989
        // applying randomized exponential backoff. We'll only apply this in the
3990
        // case that:
3991
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3992
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3993
        if relaxedBackoff > s.cfg.MinBackoff {
×
3994
                return relaxedBackoff
×
3995
        }
×
3996

3997
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3998
        // the stable connection lasted much longer than our previous backoff.
3999
        // To reward such good behavior, we'll reconnect after the default
4000
        // timeout.
4001
        return s.cfg.MinBackoff
×
4002
}
4003

4004
// shouldDropLocalConnection determines if our local connection to a remote peer
4005
// should be dropped in the case of concurrent connection establishment. In
4006
// order to deterministically decide which connection should be dropped, we'll
4007
// utilize the ordering of the local and remote public key. If we didn't use
4008
// such a tie breaker, then we risk _both_ connections erroneously being
4009
// dropped.
4010
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
4011
        localPubBytes := local.SerializeCompressed()
×
4012
        remotePubPbytes := remote.SerializeCompressed()
×
4013

×
4014
        // The connection that comes from the node with a "smaller" pubkey
×
4015
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
4016
        // should drop our established connection.
×
4017
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
4018
}
×
4019

4020
// InboundPeerConnected initializes a new peer in response to a new inbound
4021
// connection.
4022
//
4023
// NOTE: This function is safe for concurrent access.
4024
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
4025
        // Exit early if we have already been instructed to shutdown, this
3✔
4026
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4027
        if s.Stopped() {
3✔
4028
                return
×
4029
        }
×
4030

4031
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4032
        pubSer := nodePub.SerializeCompressed()
3✔
4033
        pubStr := string(pubSer)
3✔
4034

3✔
4035
        var pubBytes [33]byte
3✔
4036
        copy(pubBytes[:], pubSer)
3✔
4037

3✔
4038
        s.mu.Lock()
3✔
4039
        defer s.mu.Unlock()
3✔
4040

3✔
4041
        // If the remote node's public key is banned, drop the connection.
3✔
4042
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
3✔
4043
        if err != nil {
3✔
4044
                // Clean up the persistent peer maps if we're dropping this
×
4045
                // connection.
×
4046
                s.bannedPersistentPeerConnection(pubStr)
×
4047

×
4048
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4049
                        "of restricted-access connection slots: %v.", pubSer,
×
4050
                        err)
×
4051

×
4052
                conn.Close()
×
4053

×
4054
                return
×
4055
        }
×
4056

4057
        // If we already have an outbound connection to this peer, then ignore
4058
        // this new connection.
4059
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
4060
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
4061
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
4062
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4063

3✔
4064
                conn.Close()
3✔
4065
                return
3✔
4066
        }
3✔
4067

4068
        // If we already have a valid connection that is scheduled to take
4069
        // precedence once the prior peer has finished disconnecting, we'll
4070
        // ignore this connection.
4071
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
4072
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4073
                        "scheduled", conn.RemoteAddr(), p)
×
4074
                conn.Close()
×
4075
                return
×
4076
        }
×
4077

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

3✔
4080
        // Check to see if we already have a connection with this peer. If so,
3✔
4081
        // we may need to drop our existing connection. This prevents us from
3✔
4082
        // having duplicate connections to the same peer. We forgo adding a
3✔
4083
        // default case as we expect these to be the only error values returned
3✔
4084
        // from findPeerByPubStr.
3✔
4085
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4086
        switch err {
3✔
4087
        case ErrPeerNotConnected:
3✔
4088
                // We were unable to locate an existing connection with the
3✔
4089
                // target peer, proceed to connect.
3✔
4090
                s.cancelConnReqs(pubStr, nil)
3✔
4091
                s.peerConnected(conn, nil, true, access)
3✔
4092

4093
        case nil:
×
4094
                // We already have a connection with the incoming peer. If the
×
4095
                // connection we've already established should be kept and is
×
4096
                // not of the same type of the new connection (inbound), then
×
4097
                // we'll close out the new connection s.t there's only a single
×
4098
                // connection between us.
×
4099
                localPub := s.identityECDH.PubKey()
×
4100
                if !connectedPeer.Inbound() &&
×
4101
                        !shouldDropLocalConnection(localPub, nodePub) {
×
4102

×
4103
                        srvrLog.Warnf("Received inbound connection from "+
×
4104
                                "peer %v, but already have outbound "+
×
4105
                                "connection, dropping conn", connectedPeer)
×
4106
                        conn.Close()
×
4107
                        return
×
4108
                }
×
4109

4110
                // Otherwise, if we should drop the connection, then we'll
4111
                // disconnect our already connected peer.
4112
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4113
                        connectedPeer)
×
4114

×
4115
                s.cancelConnReqs(pubStr, nil)
×
4116

×
4117
                // Remove the current peer from the server's internal state and
×
4118
                // signal that the peer termination watcher does not need to
×
4119
                // execute for this peer.
×
4120
                s.removePeer(connectedPeer)
×
4121
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4122
                s.scheduledPeerConnection[pubStr] = func() {
×
4123
                        s.peerConnected(conn, nil, true, access)
×
4124
                }
×
4125
        }
4126
}
4127

4128
// OutboundPeerConnected initializes a new peer in response to a new outbound
4129
// connection.
4130
// NOTE: This function is safe for concurrent access.
4131
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4132
        // Exit early if we have already been instructed to shutdown, this
3✔
4133
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4134
        if s.Stopped() {
3✔
4135
                return
×
4136
        }
×
4137

4138
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4139
        pubSer := nodePub.SerializeCompressed()
3✔
4140
        pubStr := string(pubSer)
3✔
4141

3✔
4142
        var pubBytes [33]byte
3✔
4143
        copy(pubBytes[:], pubSer)
3✔
4144

3✔
4145
        s.mu.Lock()
3✔
4146
        defer s.mu.Unlock()
3✔
4147

3✔
4148
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
3✔
4149
        if err != nil {
3✔
4150
                // Clean up the persistent peer maps if we're dropping this
×
4151
                // connection.
×
4152
                s.bannedPersistentPeerConnection(pubStr)
×
4153

×
4154
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4155
                        "of restricted-access connection slots: %v.", pubSer,
×
4156
                        err)
×
4157

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

4162
                conn.Close()
×
4163

×
4164
                return
×
4165
        }
4166

4167
        // If we already have an inbound connection to this peer, then ignore
4168
        // this new connection.
4169
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4170
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4171
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4172
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4173

3✔
4174
                if connReq != nil {
6✔
4175
                        s.connMgr.Remove(connReq.ID())
3✔
4176
                }
3✔
4177
                conn.Close()
3✔
4178
                return
3✔
4179
        }
4180
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4181
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4182
                s.connMgr.Remove(connReq.ID())
×
4183
                conn.Close()
×
4184
                return
×
4185
        }
×
4186

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

×
4193
                if connReq != nil {
×
4194
                        s.connMgr.Remove(connReq.ID())
×
4195
                }
×
4196

4197
                conn.Close()
×
4198
                return
×
4199
        }
4200

4201
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
3✔
4202
                conn.RemoteAddr())
3✔
4203

3✔
4204
        if connReq != nil {
6✔
4205
                // A successful connection was returned by the connmgr.
3✔
4206
                // Immediately cancel all pending requests, excluding the
3✔
4207
                // outbound connection we just established.
3✔
4208
                ignore := connReq.ID()
3✔
4209
                s.cancelConnReqs(pubStr, &ignore)
3✔
4210
        } else {
6✔
4211
                // This was a successful connection made by some other
3✔
4212
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4213
                s.cancelConnReqs(pubStr, nil)
3✔
4214
        }
3✔
4215

4216
        // If we already have a connection with this peer, decide whether or not
4217
        // we need to drop the stale connection. We forgo adding a default case
4218
        // as we expect these to be the only error values returned from
4219
        // findPeerByPubStr.
4220
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4221
        switch err {
3✔
4222
        case ErrPeerNotConnected:
3✔
4223
                // We were unable to locate an existing connection with the
3✔
4224
                // target peer, proceed to connect.
3✔
4225
                s.peerConnected(conn, connReq, false, access)
3✔
4226

4227
        case nil:
×
4228
                // We already have a connection with the incoming peer. If the
×
4229
                // connection we've already established should be kept and is
×
4230
                // not of the same type of the new connection (outbound), then
×
4231
                // we'll close out the new connection s.t there's only a single
×
4232
                // connection between us.
×
4233
                localPub := s.identityECDH.PubKey()
×
4234
                if connectedPeer.Inbound() &&
×
4235
                        shouldDropLocalConnection(localPub, nodePub) {
×
4236

×
4237
                        srvrLog.Warnf("Established outbound connection to "+
×
4238
                                "peer %v, but already have inbound "+
×
4239
                                "connection, dropping conn", connectedPeer)
×
4240
                        if connReq != nil {
×
4241
                                s.connMgr.Remove(connReq.ID())
×
4242
                        }
×
4243
                        conn.Close()
×
4244
                        return
×
4245
                }
4246

4247
                // Otherwise, _their_ connection should be dropped. So we'll
4248
                // disconnect the peer and send the now obsolete peer to the
4249
                // server for garbage collection.
4250
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4251
                        connectedPeer)
×
4252

×
4253
                // Remove the current peer from the server's internal state and
×
4254
                // signal that the peer termination watcher does not need to
×
4255
                // execute for this peer.
×
4256
                s.removePeer(connectedPeer)
×
4257
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4258
                s.scheduledPeerConnection[pubStr] = func() {
×
4259
                        s.peerConnected(conn, connReq, false, access)
×
4260
                }
×
4261
        }
4262
}
4263

4264
// UnassignedConnID is the default connection ID that a request can have before
4265
// it actually is submitted to the connmgr.
4266
// TODO(conner): move into connmgr package, or better, add connmgr method for
4267
// generating atomic IDs
4268
const UnassignedConnID uint64 = 0
4269

4270
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4271
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4272
// Afterwards, each connection request removed from the connmgr. The caller can
4273
// optionally specify a connection ID to ignore, which prevents us from
4274
// canceling a successful request. All persistent connreqs for the provided
4275
// pubkey are discarded after the operationjw.
4276
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4277
        // First, cancel any lingering persistent retry attempts, which will
3✔
4278
        // prevent retries for any with backoffs that are still maturing.
3✔
4279
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4280
                close(cancelChan)
3✔
4281
                delete(s.persistentRetryCancels, pubStr)
3✔
4282
        }
3✔
4283

4284
        // Next, check to see if we have any outstanding persistent connection
4285
        // requests to this peer. If so, then we'll remove all of these
4286
        // connection requests, and also delete the entry from the map.
4287
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4288
        if !ok {
6✔
4289
                return
3✔
4290
        }
3✔
4291

4292
        for _, connReq := range connReqs {
6✔
4293
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4294

3✔
4295
                // Atomically capture the current request identifier.
3✔
4296
                connID := connReq.ID()
3✔
4297

3✔
4298
                // Skip any zero IDs, this indicates the request has not
3✔
4299
                // yet been schedule.
3✔
4300
                if connID == UnassignedConnID {
3✔
4301
                        continue
×
4302
                }
4303

4304
                // Skip a particular connection ID if instructed.
4305
                if skip != nil && connID == *skip {
6✔
4306
                        continue
3✔
4307
                }
4308

4309
                s.connMgr.Remove(connID)
3✔
4310
        }
4311

4312
        delete(s.persistentConnReqs, pubStr)
3✔
4313
}
4314

4315
// handleCustomMessage dispatches an incoming custom peers message to
4316
// subscribers.
4317
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4318
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4319
                peer, msg.Type)
3✔
4320

3✔
4321
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4322
                Peer: peer,
3✔
4323
                Msg:  msg,
3✔
4324
        })
3✔
4325
}
3✔
4326

4327
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4328
// messages.
4329
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4330
        return s.customMessageServer.Subscribe()
3✔
4331
}
3✔
4332

4333
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4334
// the channelNotifier's NotifyOpenChannelEvent.
4335
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4336
        remotePub *btcec.PublicKey) error {
3✔
4337

3✔
4338
        // Call newOpenChan to update the access manager's maps for this peer.
3✔
4339
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
6✔
4340
                return err
3✔
4341
        }
3✔
4342

4343
        // Notify subscribers about this open channel event.
4344
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4345

3✔
4346
        return nil
3✔
4347
}
4348

4349
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4350
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4351
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4352
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) error {
3✔
4353

3✔
4354
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4355
        // peer.
3✔
4356
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4357
                return err
×
4358
        }
×
4359

4360
        // Notify subscribers about this event.
4361
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4362

3✔
4363
        return nil
3✔
4364
}
4365

4366
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4367
// calls the channelNotifier's NotifyFundingTimeout.
4368
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4369
        remotePub *btcec.PublicKey) error {
3✔
4370

3✔
4371
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4372
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4373
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4374
                // If we encounter an error while attempting to disconnect the
×
4375
                // peer, log the error.
×
4376
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4377
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4378
                }
×
4379
        }
4380

4381
        // Notify subscribers about this event.
4382
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4383

3✔
4384
        return nil
3✔
4385
}
4386

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

3✔
4394
        brontideConn := conn.(*brontide.Conn)
3✔
4395
        addr := conn.RemoteAddr()
3✔
4396
        pubKey := brontideConn.RemotePub()
3✔
4397

3✔
4398
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4399
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4400

3✔
4401
        peerAddr := &lnwire.NetAddress{
3✔
4402
                IdentityKey: pubKey,
3✔
4403
                Address:     addr,
3✔
4404
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4405
        }
3✔
4406

3✔
4407
        // With the brontide connection established, we'll now craft the feature
3✔
4408
        // vectors to advertise to the remote node.
3✔
4409
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4410
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4411

3✔
4412
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4413
        // found, create a fresh buffer.
3✔
4414
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4415
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4416
        if !ok {
6✔
4417
                var err error
3✔
4418
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4419
                if err != nil {
3✔
4420
                        srvrLog.Errorf("unable to create peer %v", err)
×
4421
                        return
×
4422
                }
×
4423
        }
4424

4425
        // If we directly set the peer.Config TowerClient member to the
4426
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4427
        // the peer.Config's TowerClient member will not evaluate to nil even
4428
        // though the underlying value is nil. To avoid this gotcha which can
4429
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4430
        // TowerClient if needed.
4431
        var towerClient wtclient.ClientManager
3✔
4432
        if s.towerClientMgr != nil {
6✔
4433
                towerClient = s.towerClientMgr
3✔
4434
        }
3✔
4435

4436
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4437
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4438

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

3✔
4482
                        return s.genNodeAnnouncement(nil)
3✔
4483
                },
3✔
4484

4485
                PongBuf: s.pongBuf,
4486

4487
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4488

4489
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4490

4491
                FundingManager: s.fundingMgr,
4492

4493
                Hodl:                    s.cfg.Hodl,
4494
                UnsafeReplay:            s.cfg.UnsafeReplay,
4495
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4496
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4497
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4498
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4499
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4500
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4501
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4502
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4503
                HandleCustomMessage:    s.handleCustomMessage,
4504
                GetAliases:             s.aliasMgr.GetAliases,
4505
                RequestAlias:           s.aliasMgr.RequestAlias,
4506
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4507
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4508
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4509
                MaxFeeExposure:         thresholdMSats,
4510
                Quit:                   s.quit,
4511
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4512
                AuxSigner:              s.implCfg.AuxSigner,
4513
                MsgRouter:              s.implCfg.MsgRouter,
4514
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4515
                AuxResolver:            s.implCfg.AuxContractResolver,
4516
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4517
                ShouldFwdExpEndorsement: func() bool {
3✔
4518
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4519
                                return false
3✔
4520
                        }
3✔
4521

4522
                        return clock.NewDefaultClock().Now().Before(
3✔
4523
                                EndorsementExperimentEnd,
3✔
4524
                        )
3✔
4525
                },
4526
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4527
        }
4528

4529
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4530
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4531

3✔
4532
        p := peer.NewBrontide(pCfg)
3✔
4533

3✔
4534
        // Update the access manager with the access permission for this peer.
3✔
4535
        s.peerAccessMan.addPeerAccess(pubKey, access)
3✔
4536

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

3✔
4540
        s.addPeer(p)
3✔
4541

3✔
4542
        // Once we have successfully added the peer to the server, we can
3✔
4543
        // delete the previous error buffer from the server's map of error
3✔
4544
        // buffers.
3✔
4545
        delete(s.peerErrors, pkStr)
3✔
4546

3✔
4547
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4548
        // includes sending and receiving Init messages, which would be a DOS
3✔
4549
        // vector if we held the server's mutex throughout the procedure.
3✔
4550
        s.wg.Add(1)
3✔
4551
        go s.peerInitializer(p)
3✔
4552
}
4553

4554
// addPeer adds the passed peer to the server's global state of all active
4555
// peers.
4556
func (s *server) addPeer(p *peer.Brontide) {
3✔
4557
        if p == nil {
3✔
4558
                return
×
4559
        }
×
4560

4561
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4562

3✔
4563
        // Ignore new peers if we're shutting down.
3✔
4564
        if s.Stopped() {
3✔
4565
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4566
                        pubBytes)
×
4567
                p.Disconnect(ErrServerShuttingDown)
×
4568

×
4569
                return
×
4570
        }
×
4571

4572
        // Track the new peer in our indexes so we can quickly look it up either
4573
        // according to its public key, or its peer ID.
4574
        // TODO(roasbeef): pipe all requests through to the
4575
        // queryHandler/peerManager
4576

4577
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4578
        // be human-readable.
4579
        pubStr := string(pubBytes)
3✔
4580

3✔
4581
        s.peersByPub[pubStr] = p
3✔
4582

3✔
4583
        if p.Inbound() {
6✔
4584
                s.inboundPeers[pubStr] = p
3✔
4585
        } else {
6✔
4586
                s.outboundPeers[pubStr] = p
3✔
4587
        }
3✔
4588

4589
        // Inform the peer notifier of a peer online event so that it can be reported
4590
        // to clients listening for peer events.
4591
        var pubKey [33]byte
3✔
4592
        copy(pubKey[:], pubBytes)
3✔
4593

3✔
4594
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4595
}
4596

4597
// peerInitializer asynchronously starts a newly connected peer after it has
4598
// been added to the server's peer map. This method sets up a
4599
// peerTerminationWatcher for the given peer, and ensures that it executes even
4600
// if the peer failed to start. In the event of a successful connection, this
4601
// method reads the negotiated, local feature-bits and spawns the appropriate
4602
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4603
// be signaled of the new peer once the method returns.
4604
//
4605
// NOTE: This MUST be launched as a goroutine.
4606
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4607
        defer s.wg.Done()
3✔
4608

3✔
4609
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4610

3✔
4611
        // Avoid initializing peers while the server is exiting.
3✔
4612
        if s.Stopped() {
3✔
4613
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4614
                        pubBytes)
×
4615
                return
×
4616
        }
×
4617

4618
        // Create a channel that will be used to signal a successful start of
4619
        // the link. This prevents the peer termination watcher from beginning
4620
        // its duty too early.
4621
        ready := make(chan struct{})
3✔
4622

3✔
4623
        // Before starting the peer, launch a goroutine to watch for the
3✔
4624
        // unexpected termination of this peer, which will ensure all resources
3✔
4625
        // are properly cleaned up, and re-establish persistent connections when
3✔
4626
        // necessary. The peer termination watcher will be short circuited if
3✔
4627
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4628
        // that the server has already handled the removal of this peer.
3✔
4629
        s.wg.Add(1)
3✔
4630
        go s.peerTerminationWatcher(p, ready)
3✔
4631

3✔
4632
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4633
        // will unblock the peerTerminationWatcher.
3✔
4634
        if err := p.Start(); err != nil {
6✔
4635
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4636

3✔
4637
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4638
                return
3✔
4639
        }
3✔
4640

4641
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4642
        // was successful, and to begin watching the peer's wait group.
4643
        close(ready)
3✔
4644

3✔
4645
        s.mu.Lock()
3✔
4646
        defer s.mu.Unlock()
3✔
4647

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

3✔
4651
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4652
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4653
        pubStr := string(pubBytes)
3✔
4654
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4655
                select {
3✔
4656
                case peerChan <- p:
3✔
4657
                case <-s.quit:
×
4658
                        return
×
4659
                }
4660
        }
4661
        delete(s.peerConnectedListeners, pubStr)
3✔
4662
}
4663

4664
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4665
// and then cleans up all resources allocated to the peer, notifies relevant
4666
// sub-systems of its demise, and finally handles re-connecting to the peer if
4667
// it's persistent. If the server intentionally disconnects a peer, it should
4668
// have a corresponding entry in the ignorePeerTermination map which will cause
4669
// the cleanup routine to exit early. The passed `ready` chan is used to
4670
// synchronize when WaitForDisconnect should begin watching on the peer's
4671
// waitgroup. The ready chan should only be signaled if the peer starts
4672
// successfully, otherwise the peer should be disconnected instead.
4673
//
4674
// NOTE: This MUST be launched as a goroutine.
4675
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4676
        defer s.wg.Done()
3✔
4677

3✔
4678
        p.WaitForDisconnect(ready)
3✔
4679

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

3✔
4682
        // If the server is exiting then we can bail out early ourselves as all
3✔
4683
        // the other sub-systems will already be shutting down.
3✔
4684
        if s.Stopped() {
6✔
4685
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
3✔
4686
                return
3✔
4687
        }
3✔
4688

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

3✔
4695
        pubKey := p.IdentityKey()
3✔
4696

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

3✔
4701
        // Tell the switch to remove all links associated with this peer.
3✔
4702
        // Passing nil as the target link indicates that all links associated
3✔
4703
        // with this interface should be closed.
3✔
4704
        //
3✔
4705
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4706
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4707
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4708
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4709
        }
×
4710

4711
        for _, link := range links {
6✔
4712
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4713
        }
3✔
4714

4715
        s.mu.Lock()
3✔
4716
        defer s.mu.Unlock()
3✔
4717

3✔
4718
        // If there were any notification requests for when this peer
3✔
4719
        // disconnected, we can trigger them now.
3✔
4720
        srvrLog.Debugf("Notifying that peer %v is offline", p)
3✔
4721
        pubStr := string(pubKey.SerializeCompressed())
3✔
4722
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4723
                close(offlineChan)
3✔
4724
        }
3✔
4725
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4726

3✔
4727
        // If the server has already removed this peer, we can short circuit the
3✔
4728
        // peer termination watcher and skip cleanup.
3✔
4729
        if _, ok := s.ignorePeerTermination[p]; ok {
3✔
4730
                delete(s.ignorePeerTermination, p)
×
4731

×
4732
                pubKey := p.PubKey()
×
4733
                pubStr := string(pubKey[:])
×
4734

×
4735
                // If a connection callback is present, we'll go ahead and
×
4736
                // execute it now that previous peer has fully disconnected. If
×
4737
                // the callback is not present, this likely implies the peer was
×
4738
                // purposefully disconnected via RPC, and that no reconnect
×
4739
                // should be attempted.
×
4740
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4741
                if ok {
×
4742
                        delete(s.scheduledPeerConnection, pubStr)
×
4743
                        connCallback()
×
4744
                }
×
4745
                return
×
4746
        }
4747

4748
        // First, cleanup any remaining state the server has regarding the peer
4749
        // in question.
4750
        s.removePeer(p)
3✔
4751

3✔
4752
        // Next, check to see if this is a persistent peer or not.
3✔
4753
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4754
                return
3✔
4755
        }
3✔
4756

4757
        // Get the last address that we used to connect to the peer.
4758
        addrs := []net.Addr{
3✔
4759
                p.NetAddress().Address,
3✔
4760
        }
3✔
4761

3✔
4762
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4763
        // reconnection purposes.
3✔
4764
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
3✔
4765
        switch {
3✔
4766
        // We found advertised addresses, so use them.
4767
        case err == nil:
3✔
4768
                addrs = advertisedAddrs
3✔
4769

4770
        // The peer doesn't have an advertised address.
4771
        case err == errNoAdvertisedAddr:
3✔
4772
                // If it is an outbound peer then we fall back to the existing
3✔
4773
                // peer address.
3✔
4774
                if !p.Inbound() {
6✔
4775
                        break
3✔
4776
                }
4777

4778
                // Fall back to the existing peer address if
4779
                // we're not accepting connections over Tor.
4780
                if s.torController == nil {
6✔
4781
                        break
3✔
4782
                }
4783

4784
                // If we are, the peer's address won't be known
4785
                // to us (we'll see a private address, which is
4786
                // the address used by our onion service to dial
4787
                // to lnd), so we don't have enough information
4788
                // to attempt a reconnect.
4789
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4790
                        "to inbound peer %v without "+
×
4791
                        "advertised address", p)
×
4792
                return
×
4793

4794
        // We came across an error retrieving an advertised
4795
        // address, log it, and fall back to the existing peer
4796
        // address.
4797
        default:
3✔
4798
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4799
                        "address for node %x: %v", p.PubKey(),
3✔
4800
                        err)
3✔
4801
        }
4802

4803
        // Make an easy lookup map so that we can check if an address
4804
        // is already in the address list that we have stored for this peer.
4805
        existingAddrs := make(map[string]bool)
3✔
4806
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4807
                existingAddrs[addr.String()] = true
3✔
4808
        }
3✔
4809

4810
        // Add any missing addresses for this peer to persistentPeerAddr.
4811
        for _, addr := range addrs {
6✔
4812
                if existingAddrs[addr.String()] {
3✔
4813
                        continue
×
4814
                }
4815

4816
                s.persistentPeerAddrs[pubStr] = append(
3✔
4817
                        s.persistentPeerAddrs[pubStr],
3✔
4818
                        &lnwire.NetAddress{
3✔
4819
                                IdentityKey: p.IdentityKey(),
3✔
4820
                                Address:     addr,
3✔
4821
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4822
                        },
3✔
4823
                )
3✔
4824
        }
4825

4826
        // Record the computed backoff in the backoff map.
4827
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4828
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4829

3✔
4830
        // Initialize a retry canceller for this peer if one does not
3✔
4831
        // exist.
3✔
4832
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4833
        if !ok {
6✔
4834
                cancelChan = make(chan struct{})
3✔
4835
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4836
        }
3✔
4837

4838
        // We choose not to wait group this go routine since the Connect
4839
        // call can stall for arbitrarily long if we shutdown while an
4840
        // outbound connection attempt is being made.
4841
        go func() {
6✔
4842
                srvrLog.Debugf("Scheduling connection re-establishment to "+
3✔
4843
                        "persistent peer %x in %s",
3✔
4844
                        p.IdentityKey().SerializeCompressed(), backoff)
3✔
4845

3✔
4846
                select {
3✔
4847
                case <-time.After(backoff):
3✔
4848
                case <-cancelChan:
3✔
4849
                        return
3✔
4850
                case <-s.quit:
3✔
4851
                        return
3✔
4852
                }
4853

4854
                srvrLog.Debugf("Attempting to re-establish persistent "+
3✔
4855
                        "connection to peer %x",
3✔
4856
                        p.IdentityKey().SerializeCompressed())
3✔
4857

3✔
4858
                s.connectToPersistentPeer(pubStr)
3✔
4859
        }()
4860
}
4861

4862
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4863
// to connect to the peer. It creates connection requests if there are
4864
// currently none for a given address and it removes old connection requests
4865
// if the associated address is no longer in the latest address list for the
4866
// peer.
4867
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4868
        s.mu.Lock()
3✔
4869
        defer s.mu.Unlock()
3✔
4870

3✔
4871
        // Create an easy lookup map of the addresses we have stored for the
3✔
4872
        // peer. We will remove entries from this map if we have existing
3✔
4873
        // connection requests for the associated address and then any leftover
3✔
4874
        // entries will indicate which addresses we should create new
3✔
4875
        // connection requests for.
3✔
4876
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4877
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4878
                addrMap[addr.String()] = addr
3✔
4879
        }
3✔
4880

4881
        // Go through each of the existing connection requests and
4882
        // check if they correspond to the latest set of addresses. If
4883
        // there is a connection requests that does not use one of the latest
4884
        // advertised addresses then remove that connection request.
4885
        var updatedConnReqs []*connmgr.ConnReq
3✔
4886
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4887
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4888

3✔
4889
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4890
                // If the existing connection request is using one of the
4891
                // latest advertised addresses for the peer then we add it to
4892
                // updatedConnReqs and remove the associated address from
4893
                // addrMap so that we don't recreate this connReq later on.
4894
                case true:
×
4895
                        updatedConnReqs = append(
×
4896
                                updatedConnReqs, connReq,
×
4897
                        )
×
4898
                        delete(addrMap, lnAddr)
×
4899

4900
                // If the existing connection request is using an address that
4901
                // is not one of the latest advertised addresses for the peer
4902
                // then we remove the connecting request from the connection
4903
                // manager.
4904
                case false:
3✔
4905
                        srvrLog.Info(
3✔
4906
                                "Removing conn req:", connReq.Addr.String(),
3✔
4907
                        )
3✔
4908
                        s.connMgr.Remove(connReq.ID())
3✔
4909
                }
4910
        }
4911

4912
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4913

3✔
4914
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4915
        if !ok {
6✔
4916
                cancelChan = make(chan struct{})
3✔
4917
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4918
        }
3✔
4919

4920
        // Any addresses left in addrMap are new ones that we have not made
4921
        // connection requests for. So create new connection requests for those.
4922
        // If there is more than one address in the address map, stagger the
4923
        // creation of the connection requests for those.
4924
        go func() {
6✔
4925
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4926
                defer ticker.Stop()
3✔
4927

3✔
4928
                for _, addr := range addrMap {
6✔
4929
                        // Send the persistent connection request to the
3✔
4930
                        // connection manager, saving the request itself so we
3✔
4931
                        // can cancel/restart the process as needed.
3✔
4932
                        connReq := &connmgr.ConnReq{
3✔
4933
                                Addr:      addr,
3✔
4934
                                Permanent: true,
3✔
4935
                        }
3✔
4936

3✔
4937
                        s.mu.Lock()
3✔
4938
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4939
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4940
                        )
3✔
4941
                        s.mu.Unlock()
3✔
4942

3✔
4943
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4944
                                "channel peer %v", addr)
3✔
4945

3✔
4946
                        go s.connMgr.Connect(connReq)
3✔
4947

3✔
4948
                        select {
3✔
4949
                        case <-s.quit:
3✔
4950
                                return
3✔
4951
                        case <-cancelChan:
3✔
4952
                                return
3✔
4953
                        case <-ticker.C:
3✔
4954
                        }
4955
                }
4956
        }()
4957
}
4958

4959
// removePeer removes the passed peer from the server's state of all active
4960
// peers.
4961
func (s *server) removePeer(p *peer.Brontide) {
3✔
4962
        if p == nil {
3✔
4963
                return
×
4964
        }
×
4965

4966
        srvrLog.Debugf("removing peer %v", p)
3✔
4967

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

3✔
4972
        // If this peer had an active persistent connection request, remove it.
3✔
4973
        if p.ConnReq() != nil {
6✔
4974
                s.connMgr.Remove(p.ConnReq().ID())
3✔
4975
        }
3✔
4976

4977
        // Ignore deleting peers if we're shutting down.
4978
        if s.Stopped() {
3✔
4979
                return
×
4980
        }
×
4981

4982
        pKey := p.PubKey()
3✔
4983
        pubSer := pKey[:]
3✔
4984
        pubStr := string(pubSer)
3✔
4985

3✔
4986
        delete(s.peersByPub, pubStr)
3✔
4987

3✔
4988
        if p.Inbound() {
6✔
4989
                delete(s.inboundPeers, pubStr)
3✔
4990
        } else {
6✔
4991
                delete(s.outboundPeers, pubStr)
3✔
4992
        }
3✔
4993

4994
        // Remove the peer's access permission from the access manager.
4995
        s.peerAccessMan.removePeerAccess(p.IdentityKey())
3✔
4996

3✔
4997
        // Copy the peer's error buffer across to the server if it has any items
3✔
4998
        // in it so that we can restore peer errors across connections.
3✔
4999
        if p.ErrorBuffer().Total() > 0 {
6✔
5000
                s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
5001
        }
3✔
5002

5003
        // Inform the peer notifier of a peer offline event so that it can be
5004
        // reported to clients listening for peer events.
5005
        var pubKey [33]byte
3✔
5006
        copy(pubKey[:], pubSer)
3✔
5007

3✔
5008
        s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
5009
}
5010

5011
// ConnectToPeer requests that the server connect to a Lightning Network peer
5012
// at the specified address. This function will *block* until either a
5013
// connection is established, or the initial handshake process fails.
5014
//
5015
// NOTE: This function is safe for concurrent access.
5016
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
5017
        perm bool, timeout time.Duration) error {
3✔
5018

3✔
5019
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
5020

3✔
5021
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
5022
        // better granularity.  In certain conditions, this method requires
3✔
5023
        // making an outbound connection to a remote peer, which requires the
3✔
5024
        // lock to be released, and subsequently reacquired.
3✔
5025
        s.mu.Lock()
3✔
5026

3✔
5027
        // Ensure we're not already connected to this peer.
3✔
5028
        peer, err := s.findPeerByPubStr(targetPub)
3✔
5029
        if err == nil {
6✔
5030
                s.mu.Unlock()
3✔
5031
                return &errPeerAlreadyConnected{peer: peer}
3✔
5032
        }
3✔
5033

5034
        // Peer was not found, continue to pursue connection with peer.
5035

5036
        // If there's already a pending connection request for this pubkey,
5037
        // then we ignore this request to ensure we don't create a redundant
5038
        // connection.
5039
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
5040
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
5041
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
5042
        }
3✔
5043

5044
        // If there's not already a pending or active connection to this node,
5045
        // then instruct the connection manager to attempt to establish a
5046
        // persistent connection to the peer.
5047
        srvrLog.Debugf("Connecting to %v", addr)
3✔
5048
        if perm {
6✔
5049
                connReq := &connmgr.ConnReq{
3✔
5050
                        Addr:      addr,
3✔
5051
                        Permanent: true,
3✔
5052
                }
3✔
5053

3✔
5054
                // Since the user requested a permanent connection, we'll set
3✔
5055
                // the entry to true which will tell the server to continue
3✔
5056
                // reconnecting even if the number of channels with this peer is
3✔
5057
                // zero.
3✔
5058
                s.persistentPeers[targetPub] = true
3✔
5059
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
5060
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
5061
                }
3✔
5062
                s.persistentConnReqs[targetPub] = append(
3✔
5063
                        s.persistentConnReqs[targetPub], connReq,
3✔
5064
                )
3✔
5065
                s.mu.Unlock()
3✔
5066

3✔
5067
                go s.connMgr.Connect(connReq)
3✔
5068

3✔
5069
                return nil
3✔
5070
        }
5071
        s.mu.Unlock()
3✔
5072

3✔
5073
        // If we're not making a persistent connection, then we'll attempt to
3✔
5074
        // connect to the target peer. If the we can't make the connection, or
3✔
5075
        // the crypto negotiation breaks down, then return an error to the
3✔
5076
        // caller.
3✔
5077
        errChan := make(chan error, 1)
3✔
5078
        s.connectToPeer(addr, errChan, timeout)
3✔
5079

3✔
5080
        select {
3✔
5081
        case err := <-errChan:
3✔
5082
                return err
3✔
5083
        case <-s.quit:
×
5084
                return ErrServerShuttingDown
×
5085
        }
5086
}
5087

5088
// connectToPeer establishes a connection to a remote peer. errChan is used to
5089
// notify the caller if the connection attempt has failed. Otherwise, it will be
5090
// closed.
5091
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5092
        errChan chan<- error, timeout time.Duration) {
3✔
5093

3✔
5094
        conn, err := brontide.Dial(
3✔
5095
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5096
        )
3✔
5097
        if err != nil {
6✔
5098
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5099
                select {
3✔
5100
                case errChan <- err:
3✔
5101
                case <-s.quit:
×
5102
                }
5103
                return
3✔
5104
        }
5105

5106
        close(errChan)
3✔
5107

3✔
5108
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5109
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5110

3✔
5111
        s.OutboundPeerConnected(nil, conn)
3✔
5112
}
5113

5114
// DisconnectPeer sends the request to server to close the connection with peer
5115
// identified by public key.
5116
//
5117
// NOTE: This function is safe for concurrent access.
5118
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5119
        pubBytes := pubKey.SerializeCompressed()
3✔
5120
        pubStr := string(pubBytes)
3✔
5121

3✔
5122
        s.mu.Lock()
3✔
5123
        defer s.mu.Unlock()
3✔
5124

3✔
5125
        // Check that were actually connected to this peer. If not, then we'll
3✔
5126
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5127
        // currently connected to.
3✔
5128
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5129
        if err == ErrPeerNotConnected {
6✔
5130
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5131
        }
3✔
5132

5133
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5134

3✔
5135
        s.cancelConnReqs(pubStr, nil)
3✔
5136

3✔
5137
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5138
        // them from this map so we don't attempt to re-connect after we
3✔
5139
        // disconnect.
3✔
5140
        delete(s.persistentPeers, pubStr)
3✔
5141
        delete(s.persistentPeersBackoff, pubStr)
3✔
5142

3✔
5143
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5144
        // removePeer, which bypassed the peerTerminationWatcher.
3✔
5145
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5146

3✔
5147
        return nil
3✔
5148
}
5149

5150
// OpenChannel sends a request to the server to open a channel to the specified
5151
// peer identified by nodeKey with the passed channel funding parameters.
5152
//
5153
// NOTE: This function is safe for concurrent access.
5154
func (s *server) OpenChannel(
5155
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5156

3✔
5157
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5158
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5159
        // not blocked if the caller is not reading the updates.
3✔
5160
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5161
        req.Err = make(chan error, 1)
3✔
5162

3✔
5163
        // First attempt to locate the target peer to open a channel with, if
3✔
5164
        // we're unable to locate the peer then this request will fail.
3✔
5165
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5166
        s.mu.RLock()
3✔
5167
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5168
        if !ok {
3✔
5169
                s.mu.RUnlock()
×
5170

×
5171
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5172
                return req.Updates, req.Err
×
5173
        }
×
5174
        req.Peer = peer
3✔
5175
        s.mu.RUnlock()
3✔
5176

3✔
5177
        // We'll wait until the peer is active before beginning the channel
3✔
5178
        // opening process.
3✔
5179
        select {
3✔
5180
        case <-peer.ActiveSignal():
3✔
5181
        case <-peer.QuitSignal():
×
5182
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5183
                return req.Updates, req.Err
×
5184
        case <-s.quit:
×
5185
                req.Err <- ErrServerShuttingDown
×
5186
                return req.Updates, req.Err
×
5187
        }
5188

5189
        // If the fee rate wasn't specified at this point we fail the funding
5190
        // because of the missing fee rate information. The caller of the
5191
        // `OpenChannel` method needs to make sure that default values for the
5192
        // fee rate are set beforehand.
5193
        if req.FundingFeePerKw == 0 {
3✔
5194
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5195
                        "the channel opening transaction")
×
5196

×
5197
                return req.Updates, req.Err
×
5198
        }
×
5199

5200
        // Spawn a goroutine to send the funding workflow request to the funding
5201
        // manager. This allows the server to continue handling queries instead
5202
        // of blocking on this request which is exported as a synchronous
5203
        // request to the outside world.
5204
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5205

3✔
5206
        return req.Updates, req.Err
3✔
5207
}
5208

5209
// Peers returns a slice of all active peers.
5210
//
5211
// NOTE: This function is safe for concurrent access.
5212
func (s *server) Peers() []*peer.Brontide {
3✔
5213
        s.mu.RLock()
3✔
5214
        defer s.mu.RUnlock()
3✔
5215

3✔
5216
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5217
        for _, peer := range s.peersByPub {
6✔
5218
                peers = append(peers, peer)
3✔
5219
        }
3✔
5220

5221
        return peers
3✔
5222
}
5223

5224
// computeNextBackoff uses a truncated exponential backoff to compute the next
5225
// backoff using the value of the exiting backoff. The returned duration is
5226
// randomized in either direction by 1/20 to prevent tight loops from
5227
// stabilizing.
5228
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5229
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5230
        nextBackoff := 2 * currBackoff
3✔
5231
        if nextBackoff > maxBackoff {
6✔
5232
                nextBackoff = maxBackoff
3✔
5233
        }
3✔
5234

5235
        // Using 1/10 of our duration as a margin, compute a random offset to
5236
        // avoid the nodes entering connection cycles.
5237
        margin := nextBackoff / 10
3✔
5238

3✔
5239
        var wiggle big.Int
3✔
5240
        wiggle.SetUint64(uint64(margin))
3✔
5241
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5242
                // Randomizing is not mission critical, so we'll just return the
×
5243
                // current backoff.
×
5244
                return nextBackoff
×
5245
        }
×
5246

5247
        // Otherwise add in our wiggle, but subtract out half of the margin so
5248
        // that the backoff can tweaked by 1/20 in either direction.
5249
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5250
}
5251

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

5256
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5257
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
5258
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5259
        if err != nil {
3✔
5260
                return nil, err
×
5261
        }
×
5262

5263
        node, err := s.graphDB.FetchLightningNode(vertex)
3✔
5264
        if err != nil {
6✔
5265
                return nil, err
3✔
5266
        }
3✔
5267

5268
        if len(node.Addresses) == 0 {
6✔
5269
                return nil, errNoAdvertisedAddr
3✔
5270
        }
3✔
5271

5272
        return node.Addresses, nil
3✔
5273
}
5274

5275
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5276
// channel update for a target channel.
5277
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5278
        *lnwire.ChannelUpdate1, error) {
3✔
5279

3✔
5280
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5281
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5282
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5283
                if err != nil {
6✔
5284
                        return nil, err
3✔
5285
                }
3✔
5286

5287
                return netann.ExtractChannelUpdate(
3✔
5288
                        ourPubKey[:], info, edge1, edge2,
3✔
5289
                )
3✔
5290
        }
5291
}
5292

5293
// applyChannelUpdate applies the channel update to the different sub-systems of
5294
// the server. The useAlias boolean denotes whether or not to send an alias in
5295
// place of the real SCID.
5296
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5297
        op *wire.OutPoint, useAlias bool) error {
3✔
5298

3✔
5299
        var (
3✔
5300
                peerAlias    *lnwire.ShortChannelID
3✔
5301
                defaultAlias lnwire.ShortChannelID
3✔
5302
        )
3✔
5303

3✔
5304
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5305

3✔
5306
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5307
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5308
        if useAlias {
6✔
5309
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5310
                if foundAlias != defaultAlias {
6✔
5311
                        peerAlias = &foundAlias
3✔
5312
                }
3✔
5313
        }
5314

5315
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5316
                update, discovery.RemoteAlias(peerAlias),
3✔
5317
        )
3✔
5318
        select {
3✔
5319
        case err := <-errChan:
3✔
5320
                return err
3✔
5321
        case <-s.quit:
×
5322
                return ErrServerShuttingDown
×
5323
        }
5324
}
5325

5326
// SendCustomMessage sends a custom message to the peer with the specified
5327
// pubkey.
5328
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5329
        data []byte) error {
3✔
5330

3✔
5331
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5332
        if err != nil {
3✔
5333
                return err
×
5334
        }
×
5335

5336
        // We'll wait until the peer is active.
5337
        select {
3✔
5338
        case <-peer.ActiveSignal():
3✔
5339
        case <-peer.QuitSignal():
×
5340
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5341
        case <-s.quit:
×
5342
                return ErrServerShuttingDown
×
5343
        }
5344

5345
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5346
        if err != nil {
6✔
5347
                return err
3✔
5348
        }
3✔
5349

5350
        // Send the message as low-priority. For now we assume that all
5351
        // application-defined message are low priority.
5352
        return peer.SendMessageLazy(true, msg)
3✔
5353
}
5354

5355
// newSweepPkScriptGen creates closure that generates a new public key script
5356
// which should be used to sweep any funds into the on-chain wallet.
5357
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5358
// (p2wkh) output.
5359
func newSweepPkScriptGen(
5360
        wallet lnwallet.WalletController,
5361
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5362

3✔
5363
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5364
                sweepAddr, err := wallet.NewAddress(
3✔
5365
                        lnwallet.TaprootPubkey, false,
3✔
5366
                        lnwallet.DefaultAccountName,
3✔
5367
                )
3✔
5368
                if err != nil {
3✔
5369
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5370
                }
×
5371

5372
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5373
                if err != nil {
3✔
5374
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5375
                }
×
5376

5377
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5378
                        wallet, netParams, addr,
3✔
5379
                )
3✔
5380
                if err != nil {
3✔
5381
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5382
                }
×
5383

5384
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5385
                        DeliveryAddress: addr,
3✔
5386
                        InternalKey:     internalKeyDesc,
3✔
5387
                })
3✔
5388
        }
5389
}
5390

5391
// shouldPeerBootstrap returns true if we should attempt to perform peer
5392
// bootstrapping to actively seek our peers using the set of active network
5393
// bootstrappers.
5394
func shouldPeerBootstrap(cfg *Config) bool {
3✔
5395
        isSimnet := cfg.Bitcoin.SimNet
3✔
5396
        isSignet := cfg.Bitcoin.SigNet
3✔
5397
        isRegtest := cfg.Bitcoin.RegTest
3✔
5398
        isDevNetwork := isSimnet || isSignet || isRegtest
3✔
5399

3✔
5400
        // TODO(yy): remove the check on simnet/regtest such that the itest is
3✔
5401
        // covering the bootstrapping process.
3✔
5402
        return !cfg.NoNetBootstrap && !isDevNetwork
3✔
5403
}
3✔
5404

5405
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5406
// finished.
5407
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5408
        // Get a list of closed channels.
3✔
5409
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5410
        if err != nil {
3✔
5411
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5412
                return nil
×
5413
        }
×
5414

5415
        // Save the SCIDs in a map.
5416
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5417
        for _, c := range channels {
6✔
5418
                // If the channel is not pending, its FC has been finalized.
3✔
5419
                if !c.IsPending {
6✔
5420
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5421
                }
3✔
5422
        }
5423

5424
        // Double check whether the reported closed channel has indeed finished
5425
        // closing.
5426
        //
5427
        // NOTE: There are misalignments regarding when a channel's FC is
5428
        // marked as finalized. We double check the pending channels to make
5429
        // sure the returned SCIDs are indeed terminated.
5430
        //
5431
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5432
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5433
        if err != nil {
3✔
5434
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5435
                return nil
×
5436
        }
×
5437

5438
        for _, c := range pendings {
6✔
5439
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5440
                        continue
3✔
5441
                }
5442

5443
                // If the channel is still reported as pending, remove it from
5444
                // the map.
5445
                delete(closedSCIDs, c.ShortChannelID)
×
5446

×
5447
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5448
                        c.ShortChannelID)
×
5449
        }
5450

5451
        return closedSCIDs
3✔
5452
}
5453

5454
// getStartingBeat returns the current beat. This is used during the startup to
5455
// initialize blockbeat consumers.
5456
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5457
        // beat is the current blockbeat.
3✔
5458
        var beat *chainio.Beat
3✔
5459

3✔
5460
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5461
        // we will skip fetching the best block.
3✔
5462
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5463
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5464
                        "mode")
×
5465

×
5466
                return &chainio.Beat{}, nil
×
5467
        }
×
5468

5469
        // We should get a notification with the current best block immediately
5470
        // by passing a nil block.
5471
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5472
        if err != nil {
3✔
5473
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5474
        }
×
5475
        defer blockEpochs.Cancel()
3✔
5476

3✔
5477
        // We registered for the block epochs with a nil request. The notifier
3✔
5478
        // should send us the current best block immediately. So we need to
3✔
5479
        // wait for it here because we need to know the current best height.
3✔
5480
        select {
3✔
5481
        case bestBlock := <-blockEpochs.Epochs:
3✔
5482
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5483
                        bestBlock.Hash, bestBlock.Height)
3✔
5484

3✔
5485
                // Update the current blockbeat.
3✔
5486
                beat = chainio.NewBeat(*bestBlock)
3✔
5487

5488
        case <-s.quit:
×
5489
                srvrLog.Debug("LND shutting down")
×
5490
        }
5491

5492
        return beat, nil
3✔
5493
}
5494

5495
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5496
// point has an active RBF chan closer.
5497
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5498
        chanPoint wire.OutPoint) bool {
3✔
5499

3✔
5500
        pubBytes := peerPub.SerializeCompressed()
3✔
5501

3✔
5502
        s.mu.RLock()
3✔
5503
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5504
        s.mu.RUnlock()
3✔
5505
        if !ok {
3✔
5506
                return false
×
5507
        }
×
5508

5509
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5510
}
5511

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

3✔
5520
        // First, we'll attempt to look up the channel based on it's
3✔
5521
        // ChannelPoint.
3✔
5522
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5523
        if err != nil {
3✔
5524
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5525
        }
×
5526

5527
        // From the channel, we can now get the pubkey of the peer, then use
5528
        // that to eventually get the chan closer.
5529
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5530

3✔
5531
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5532
        s.mu.RLock()
3✔
5533
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5534
        s.mu.RUnlock()
3✔
5535
        if !ok {
3✔
5536
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5537
                        "not online", chanPoint)
×
5538
        }
×
5539

5540
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5541
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5542
        )
3✔
5543
        if err != nil {
3✔
5544
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5545
                        "%w", err)
×
5546
        }
×
5547

5548
        return closeUpdates, nil
3✔
5549
}
5550

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

3✔
5559
        // If the channel is present in the switch, then the request should flow
3✔
5560
        // through the switch instead.
3✔
5561
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5562
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5563
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5564
                        "invalid request", chanPoint)
×
5565
        }
×
5566

5567
        // At this point, we know that the channel isn't present in the link, so
5568
        // we'll check to see if we have an entry in the active chan closer map.
5569
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5570
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5571
        )
3✔
5572
        if err != nil {
3✔
5573
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5574
                        "ChannelPoint(%v)", chanPoint)
×
5575
        }
×
5576

5577
        return updates, nil
3✔
5578
}
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