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

lightningnetwork / lnd / 13593508312

28 Feb 2025 05:41PM UTC coverage: 58.287% (-10.4%) from 68.65%
13593508312

Pull #9458

github

web-flow
Merge d40067c0c into f1182e433
Pull Request #9458: multi+server.go: add initial permissions for some peers

346 of 548 new or added lines in 10 files covered. (63.14%)

27412 existing lines in 442 files now uncovered.

94709 of 162488 relevant lines covered (58.29%)

1.81 hits per line

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

64.03
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

212
        start sync.Once
213
        stop  sync.Once
214

215
        cfg *Config
216

217
        implCfg *ImplementationCfg
218

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

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

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

230
        chanStatusMgr *netann.ChanStatusManager
231

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

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

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

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

252
        mu sync.RWMutex
253

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

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

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

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

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

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

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

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

304
        cc *chainreg.ChainControl
305

306
        fundingMgr *funding.Manager
307

308
        graphDB *graphdb.ChannelGraph
309

310
        chanStateDB *channeldb.ChannelStateDB
311

312
        addrSource channeldb.AddrSource
313

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

318
        invoicesDB invoices.InvoiceDB
319

320
        aliasMgr *aliasmgr.Manager
321

322
        htlcSwitch *htlcswitch.Switch
323

324
        interceptableSwitch *htlcswitch.InterceptableSwitch
325

326
        invoices *invoices.InvoiceRegistry
327

328
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
329

330
        channelNotifier *channelnotifier.ChannelNotifier
331

332
        peerNotifier *peernotifier.PeerNotifier
333

334
        htlcNotifier *htlcswitch.HtlcNotifier
335

336
        witnessBeacon contractcourt.WitnessBeacon
337

338
        breachArbitrator *contractcourt.BreachArbitrator
339

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

343
        graphBuilder *graph.Builder
344

345
        chanRouter *routing.ChannelRouter
346

347
        controlTower routing.ControlTower
348

349
        authGossiper *discovery.AuthenticatedGossiper
350

351
        localChanMgr *localchans.Manager
352

353
        utxoNursery *contractcourt.UtxoNursery
354

355
        sweeper *sweep.UtxoSweeper
356

357
        chainArb *contractcourt.ChainArbitrator
358

359
        sphinx *hop.OnionProcessor
360

361
        towerClientMgr *wtclient.Manager
362

363
        connMgr *connmgr.ConnManager
364

365
        sigPool *lnwallet.SigPool
366

367
        writePool *pool.Write
368

369
        readPool *pool.Read
370

371
        tlsManager *TLSManager
372

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

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

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

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

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

395
        hostAnn *netann.HostAnnouncer
396

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

400
        customMessageServer *subscribe.Server
401

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

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

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

412
        quit chan struct{}
413

414
        wg sync.WaitGroup
415
}
416

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

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

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

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

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

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

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

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

472
                                        s.mu.Lock()
3✔
473

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

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

488
                                        s.mu.Unlock()
3✔
489

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

496
        return nil
3✔
497
}
498

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

615
        //nolint:ll
616
        featureMgr, err := feature.NewManager(feature.Config{
3✔
617
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
3✔
618
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
3✔
619
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
3✔
620
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
3✔
621
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
3✔
622
                NoKeysend:                 !cfg.AcceptKeySend,
3✔
623
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
3✔
624
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
3✔
625
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
3✔
626
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
3✔
627
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
3✔
628
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
3✔
629
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
3✔
630
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
3✔
631
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
3✔
632
        })
3✔
633
        if err != nil {
3✔
634
                return nil, err
×
635
        }
×
636

637
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
638
        registryConfig := invoices.RegistryConfig{
3✔
639
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
640
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
641
                Clock:                       clock.NewDefaultClock(),
3✔
642
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
643
                AcceptAMP:                   cfg.AcceptAMP,
3✔
644
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
645
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
646
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
647
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
648
        }
3✔
649

3✔
650
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
651

3✔
652
        s := &server{
3✔
653
                cfg:            cfg,
3✔
654
                implCfg:        implCfg,
3✔
655
                graphDB:        dbs.GraphDB,
3✔
656
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
657
                addrSource:     addrSource,
3✔
658
                miscDB:         dbs.ChanStateDB,
3✔
659
                invoicesDB:     dbs.InvoiceDB,
3✔
660
                cc:             cc,
3✔
661
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
662
                writePool:      writePool,
3✔
663
                readPool:       readPool,
3✔
664
                chansToRestore: chansToRestore,
3✔
665

3✔
666
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
667
                        cc.ChainNotifier,
3✔
668
                ),
3✔
669
                channelNotifier: channelnotifier.New(
3✔
670
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
671
                ),
3✔
672

3✔
673
                identityECDH:   nodeKeyECDH,
3✔
674
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
675
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
676

3✔
677
                listenAddrs: listenAddrs,
3✔
678

3✔
679
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
680
                // schedule
3✔
681
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
682

3✔
683
                torController: torController,
3✔
684

3✔
685
                persistentPeers:         make(map[string]bool),
3✔
686
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
687
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
688
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
689
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
690
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
691
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
692
                scheduledPeerConnection: make(map[string]func()),
3✔
693
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
694

3✔
695
                peersByPub:                make(map[string]*peer.Brontide),
3✔
696
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
697
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
698
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
699
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
700

3✔
701
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
702

3✔
703
                customMessageServer: subscribe.NewServer(),
3✔
704

3✔
705
                tlsManager: tlsManager,
3✔
706

3✔
707
                featureMgr: featureMgr,
3✔
708
                quit:       make(chan struct{}),
3✔
709
        }
3✔
710

3✔
711
        // Start the low-level services once they are initialized.
3✔
712
        //
3✔
713
        // TODO(yy): break the server startup into four steps,
3✔
714
        // 1. init the low-level services.
3✔
715
        // 2. start the low-level services.
3✔
716
        // 3. init the high-level services.
3✔
717
        // 4. start the high-level services.
3✔
718
        if err := s.startLowLevelServices(); err != nil {
3✔
719
                return nil, err
×
720
        }
×
721

722
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
723
        if err != nil {
3✔
724
                return nil, err
×
725
        }
×
726

727
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
728
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
729
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
730
        )
3✔
731
        s.invoices = invoices.NewRegistry(
3✔
732
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
733
        )
3✔
734

3✔
735
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
736

3✔
737
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
738
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
739

3✔
740
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
741
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
742
                if err != nil {
3✔
743
                        return err
×
744
                }
×
745

746
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
747

3✔
748
                return nil
3✔
749
        }
750

751
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
752
        if err != nil {
3✔
753
                return nil, err
×
754
        }
×
755

756
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
757
                DB:                   dbs.ChanStateDB,
3✔
758
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
759
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
760
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
761
                LocalChannelClose: func(pubKey []byte,
3✔
762
                        request *htlcswitch.ChanClose) {
6✔
763

3✔
764
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
765
                        if err != nil {
3✔
766
                                srvrLog.Errorf("unable to close channel, peer"+
×
767
                                        " with %v id can't be found: %v",
×
768
                                        pubKey, err,
×
769
                                )
×
770
                                return
×
771
                        }
×
772

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

808
        s.witnessBeacon = newPreimageBeacon(
3✔
809
                dbs.ChanStateDB.NewWitnessCache(),
3✔
810
                s.interceptableSwitch.ForwardPacket,
3✔
811
        )
3✔
812

3✔
813
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
814
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
815
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
816
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
817
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
818
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
819
                MessageSigner:            s.nodeSigner,
3✔
820
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
821
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
822
                DB:                       s.chanStateDB,
3✔
823
                Graph:                    dbs.GraphDB,
3✔
824
        }
3✔
825

3✔
826
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
827
        if err != nil {
3✔
828
                return nil, err
×
829
        }
×
830
        s.chanStatusMgr = chanStatusMgr
3✔
831

3✔
832
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
833
        // port forwarding for users behind a NAT.
3✔
834
        if cfg.NAT {
3✔
835
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
836

×
837
                discoveryTimeout := time.Duration(10 * time.Second)
×
838

×
839
                ctx, cancel := context.WithTimeout(
×
840
                        context.Background(), discoveryTimeout,
×
841
                )
×
842
                defer cancel()
×
843
                upnp, err := nat.DiscoverUPnP(ctx)
×
844
                if err == nil {
×
845
                        s.natTraversal = upnp
×
846
                } else {
×
847
                        // If we were not able to discover a UPnP enabled device
×
848
                        // on the local network, we'll fall back to attempting
×
849
                        // to discover a NAT-PMP enabled device.
×
850
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
851
                                "device on the local network: %v", err)
×
852

×
853
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
854
                                "enabled device")
×
855

×
856
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
857
                        if err != nil {
×
858
                                err := fmt.Errorf("unable to discover a "+
×
859
                                        "NAT-PMP enabled device on the local "+
×
860
                                        "network: %v", err)
×
861
                                srvrLog.Error(err)
×
862
                                return nil, err
×
863
                        }
×
864

865
                        s.natTraversal = pmp
×
866
                }
867
        }
868

869
        // If we were requested to automatically configure port forwarding,
870
        // we'll use the ports that the server will be listening on.
871
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
3✔
872
        for idx, ip := range cfg.ExternalIPs {
6✔
873
                externalIPStrings[idx] = ip.String()
3✔
874
        }
3✔
875
        if s.natTraversal != nil {
3✔
876
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
877
                for _, listenAddr := range listenAddrs {
×
878
                        // At this point, the listen addresses should have
×
879
                        // already been normalized, so it's safe to ignore the
×
880
                        // errors.
×
881
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
882
                        port, _ := strconv.Atoi(portStr)
×
883

×
884
                        listenPorts = append(listenPorts, uint16(port))
×
885
                }
×
886

887
                ips, err := s.configurePortForwarding(listenPorts...)
×
888
                if err != nil {
×
889
                        srvrLog.Errorf("Unable to automatically set up port "+
×
890
                                "forwarding using %s: %v",
×
891
                                s.natTraversal.Name(), err)
×
892
                } else {
×
893
                        srvrLog.Infof("Automatically set up port forwarding "+
×
894
                                "using %s to advertise external IP",
×
895
                                s.natTraversal.Name())
×
896
                        externalIPStrings = append(externalIPStrings, ips...)
×
897
                }
×
898
        }
899

900
        // If external IP addresses have been specified, add those to the list
901
        // of this server's addresses.
902
        externalIPs, err := lncfg.NormalizeAddresses(
3✔
903
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
904
                cfg.net.ResolveTCPAddr,
3✔
905
        )
3✔
906
        if err != nil {
3✔
907
                return nil, err
×
908
        }
×
909

910
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
3✔
911
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
912

3✔
913
        // We'll now reconstruct a node announcement based on our current
3✔
914
        // configuration so we can send it out as a sort of heart beat within
3✔
915
        // the network.
3✔
916
        //
3✔
917
        // We'll start by parsing the node color from configuration.
3✔
918
        color, err := lncfg.ParseHexColor(cfg.Color)
3✔
919
        if err != nil {
3✔
920
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
921
                return nil, err
×
922
        }
×
923

924
        // If no alias is provided, default to first 10 characters of public
925
        // key.
926
        alias := cfg.Alias
3✔
927
        if alias == "" {
6✔
928
                alias = hex.EncodeToString(serializedPubKey[:10])
3✔
929
        }
3✔
930
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
931
        if err != nil {
3✔
932
                return nil, err
×
933
        }
×
934
        selfNode := &models.LightningNode{
3✔
935
                HaveNodeAnnouncement: true,
3✔
936
                LastUpdate:           time.Now(),
3✔
937
                Addresses:            selfAddrs,
3✔
938
                Alias:                nodeAlias.String(),
3✔
939
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
940
                Color:                color,
3✔
941
        }
3✔
942
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
943

3✔
944
        // Based on the disk representation of the node announcement generated
3✔
945
        // above, we'll generate a node announcement that can go out on the
3✔
946
        // network so we can properly sign it.
3✔
947
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
948
        if err != nil {
3✔
949
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
950
        }
×
951

952
        // With the announcement generated, we'll sign it to properly
953
        // authenticate the message on the network.
954
        authSig, err := netann.SignAnnouncement(
3✔
955
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
3✔
956
        )
3✔
957
        if err != nil {
3✔
958
                return nil, fmt.Errorf("unable to generate signature for "+
×
959
                        "self node announcement: %v", err)
×
960
        }
×
961
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
962
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
963
                selfNode.AuthSigBytes,
3✔
964
        )
3✔
965
        if err != nil {
3✔
966
                return nil, err
×
967
        }
×
968

969
        // Finally, we'll update the representation on disk, and update our
970
        // cached in-memory version as well.
971
        if err := dbs.GraphDB.SetSourceNode(selfNode); err != nil {
3✔
972
                return nil, fmt.Errorf("can't set self node: %w", err)
×
973
        }
×
974
        s.currentNodeAnn = nodeAnn
3✔
975

3✔
976
        // The router will get access to the payment ID sequencer, such that it
3✔
977
        // can generate unique payment IDs.
3✔
978
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
979
        if err != nil {
3✔
980
                return nil, err
×
981
        }
×
982

983
        // Instantiate mission control with config from the sub server.
984
        //
985
        // TODO(joostjager): When we are further in the process of moving to sub
986
        // servers, the mission control instance itself can be moved there too.
987
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
988

3✔
989
        // We only initialize a probability estimator if there's no custom one.
3✔
990
        var estimator routing.Estimator
3✔
991
        if cfg.Estimator != nil {
3✔
992
                estimator = cfg.Estimator
×
993
        } else {
3✔
994
                switch routingConfig.ProbabilityEstimatorType {
3✔
995
                case routing.AprioriEstimatorName:
3✔
996
                        aCfg := routingConfig.AprioriConfig
3✔
997
                        aprioriConfig := routing.AprioriConfig{
3✔
998
                                AprioriHopProbability: aCfg.HopProbability,
3✔
999
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
1000
                                AprioriWeight:         aCfg.Weight,
3✔
1001
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
1002
                        }
3✔
1003

3✔
1004
                        estimator, err = routing.NewAprioriEstimator(
3✔
1005
                                aprioriConfig,
3✔
1006
                        )
3✔
1007
                        if err != nil {
3✔
1008
                                return nil, err
×
1009
                        }
×
1010

1011
                case routing.BimodalEstimatorName:
×
1012
                        bCfg := routingConfig.BimodalConfig
×
1013
                        bimodalConfig := routing.BimodalConfig{
×
1014
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1015
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1016
                                        bCfg.Scale,
×
1017
                                ),
×
1018
                                BimodalDecayTime: bCfg.DecayTime,
×
1019
                        }
×
1020

×
1021
                        estimator, err = routing.NewBimodalEstimator(
×
1022
                                bimodalConfig,
×
1023
                        )
×
1024
                        if err != nil {
×
1025
                                return nil, err
×
1026
                        }
×
1027

1028
                default:
×
1029
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1030
                                routingConfig.ProbabilityEstimatorType)
×
1031
                }
1032
        }
1033

1034
        mcCfg := &routing.MissionControlConfig{
3✔
1035
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
1036
                Estimator:               estimator,
3✔
1037
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
1038
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
1039
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
1040
        }
3✔
1041

3✔
1042
        s.missionController, err = routing.NewMissionController(
3✔
1043
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
1044
        )
3✔
1045
        if err != nil {
3✔
1046
                return nil, fmt.Errorf("can't create mission control "+
×
1047
                        "manager: %w", err)
×
1048
        }
×
1049
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
1050
                routing.DefaultMissionControlNamespace,
3✔
1051
        )
3✔
1052
        if err != nil {
3✔
1053
                return nil, fmt.Errorf("can't create mission control in the "+
×
1054
                        "default namespace: %w", err)
×
1055
        }
×
1056

1057
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1058
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1059
                int64(routingConfig.AttemptCost),
3✔
1060
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1061
                routingConfig.MinRouteProbability)
3✔
1062

3✔
1063
        pathFindingConfig := routing.PathFindingConfig{
3✔
1064
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1065
                        routingConfig.AttemptCost,
3✔
1066
                ),
3✔
1067
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1068
                MinProbability: routingConfig.MinRouteProbability,
3✔
1069
        }
3✔
1070

3✔
1071
        sourceNode, err := dbs.GraphDB.SourceNode()
3✔
1072
        if err != nil {
3✔
1073
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1074
        }
×
1075
        paymentSessionSource := &routing.SessionSource{
3✔
1076
                GraphSessionFactory: dbs.GraphDB,
3✔
1077
                SourceNode:          sourceNode,
3✔
1078
                MissionControl:      s.defaultMC,
3✔
1079
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1080
                PathFindingConfig:   pathFindingConfig,
3✔
1081
        }
3✔
1082

3✔
1083
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1084

3✔
1085
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1086

3✔
1087
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1088
                cfg.Routing.StrictZombiePruning
3✔
1089

3✔
1090
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1091
                SelfNode:            selfNode.PubKeyBytes,
3✔
1092
                Graph:               dbs.GraphDB,
3✔
1093
                Chain:               cc.ChainIO,
3✔
1094
                ChainView:           cc.ChainView,
3✔
1095
                Notifier:            cc.ChainNotifier,
3✔
1096
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1097
                GraphPruneInterval:  time.Hour,
3✔
1098
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1099
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1100
                StrictZombiePruning: strictPruning,
3✔
1101
                IsAlias:             aliasmgr.IsAlias,
3✔
1102
        })
3✔
1103
        if err != nil {
3✔
1104
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1105
        }
×
1106

1107
        s.chanRouter, err = routing.New(routing.Config{
3✔
1108
                SelfNode:           selfNode.PubKeyBytes,
3✔
1109
                RoutingGraph:       dbs.GraphDB,
3✔
1110
                Chain:              cc.ChainIO,
3✔
1111
                Payer:              s.htlcSwitch,
3✔
1112
                Control:            s.controlTower,
3✔
1113
                MissionControl:     s.defaultMC,
3✔
1114
                SessionSource:      paymentSessionSource,
3✔
1115
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1116
                NextPaymentID:      sequencer.NextID,
3✔
1117
                PathFindingConfig:  pathFindingConfig,
3✔
1118
                Clock:              clock.NewDefaultClock(),
3✔
1119
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1120
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1121
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1122
        })
3✔
1123
        if err != nil {
3✔
1124
                return nil, fmt.Errorf("can't create router: %w", err)
×
1125
        }
×
1126

1127
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1128
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1129
        if err != nil {
3✔
1130
                return nil, err
×
1131
        }
×
1132
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1133
        if err != nil {
3✔
1134
                return nil, err
×
1135
        }
×
1136

1137
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1138

3✔
1139
        s.authGossiper = discovery.New(discovery.Config{
3✔
1140
                Graph:                 s.graphBuilder,
3✔
1141
                ChainIO:               s.cc.ChainIO,
3✔
1142
                Notifier:              s.cc.ChainNotifier,
3✔
1143
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1144
                Broadcast:             s.BroadcastMessage,
3✔
1145
                ChanSeries:            chanSeries,
3✔
1146
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1147
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1148
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1149
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1150
                        error) {
3✔
1151

×
1152
                        return s.genNodeAnnouncement(nil)
×
1153
                },
×
1154
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1155
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1156
                RetransmitTicker:        ticker.New(time.Minute * 30),
1157
                RebroadcastInterval:     time.Hour * 24,
1158
                WaitingProofStore:       waitingProofStore,
1159
                MessageStore:            gossipMessageStore,
1160
                AnnSigner:               s.nodeSigner,
1161
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1162
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1163
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1164
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1165
                MinimumBatchSize:        10,
1166
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1167
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1168
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1169
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1170
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1171
                IsAlias:                 aliasmgr.IsAlias,
1172
                SignAliasUpdate:         s.signAliasUpdate,
1173
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1174
                GetAlias:                s.aliasMgr.GetPeerAlias,
1175
                FindChannel:             s.findChannel,
1176
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1177
                ScidCloser:              scidCloserMan,
1178
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1179
        }, nodeKeyDesc)
1180

1181
        accessCfg := &accessManConfig{
3✔
1182
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1183
                        error) {
6✔
1184

3✔
1185
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1186
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1187
                                genesisHash[:],
3✔
1188
                        )
3✔
1189
                },
3✔
1190
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1191
                maxRestrictedSlots: s.cfg.NumRestrictedSlots,
1192
        }
1193

1194
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1195
        if err != nil {
3✔
NEW
1196
                return nil, err
×
NEW
1197
        }
×
1198

1199
        s.peerAccessMan = peerAccessMan
3✔
1200

3✔
1201
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1202
        //nolint:ll
3✔
1203
        s.localChanMgr = &localchans.Manager{
3✔
1204
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1205
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1206
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
3✔
1207
                        *models.ChannelEdgePolicy) error) error {
6✔
1208

3✔
1209
                        return s.graphDB.ForEachNodeChannel(selfVertex,
3✔
1210
                                func(_ kvdb.RTx, c *models.ChannelEdgeInfo,
3✔
1211
                                        e *models.ChannelEdgePolicy,
3✔
1212
                                        _ *models.ChannelEdgePolicy) error {
6✔
1213

3✔
1214
                                        // NOTE: The invoked callback here may
3✔
1215
                                        // receive a nil channel policy.
3✔
1216
                                        return cb(c, e)
3✔
1217
                                },
3✔
1218
                        )
1219
                },
1220
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1221
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1222
                FetchChannel:              s.chanStateDB.FetchChannel,
1223
                AddEdge: func(edge *models.ChannelEdgeInfo) error {
×
1224
                        return s.graphBuilder.AddEdge(edge)
×
1225
                },
×
1226
        }
1227

1228
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1229
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1230
        )
3✔
1231
        if err != nil {
3✔
1232
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1233
                return nil, err
×
1234
        }
×
1235

1236
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1237
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1238
        )
3✔
1239
        if err != nil {
3✔
1240
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1241
                return nil, err
×
1242
        }
×
1243

1244
        aggregator := sweep.NewBudgetAggregator(
3✔
1245
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1246
                s.implCfg.AuxSweeper,
3✔
1247
        )
3✔
1248

3✔
1249
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1250
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1251
                Wallet:     cc.Wallet,
3✔
1252
                Estimator:  cc.FeeEstimator,
3✔
1253
                Notifier:   cc.ChainNotifier,
3✔
1254
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1255
        })
3✔
1256

3✔
1257
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1258
                FeeEstimator: cc.FeeEstimator,
3✔
1259
                GenSweepScript: newSweepPkScriptGen(
3✔
1260
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1261
                ),
3✔
1262
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1263
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1264
                Mempool:              cc.MempoolNotifier,
3✔
1265
                Notifier:             cc.ChainNotifier,
3✔
1266
                Store:                sweeperStore,
3✔
1267
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1268
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1269
                Aggregator:           aggregator,
3✔
1270
                Publisher:            s.txPublisher,
3✔
1271
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1272
        })
3✔
1273

3✔
1274
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1275
                ChainIO:             cc.ChainIO,
3✔
1276
                ConfDepth:           1,
3✔
1277
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1278
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1279
                Notifier:            cc.ChainNotifier,
3✔
1280
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1281
                Store:               utxnStore,
3✔
1282
                SweepInput:          s.sweeper.SweepInput,
3✔
1283
                Budget:              s.cfg.Sweeper.Budget,
3✔
1284
        })
3✔
1285

3✔
1286
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1287
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1288
                closureType contractcourt.ChannelCloseType) {
6✔
1289
                // TODO(conner): Properly respect the update and error channels
3✔
1290
                // returned by CloseLink.
3✔
1291

3✔
1292
                // Instruct the switch to close the channel.  Provide no close out
3✔
1293
                // delivery script or target fee per kw because user input is not
3✔
1294
                // available when the remote peer closes the channel.
3✔
1295
                s.htlcSwitch.CloseLink(chanPoint, closureType, 0, 0, nil)
3✔
1296
        }
3✔
1297

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

3✔
1302
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1303
                &contractcourt.BreachConfig{
3✔
1304
                        CloseLink: closeLink,
3✔
1305
                        DB:        s.chanStateDB,
3✔
1306
                        Estimator: s.cc.FeeEstimator,
3✔
1307
                        GenSweepScript: newSweepPkScriptGen(
3✔
1308
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1309
                        ),
3✔
1310
                        Notifier:           cc.ChainNotifier,
3✔
1311
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1312
                        ContractBreaches:   contractBreaches,
3✔
1313
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1314
                        Store: contractcourt.NewRetributionStore(
3✔
1315
                                dbs.ChanStateDB,
3✔
1316
                        ),
3✔
1317
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1318
                },
3✔
1319
        )
3✔
1320

3✔
1321
        //nolint:ll
3✔
1322
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1323
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1324
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1325
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1326
                NewSweepAddr: func() ([]byte, error) {
3✔
1327
                        addr, err := newSweepPkScriptGen(
×
1328
                                cc.Wallet, netParams,
×
1329
                        )().Unpack()
×
1330
                        if err != nil {
×
1331
                                return nil, err
×
1332
                        }
×
1333

1334
                        return addr.DeliveryAddress, nil
×
1335
                },
1336
                PublishTx: cc.Wallet.PublishTransaction,
1337
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1338
                        for _, msg := range msgs {
6✔
1339
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1340
                                if err != nil {
3✔
1341
                                        return err
×
1342
                                }
×
1343
                        }
1344
                        return nil
3✔
1345
                },
1346
                IncubateOutputs: func(chanPoint wire.OutPoint,
1347
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1348
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1349
                        broadcastHeight uint32,
1350
                        deadlineHeight fn.Option[int32]) error {
3✔
1351

3✔
1352
                        return s.utxoNursery.IncubateOutputs(
3✔
1353
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1354
                                broadcastHeight, deadlineHeight,
3✔
1355
                        )
3✔
1356
                },
3✔
1357
                PreimageDB:   s.witnessBeacon,
1358
                Notifier:     cc.ChainNotifier,
1359
                Mempool:      cc.MempoolNotifier,
1360
                Signer:       cc.Wallet.Cfg.Signer,
1361
                FeeEstimator: cc.FeeEstimator,
1362
                ChainIO:      cc.ChainIO,
1363
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1364
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1365
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1366
                        return nil
3✔
1367
                },
3✔
1368
                IsOurAddress: cc.Wallet.IsOurAddress,
1369
                ContractBreach: func(chanPoint wire.OutPoint,
1370
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1371

3✔
1372
                        // processACK will handle the BreachArbitrator ACKing
3✔
1373
                        // the event.
3✔
1374
                        finalErr := make(chan error, 1)
3✔
1375
                        processACK := func(brarErr error) {
6✔
1376
                                if brarErr != nil {
3✔
1377
                                        finalErr <- brarErr
×
1378
                                        return
×
1379
                                }
×
1380

1381
                                // If the BreachArbitrator successfully handled
1382
                                // the event, we can signal that the handoff
1383
                                // was successful.
1384
                                finalErr <- nil
3✔
1385
                        }
1386

1387
                        event := &contractcourt.ContractBreachEvent{
3✔
1388
                                ChanPoint:         chanPoint,
3✔
1389
                                ProcessACK:        processACK,
3✔
1390
                                BreachRetribution: breachRet,
3✔
1391
                        }
3✔
1392

3✔
1393
                        // Send the contract breach event to the
3✔
1394
                        // BreachArbitrator.
3✔
1395
                        select {
3✔
1396
                        case contractBreaches <- event:
3✔
1397
                        case <-s.quit:
×
1398
                                return ErrServerShuttingDown
×
1399
                        }
1400

1401
                        // We'll wait for a final error to be available from
1402
                        // the BreachArbitrator.
1403
                        select {
3✔
1404
                        case err := <-finalErr:
3✔
1405
                                return err
3✔
1406
                        case <-s.quit:
×
1407
                                return ErrServerShuttingDown
×
1408
                        }
1409
                },
1410
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1411
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1412
                },
3✔
1413
                Sweeper:                       s.sweeper,
1414
                Registry:                      s.invoices,
1415
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1416
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1417
                OnionProcessor:                s.sphinx,
1418
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1419
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1420
                Clock:                         clock.NewDefaultClock(),
1421
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1422
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1423
                HtlcNotifier:                  s.htlcNotifier,
1424
                Budget:                        *s.cfg.Sweeper.Budget,
1425

1426
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1427
                QueryIncomingCircuit: func(
1428
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1429

3✔
1430
                        // Get the circuit map.
3✔
1431
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1432

3✔
1433
                        // Lookup the outgoing circuit.
3✔
1434
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1435
                        if pc == nil {
5✔
1436
                                return nil
2✔
1437
                        }
2✔
1438

1439
                        return &pc.Incoming
3✔
1440
                },
1441
                AuxLeafStore: implCfg.AuxLeafStore,
1442
                AuxSigner:    implCfg.AuxSigner,
1443
                AuxResolver:  implCfg.AuxContractResolver,
1444
        }, dbs.ChanStateDB)
1445

1446
        // Select the configuration and funding parameters for Bitcoin.
1447
        chainCfg := cfg.Bitcoin
3✔
1448
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1449
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1450

3✔
1451
        var chanIDSeed [32]byte
3✔
1452
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1453
                return nil, err
×
1454
        }
×
1455

1456
        // Wrap the DeleteChannelEdges method so that the funding manager can
1457
        // use it without depending on several layers of indirection.
1458
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1459
                *models.ChannelEdgePolicy, error) {
6✔
1460

3✔
1461
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1462
                        scid.ToUint64(),
3✔
1463
                )
3✔
1464
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1465
                        // This is unlikely but there is a slim chance of this
×
1466
                        // being hit if lnd was killed via SIGKILL and the
×
1467
                        // funding manager was stepping through the delete
×
1468
                        // alias edge logic.
×
1469
                        return nil, nil
×
1470
                } else if err != nil {
3✔
1471
                        return nil, err
×
1472
                }
×
1473

1474
                // Grab our key to find our policy.
1475
                var ourKey [33]byte
3✔
1476
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1477

3✔
1478
                var ourPolicy *models.ChannelEdgePolicy
3✔
1479
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1480
                        ourPolicy = e1
3✔
1481
                } else {
6✔
1482
                        ourPolicy = e2
3✔
1483
                }
3✔
1484

1485
                if ourPolicy == nil {
3✔
1486
                        // Something is wrong, so return an error.
×
1487
                        return nil, fmt.Errorf("we don't have an edge")
×
1488
                }
×
1489

1490
                err = s.graphDB.DeleteChannelEdges(
3✔
1491
                        false, false, scid.ToUint64(),
3✔
1492
                )
3✔
1493
                return ourPolicy, err
3✔
1494
        }
1495

1496
        // For the reservationTimeout and the zombieSweeperInterval different
1497
        // values are set in case we are in a dev environment so enhance test
1498
        // capacilities.
1499
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1500
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1501

3✔
1502
        // Get the development config for funding manager. If we are not in
3✔
1503
        // development mode, this would be nil.
3✔
1504
        var devCfg *funding.DevConfig
3✔
1505
        if lncfg.IsDevBuild() {
6✔
1506
                devCfg = &funding.DevConfig{
3✔
1507
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1508
                }
3✔
1509

3✔
1510
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1511
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1512

3✔
1513
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1514
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1515
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1516
        }
3✔
1517

1518
        //nolint:ll
1519
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1520
                Dev:                devCfg,
3✔
1521
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1522
                IDKey:              nodeKeyDesc.PubKey,
3✔
1523
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1524
                Wallet:             cc.Wallet,
3✔
1525
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1526
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1527
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1528
                },
3✔
1529
                Notifier:     cc.ChainNotifier,
1530
                ChannelDB:    s.chanStateDB,
1531
                FeeEstimator: cc.FeeEstimator,
1532
                SignMessage:  cc.MsgSigner.SignMessage,
1533
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1534
                        error) {
3✔
1535

3✔
1536
                        return s.genNodeAnnouncement(nil)
3✔
1537
                },
3✔
1538
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1539
                NotifyWhenOnline:     s.NotifyWhenOnline,
1540
                TempChanIDSeed:       chanIDSeed,
1541
                FindChannel:          s.findChannel,
1542
                DefaultRoutingPolicy: cc.RoutingPolicy,
1543
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1544
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1545
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1546
                        // For large channels we increase the number
3✔
1547
                        // of confirmations we require for the
3✔
1548
                        // channel to be considered open. As it is
3✔
1549
                        // always the responder that gets to choose
3✔
1550
                        // value, the pushAmt is value being pushed
3✔
1551
                        // to us. This means we have more to lose
3✔
1552
                        // in the case this gets re-orged out, and
3✔
1553
                        // we will require more confirmations before
3✔
1554
                        // we consider it open.
3✔
1555

3✔
1556
                        // In case the user has explicitly specified
3✔
1557
                        // a default value for the number of
3✔
1558
                        // confirmations, we use it.
3✔
1559
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1560
                        if defaultConf != 0 {
6✔
1561
                                return defaultConf
3✔
1562
                        }
3✔
1563

1564
                        minConf := uint64(3)
×
1565
                        maxConf := uint64(6)
×
1566

×
1567
                        // If this is a wumbo channel, then we'll require the
×
1568
                        // max amount of confirmations.
×
1569
                        if chanAmt > MaxFundingAmount {
×
1570
                                return uint16(maxConf)
×
1571
                        }
×
1572

1573
                        // If not we return a value scaled linearly
1574
                        // between 3 and 6, depending on channel size.
1575
                        // TODO(halseth): Use 1 as minimum?
1576
                        maxChannelSize := uint64(
×
1577
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1578
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1579
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1580
                        if conf < minConf {
×
1581
                                conf = minConf
×
1582
                        }
×
1583
                        if conf > maxConf {
×
1584
                                conf = maxConf
×
1585
                        }
×
1586
                        return uint16(conf)
×
1587
                },
1588
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1589
                        // We scale the remote CSV delay (the time the
3✔
1590
                        // remote have to claim funds in case of a unilateral
3✔
1591
                        // close) linearly from minRemoteDelay blocks
3✔
1592
                        // for small channels, to maxRemoteDelay blocks
3✔
1593
                        // for channels of size MaxFundingAmount.
3✔
1594

3✔
1595
                        // In case the user has explicitly specified
3✔
1596
                        // a default value for the remote delay, we
3✔
1597
                        // use it.
3✔
1598
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1599
                        if defaultDelay > 0 {
6✔
1600
                                return defaultDelay
3✔
1601
                        }
3✔
1602

1603
                        // If this is a wumbo channel, then we'll require the
1604
                        // max value.
1605
                        if chanAmt > MaxFundingAmount {
×
1606
                                return maxRemoteDelay
×
1607
                        }
×
1608

1609
                        // If not we scale according to channel size.
1610
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1611
                                chanAmt / MaxFundingAmount)
×
1612
                        if delay < minRemoteDelay {
×
1613
                                delay = minRemoteDelay
×
1614
                        }
×
1615
                        if delay > maxRemoteDelay {
×
1616
                                delay = maxRemoteDelay
×
1617
                        }
×
1618
                        return delay
×
1619
                },
1620
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1621
                        peerKey *btcec.PublicKey) error {
3✔
1622

3✔
1623
                        // First, we'll mark this new peer as a persistent peer
3✔
1624
                        // for re-connection purposes. If the peer is not yet
3✔
1625
                        // tracked or the user hasn't requested it to be perm,
3✔
1626
                        // we'll set false to prevent the server from continuing
3✔
1627
                        // to connect to this peer even if the number of
3✔
1628
                        // channels with this peer is zero.
3✔
1629
                        s.mu.Lock()
3✔
1630
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1631
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1632
                                s.persistentPeers[pubStr] = false
3✔
1633
                        }
3✔
1634
                        s.mu.Unlock()
3✔
1635

3✔
1636
                        // With that taken care of, we'll send this channel to
3✔
1637
                        // the chain arb so it can react to on-chain events.
3✔
1638
                        return s.chainArb.WatchNewChannel(channel)
3✔
1639
                },
1640
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1641
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1642
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1643
                },
3✔
1644
                RequiredRemoteChanReserve: func(chanAmt,
1645
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1646

3✔
1647
                        // By default, we'll require the remote peer to maintain
3✔
1648
                        // at least 1% of the total channel capacity at all
3✔
1649
                        // times. If this value ends up dipping below the dust
3✔
1650
                        // limit, then we'll use the dust limit itself as the
3✔
1651
                        // reserve as required by BOLT #2.
3✔
1652
                        reserve := chanAmt / 100
3✔
1653
                        if reserve < dustLimit {
6✔
1654
                                reserve = dustLimit
3✔
1655
                        }
3✔
1656

1657
                        return reserve
3✔
1658
                },
1659
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1660
                        // By default, we'll allow the remote peer to fully
3✔
1661
                        // utilize the full bandwidth of the channel, minus our
3✔
1662
                        // required reserve.
3✔
1663
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1664
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1665
                },
3✔
1666
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1667
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1668
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1669
                        }
3✔
1670

1671
                        // By default, we'll permit them to utilize the full
1672
                        // channel bandwidth.
1673
                        return uint16(input.MaxHTLCNumber / 2)
×
1674
                },
1675
                ZombieSweeperInterval:         zombieSweeperInterval,
1676
                ReservationTimeout:            reservationTimeout,
1677
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1678
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1679
                MaxPendingChannels:            cfg.MaxPendingChannels,
1680
                RejectPush:                    cfg.RejectPush,
1681
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1682
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1683
                OpenChannelPredicate:          chanPredicate,
1684
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1685
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1686
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1687
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1688
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1689
                DeleteAliasEdge:      deleteAliasEdge,
1690
                AliasManager:         s.aliasMgr,
1691
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1692
                AuxFundingController: implCfg.AuxFundingController,
1693
                AuxSigner:            implCfg.AuxSigner,
1694
                AuxResolver:          implCfg.AuxContractResolver,
1695
        })
1696
        if err != nil {
3✔
1697
                return nil, err
×
1698
        }
×
1699

1700
        // Next, we'll assemble the sub-system that will maintain an on-disk
1701
        // static backup of the latest channel state.
1702
        chanNotifier := &channelNotifier{
3✔
1703
                chanNotifier: s.channelNotifier,
3✔
1704
                addrs:        s.addrSource,
3✔
1705
        }
3✔
1706
        backupFile := chanbackup.NewMultiFile(
3✔
1707
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1708
        )
3✔
1709
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1710
                s.chanStateDB, s.addrSource,
3✔
1711
        )
3✔
1712
        if err != nil {
3✔
1713
                return nil, err
×
1714
        }
×
1715
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1716
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1717
        )
3✔
1718
        if err != nil {
3✔
1719
                return nil, err
×
1720
        }
×
1721

1722
        // Assemble a peer notifier which will provide clients with subscriptions
1723
        // to peer online and offline events.
1724
        s.peerNotifier = peernotifier.New()
3✔
1725

3✔
1726
        // Create a channel event store which monitors all open channels.
3✔
1727
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1728
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1729
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1730
                },
3✔
1731
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1732
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1733
                },
3✔
1734
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1735
                Clock:           clock.NewDefaultClock(),
1736
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1737
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1738
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1739
        })
1740

1741
        if cfg.WtClient.Active {
6✔
1742
                policy := wtpolicy.DefaultPolicy()
3✔
1743
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1744

3✔
1745
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1746
                // protocol operations on sat/kw.
3✔
1747
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1748
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1749
                )
3✔
1750

3✔
1751
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1752

3✔
1753
                if err := policy.Validate(); err != nil {
3✔
1754
                        return nil, err
×
1755
                }
×
1756

1757
                // authDial is the wrapper around the btrontide.Dial for the
1758
                // watchtower.
1759
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1760
                        netAddr *lnwire.NetAddress,
3✔
1761
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1762

3✔
1763
                        return brontide.Dial(
3✔
1764
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1765
                        )
3✔
1766
                }
3✔
1767

1768
                // buildBreachRetribution is a call-back that can be used to
1769
                // query the BreachRetribution info and channel type given a
1770
                // channel ID and commitment height.
1771
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1772
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1773
                        channeldb.ChannelType, error) {
6✔
1774

3✔
1775
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1776
                                nil, chanID,
3✔
1777
                        )
3✔
1778
                        if err != nil {
3✔
1779
                                return nil, 0, err
×
1780
                        }
×
1781

1782
                        br, err := lnwallet.NewBreachRetribution(
3✔
1783
                                channel, commitHeight, 0, nil,
3✔
1784
                                implCfg.AuxLeafStore,
3✔
1785
                                implCfg.AuxContractResolver,
3✔
1786
                        )
3✔
1787
                        if err != nil {
3✔
1788
                                return nil, 0, err
×
1789
                        }
×
1790

1791
                        return br, channel.ChanType, nil
3✔
1792
                }
1793

1794
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1795

3✔
1796
                // Copy the policy for legacy channels and set the blob flag
3✔
1797
                // signalling support for anchor channels.
3✔
1798
                anchorPolicy := policy
3✔
1799
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1800

3✔
1801
                // Copy the policy for legacy channels and set the blob flag
3✔
1802
                // signalling support for taproot channels.
3✔
1803
                taprootPolicy := policy
3✔
1804
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1805
                        blob.FlagTaprootChannel,
3✔
1806
                )
3✔
1807

3✔
1808
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1809
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1810
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1811
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1812
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1813
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1814
                                error) {
6✔
1815

3✔
1816
                                return s.channelNotifier.
3✔
1817
                                        SubscribeChannelEvents()
3✔
1818
                        },
3✔
1819
                        Signer: cc.Wallet.Cfg.Signer,
1820
                        NewAddress: func() ([]byte, error) {
3✔
1821
                                addr, err := newSweepPkScriptGen(
3✔
1822
                                        cc.Wallet, netParams,
3✔
1823
                                )().Unpack()
3✔
1824
                                if err != nil {
3✔
1825
                                        return nil, err
×
1826
                                }
×
1827

1828
                                return addr.DeliveryAddress, nil
3✔
1829
                        },
1830
                        SecretKeyRing:      s.cc.KeyRing,
1831
                        Dial:               cfg.net.Dial,
1832
                        AuthDial:           authDial,
1833
                        DB:                 dbs.TowerClientDB,
1834
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1835
                        MinBackoff:         10 * time.Second,
1836
                        MaxBackoff:         5 * time.Minute,
1837
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1838
                }, policy, anchorPolicy, taprootPolicy)
1839
                if err != nil {
3✔
1840
                        return nil, err
×
1841
                }
×
1842
        }
1843

1844
        if len(cfg.ExternalHosts) != 0 {
3✔
1845
                advertisedIPs := make(map[string]struct{})
×
1846
                for _, addr := range s.currentNodeAnn.Addresses {
×
1847
                        advertisedIPs[addr.String()] = struct{}{}
×
1848
                }
×
1849

1850
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1851
                        Hosts:         cfg.ExternalHosts,
×
1852
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1853
                        LookupHost: func(host string) (net.Addr, error) {
×
1854
                                return lncfg.ParseAddressString(
×
1855
                                        host, strconv.Itoa(defaultPeerPort),
×
1856
                                        cfg.net.ResolveTCPAddr,
×
1857
                                )
×
1858
                        },
×
1859
                        AdvertisedIPs: advertisedIPs,
1860
                        AnnounceNewIPs: netann.IPAnnouncer(
1861
                                func(modifier ...netann.NodeAnnModifier) (
1862
                                        lnwire.NodeAnnouncement, error) {
×
1863

×
1864
                                        return s.genNodeAnnouncement(
×
1865
                                                nil, modifier...,
×
1866
                                        )
×
1867
                                }),
×
1868
                })
1869
        }
1870

1871
        // Create liveness monitor.
1872
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1873

3✔
1874
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1875
        for i, listenAddr := range listenAddrs {
6✔
1876
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1877
                // doesn't need to call the general lndResolveTCP function
3✔
1878
                // since we are resolving a local address.
3✔
1879

3✔
1880
                // RESOLVE: We are actually partially accepting inbound
3✔
1881
                // connection requests when we call NewListener.
3✔
1882
                listeners[i], err = brontide.NewListener(
3✔
1883
                        nodeKeyECDH, listenAddr.String(),
3✔
1884
                        s.peerAccessMan.checkIncomingConnBanScore,
3✔
1885
                )
3✔
1886
                if err != nil {
3✔
NEW
1887
                        return nil, err
×
NEW
1888
                }
×
1889
        }
1890

1891
        // Create the connection manager which will be responsible for
1892
        // maintaining persistent outbound connections and also accepting new
1893
        // incoming connections
1894
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1895
                Listeners:      listeners,
3✔
1896
                OnAccept:       s.InboundPeerConnected,
3✔
1897
                RetryDuration:  time.Second * 5,
3✔
1898
                TargetOutbound: 100,
3✔
1899
                Dial: noiseDial(
3✔
1900
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1901
                ),
3✔
1902
                OnConnection: s.OutboundPeerConnected,
3✔
1903
        })
3✔
1904
        if err != nil {
3✔
1905
                return nil, err
×
1906
        }
×
1907
        s.connMgr = cmgr
3✔
1908

3✔
1909
        // Finally, register the subsystems in blockbeat.
3✔
1910
        s.registerBlockConsumers()
3✔
1911

3✔
1912
        return s, nil
3✔
1913
}
1914

1915
// UpdateRoutingConfig is a callback function to update the routing config
1916
// values in the main cfg.
1917
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1918
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1919

3✔
1920
        switch c := cfg.Estimator.Config().(type) {
3✔
1921
        case routing.AprioriConfig:
3✔
1922
                routerCfg.ProbabilityEstimatorType =
3✔
1923
                        routing.AprioriEstimatorName
3✔
1924

3✔
1925
                targetCfg := routerCfg.AprioriConfig
3✔
1926
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1927
                targetCfg.Weight = c.AprioriWeight
3✔
1928
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1929
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1930

1931
        case routing.BimodalConfig:
3✔
1932
                routerCfg.ProbabilityEstimatorType =
3✔
1933
                        routing.BimodalEstimatorName
3✔
1934

3✔
1935
                targetCfg := routerCfg.BimodalConfig
3✔
1936
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1937
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1938
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1939
        }
1940

1941
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1942
}
1943

1944
// registerBlockConsumers registers the subsystems that consume block events.
1945
// By calling `RegisterQueue`, a list of subsystems are registered in the
1946
// blockbeat for block notifications. When a new block arrives, the subsystems
1947
// in the same queue are notified sequentially, and different queues are
1948
// notified concurrently.
1949
//
1950
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1951
// a new `RegisterQueue` call.
1952
func (s *server) registerBlockConsumers() {
3✔
1953
        // In this queue, when a new block arrives, it will be received and
3✔
1954
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
1955
        consumers := []chainio.Consumer{
3✔
1956
                s.chainArb,
3✔
1957
                s.sweeper,
3✔
1958
                s.txPublisher,
3✔
1959
        }
3✔
1960
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
1961
}
3✔
1962

1963
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1964
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1965
// may differ from what is on disk.
1966
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1967
        error) {
3✔
1968

3✔
1969
        data, err := u.DataToSign()
3✔
1970
        if err != nil {
3✔
1971
                return nil, err
×
1972
        }
×
1973

1974
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1975
}
1976

1977
// createLivenessMonitor creates a set of health checks using our configured
1978
// values and uses these checks to create a liveness monitor. Available
1979
// health checks,
1980
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1981
//   - diskCheck
1982
//   - tlsHealthCheck
1983
//   - torController, only created when tor is enabled.
1984
//
1985
// If a health check has been disabled by setting attempts to 0, our monitor
1986
// will not run it.
1987
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1988
        leaderElector cluster.LeaderElector) {
3✔
1989

3✔
1990
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1991
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1992
                srvrLog.Info("Disabling chain backend checks for " +
×
1993
                        "nochainbackend mode")
×
1994

×
1995
                chainBackendAttempts = 0
×
1996
        }
×
1997

1998
        chainHealthCheck := healthcheck.NewObservation(
3✔
1999
                "chain backend",
3✔
2000
                cc.HealthCheck,
3✔
2001
                cfg.HealthChecks.ChainCheck.Interval,
3✔
2002
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
2003
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
2004
                chainBackendAttempts,
3✔
2005
        )
3✔
2006

3✔
2007
        diskCheck := healthcheck.NewObservation(
3✔
2008
                "disk space",
3✔
2009
                func() error {
3✔
2010
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2011
                                cfg.LndDir,
×
2012
                        )
×
2013
                        if err != nil {
×
2014
                                return err
×
2015
                        }
×
2016

2017
                        // If we have more free space than we require,
2018
                        // we return a nil error.
2019
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2020
                                return nil
×
2021
                        }
×
2022

2023
                        return fmt.Errorf("require: %v free space, got: %v",
×
2024
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2025
                                free)
×
2026
                },
2027
                cfg.HealthChecks.DiskCheck.Interval,
2028
                cfg.HealthChecks.DiskCheck.Timeout,
2029
                cfg.HealthChecks.DiskCheck.Backoff,
2030
                cfg.HealthChecks.DiskCheck.Attempts,
2031
        )
2032

2033
        tlsHealthCheck := healthcheck.NewObservation(
3✔
2034
                "tls",
3✔
2035
                func() error {
3✔
2036
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2037
                                s.cc.KeyRing,
×
2038
                        )
×
2039
                        if err != nil {
×
2040
                                return err
×
2041
                        }
×
2042
                        if expired {
×
2043
                                return fmt.Errorf("TLS certificate is "+
×
2044
                                        "expired as of %v", expTime)
×
2045
                        }
×
2046

2047
                        // If the certificate is not outdated, no error needs
2048
                        // to be returned
2049
                        return nil
×
2050
                },
2051
                cfg.HealthChecks.TLSCheck.Interval,
2052
                cfg.HealthChecks.TLSCheck.Timeout,
2053
                cfg.HealthChecks.TLSCheck.Backoff,
2054
                cfg.HealthChecks.TLSCheck.Attempts,
2055
        )
2056

2057
        checks := []*healthcheck.Observation{
3✔
2058
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2059
        }
3✔
2060

3✔
2061
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2062
        if s.torController != nil {
3✔
2063
                torConnectionCheck := healthcheck.NewObservation(
×
2064
                        "tor connection",
×
2065
                        func() error {
×
2066
                                return healthcheck.CheckTorServiceStatus(
×
2067
                                        s.torController,
×
2068
                                        s.createNewHiddenService,
×
2069
                                )
×
2070
                        },
×
2071
                        cfg.HealthChecks.TorConnection.Interval,
2072
                        cfg.HealthChecks.TorConnection.Timeout,
2073
                        cfg.HealthChecks.TorConnection.Backoff,
2074
                        cfg.HealthChecks.TorConnection.Attempts,
2075
                )
2076
                checks = append(checks, torConnectionCheck)
×
2077
        }
2078

2079
        // If remote signing is enabled, add the healthcheck for the remote
2080
        // signing RPC interface.
2081
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2082
                // Because we have two cascading timeouts here, we need to add
3✔
2083
                // some slack to the "outer" one of them in case the "inner"
3✔
2084
                // returns exactly on time.
3✔
2085
                overhead := time.Millisecond * 10
3✔
2086

3✔
2087
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2088
                        "remote signer connection",
3✔
2089
                        rpcwallet.HealthCheck(
3✔
2090
                                s.cfg.RemoteSigner,
3✔
2091

3✔
2092
                                // For the health check we might to be even
3✔
2093
                                // stricter than the initial/normal connect, so
3✔
2094
                                // we use the health check timeout here.
3✔
2095
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2096
                        ),
3✔
2097
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2098
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2099
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2100
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2101
                )
3✔
2102
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2103
        }
3✔
2104

2105
        // If we have a leader elector, we add a health check to ensure we are
2106
        // still the leader. During normal operation, we should always be the
2107
        // leader, but there are circumstances where this may change, such as
2108
        // when we lose network connectivity for long enough expiring out lease.
2109
        if leaderElector != nil {
3✔
2110
                leaderCheck := healthcheck.NewObservation(
×
2111
                        "leader status",
×
2112
                        func() error {
×
2113
                                // Check if we are still the leader. Note that
×
2114
                                // we don't need to use a timeout context here
×
2115
                                // as the healthcheck observer will handle the
×
2116
                                // timeout case for us.
×
2117
                                timeoutCtx, cancel := context.WithTimeout(
×
2118
                                        context.Background(),
×
2119
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2120
                                )
×
2121
                                defer cancel()
×
2122

×
2123
                                leader, err := leaderElector.IsLeader(
×
2124
                                        timeoutCtx,
×
2125
                                )
×
2126
                                if err != nil {
×
2127
                                        return fmt.Errorf("unable to check if "+
×
2128
                                                "still leader: %v", err)
×
2129
                                }
×
2130

2131
                                if !leader {
×
2132
                                        srvrLog.Debug("Not the current leader")
×
2133
                                        return fmt.Errorf("not the current " +
×
2134
                                                "leader")
×
2135
                                }
×
2136

2137
                                return nil
×
2138
                        },
2139
                        cfg.HealthChecks.LeaderCheck.Interval,
2140
                        cfg.HealthChecks.LeaderCheck.Timeout,
2141
                        cfg.HealthChecks.LeaderCheck.Backoff,
2142
                        cfg.HealthChecks.LeaderCheck.Attempts,
2143
                )
2144

2145
                checks = append(checks, leaderCheck)
×
2146
        }
2147

2148
        // If we have not disabled all of our health checks, we create a
2149
        // liveness monitor with our configured checks.
2150
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2151
                &healthcheck.Config{
3✔
2152
                        Checks:   checks,
3✔
2153
                        Shutdown: srvrLog.Criticalf,
3✔
2154
                },
3✔
2155
        )
3✔
2156
}
2157

2158
// Started returns true if the server has been started, and false otherwise.
2159
// NOTE: This function is safe for concurrent access.
2160
func (s *server) Started() bool {
3✔
2161
        return atomic.LoadInt32(&s.active) != 0
3✔
2162
}
3✔
2163

2164
// cleaner is used to aggregate "cleanup" functions during an operation that
2165
// starts several subsystems. In case one of the subsystem fails to start
2166
// and a proper resource cleanup is required, the "run" method achieves this
2167
// by running all these added "cleanup" functions.
2168
type cleaner []func() error
2169

2170
// add is used to add a cleanup function to be called when
2171
// the run function is executed.
2172
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2173
        return append(c, cleanup)
3✔
2174
}
3✔
2175

2176
// run is used to run all the previousely added cleanup functions.
2177
func (c cleaner) run() {
×
2178
        for i := len(c) - 1; i >= 0; i-- {
×
2179
                if err := c[i](); err != nil {
×
2180
                        srvrLog.Infof("Cleanup failed: %v", err)
×
2181
                }
×
2182
        }
2183
}
2184

2185
// startLowLevelServices starts the low-level services of the server. These
2186
// services must be started successfully before running the main server. The
2187
// services are,
2188
// 1. the chain notifier.
2189
//
2190
// TODO(yy): identify and add more low-level services here.
2191
func (s *server) startLowLevelServices() error {
3✔
2192
        var startErr error
3✔
2193

3✔
2194
        cleanup := cleaner{}
3✔
2195

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

2201
        if startErr != nil {
3✔
2202
                cleanup.run()
×
2203
        }
×
2204

2205
        return startErr
3✔
2206
}
2207

2208
// Start starts the main daemon server, all requested listeners, and any helper
2209
// goroutines.
2210
// NOTE: This function is safe for concurrent access.
2211
//
2212
//nolint:funlen
2213
func (s *server) Start() error {
3✔
2214
        // Get the current blockbeat.
3✔
2215
        beat, err := s.getStartingBeat()
3✔
2216
        if err != nil {
3✔
2217
                return err
×
2218
        }
×
2219

2220
        var startErr error
3✔
2221

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

3✔
2227
        s.start.Do(func() {
6✔
2228
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2229
                if err := s.customMessageServer.Start(); err != nil {
3✔
2230
                        startErr = err
×
2231
                        return
×
2232
                }
×
2233

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

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

2250
                // Start the notification server. This is used so channel
2251
                // management goroutines can be notified when a funding
2252
                // transaction reaches a sufficient number of confirmations, or
2253
                // when the input for the funding transaction is spent in an
2254
                // attempt at an uncooperative close by the counterparty.
2255
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2256
                if err := s.sigPool.Start(); err != nil {
3✔
2257
                        startErr = err
×
2258
                        return
×
2259
                }
×
2260

2261
                cleanup = cleanup.add(s.writePool.Stop)
3✔
2262
                if err := s.writePool.Start(); err != nil {
3✔
2263
                        startErr = err
×
2264
                        return
×
2265
                }
×
2266

2267
                cleanup = cleanup.add(s.readPool.Stop)
3✔
2268
                if err := s.readPool.Start(); err != nil {
3✔
2269
                        startErr = err
×
2270
                        return
×
2271
                }
×
2272

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

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

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

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

2299
                if s.towerClientMgr != nil {
6✔
2300
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
3✔
2301
                        if err := s.towerClientMgr.Start(); err != nil {
3✔
2302
                                startErr = err
×
2303
                                return
×
2304
                        }
×
2305
                }
2306

2307
                cleanup = cleanup.add(s.txPublisher.Stop)
3✔
2308
                if err := s.txPublisher.Start(beat); err != nil {
3✔
2309
                        startErr = err
×
2310
                        return
×
2311
                }
×
2312

2313
                cleanup = cleanup.add(s.sweeper.Stop)
3✔
2314
                if err := s.sweeper.Start(beat); err != nil {
3✔
2315
                        startErr = err
×
2316
                        return
×
2317
                }
×
2318

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

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

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

2337
                // htlcSwitch must be started before chainArb since the latter
2338
                // relies on htlcSwitch to deliver resolution message upon
2339
                // start.
2340
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2341
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2342
                        startErr = err
×
2343
                        return
×
2344
                }
×
2345

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

2352
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
3✔
2353
                if err := s.invoiceHtlcModifier.Start(); err != nil {
3✔
2354
                        startErr = err
×
2355
                        return
×
2356
                }
×
2357

2358
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
2359
                if err := s.chainArb.Start(beat); err != nil {
3✔
2360
                        startErr = err
×
2361
                        return
×
2362
                }
×
2363

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

2370
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2371
                if err := s.chanRouter.Start(); err != nil {
3✔
2372
                        startErr = err
×
2373
                        return
×
2374
                }
×
2375
                // The authGossiper depends on the chanRouter and therefore
2376
                // should be started after it.
2377
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2378
                if err := s.authGossiper.Start(); err != nil {
3✔
2379
                        startErr = err
×
2380
                        return
×
2381
                }
×
2382

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

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

2395
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
2396
                if err := s.chanStatusMgr.Start(); err != nil {
3✔
2397
                        startErr = err
×
2398
                        return
×
2399
                }
×
2400

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

2407
                cleanup.add(func() error {
3✔
2408
                        s.missionController.StopStoreTickers()
×
2409
                        return nil
×
2410
                })
×
2411
                s.missionController.RunStoreTickers()
3✔
2412

3✔
2413
                // Before we start the connMgr, we'll check to see if we have
3✔
2414
                // any backups to recover. We do this now as we want to ensure
3✔
2415
                // that have all the information we need to handle channel
3✔
2416
                // recovery _before_ we even accept connections from any peers.
3✔
2417
                chanRestorer := &chanDBRestorer{
3✔
2418
                        db:         s.chanStateDB,
3✔
2419
                        secretKeys: s.cc.KeyRing,
3✔
2420
                        chainArb:   s.chainArb,
3✔
2421
                }
3✔
2422
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2423
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2424
                                s.chansToRestore.PackedSingleChanBackups,
×
2425
                                s.cc.KeyRing, chanRestorer, s,
×
2426
                        )
×
2427
                        if err != nil {
×
2428
                                startErr = fmt.Errorf("unable to unpack single "+
×
2429
                                        "backups: %v", err)
×
2430
                                return
×
2431
                        }
×
2432
                }
2433
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2434
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2435
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2436
                                s.cc.KeyRing, chanRestorer, s,
3✔
2437
                        )
3✔
2438
                        if err != nil {
3✔
2439
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2440
                                        "backup: %v", err)
×
2441
                                return
×
2442
                        }
×
2443
                }
2444

2445
                // chanSubSwapper must be started after the `channelNotifier`
2446
                // because it depends on channel events as a synchronization
2447
                // point.
2448
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2449
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2450
                        startErr = err
×
2451
                        return
×
2452
                }
×
2453

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

2462
                if s.natTraversal != nil {
3✔
2463
                        s.wg.Add(1)
×
2464
                        go s.watchExternalIP()
×
2465
                }
×
2466

2467
                // Start connmgr last to prevent connections before init.
2468
                cleanup = cleanup.add(func() error {
3✔
2469
                        s.connMgr.Stop()
×
2470
                        return nil
×
2471
                })
×
2472

2473
                // RESOLVE: s.connMgr.Start() is called here, but
2474
                // brontide.NewListener() is called in newServer. This means
2475
                // that we are actually listening and partially accepting
2476
                // inbound connections even before the connMgr starts.
2477
                s.connMgr.Start()
3✔
2478

3✔
2479
                // If peers are specified as a config option, we'll add those
3✔
2480
                // peers first.
3✔
2481
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2482
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2483
                                peerAddrCfg,
3✔
2484
                        )
3✔
2485
                        if err != nil {
3✔
2486
                                startErr = fmt.Errorf("unable to parse peer "+
×
2487
                                        "pubkey from config: %v", err)
×
2488
                                return
×
2489
                        }
×
2490
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2491
                        if err != nil {
3✔
2492
                                startErr = fmt.Errorf("unable to parse peer "+
×
2493
                                        "address provided as a config option: "+
×
2494
                                        "%v", err)
×
2495
                                return
×
2496
                        }
×
2497

2498
                        peerAddr := &lnwire.NetAddress{
3✔
2499
                                IdentityKey: parsedPubkey,
3✔
2500
                                Address:     addr,
3✔
2501
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2502
                        }
3✔
2503

3✔
2504
                        err = s.ConnectToPeer(
3✔
2505
                                peerAddr, true,
3✔
2506
                                s.cfg.ConnectionTimeout,
3✔
2507
                        )
3✔
2508
                        if err != nil {
3✔
2509
                                startErr = fmt.Errorf("unable to connect to "+
×
2510
                                        "peer address provided as a config "+
×
2511
                                        "option: %v", err)
×
2512
                                return
×
2513
                        }
×
2514
                }
2515

2516
                // Subscribe to NodeAnnouncements that advertise new addresses
2517
                // our persistent peers.
2518
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2519
                        startErr = err
×
2520
                        return
×
2521
                }
×
2522

2523
                // With all the relevant sub-systems started, we'll now attempt
2524
                // to establish persistent connections to our direct channel
2525
                // collaborators within the network. Before doing so however,
2526
                // we'll prune our set of link nodes found within the database
2527
                // to ensure we don't reconnect to any nodes we no longer have
2528
                // open channels with.
2529
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2530
                        startErr = err
×
2531
                        return
×
2532
                }
×
2533
                if err := s.establishPersistentConnections(); err != nil {
3✔
2534
                        startErr = err
×
2535
                        return
×
2536
                }
×
2537

2538
                // setSeedList is a helper function that turns multiple DNS seed
2539
                // server tuples from the command line or config file into the
2540
                // data structure we need and does a basic formal sanity check
2541
                // in the process.
2542
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2543
                        if len(tuples) == 0 {
×
2544
                                return
×
2545
                        }
×
2546

2547
                        result := make([][2]string, len(tuples))
×
2548
                        for idx, tuple := range tuples {
×
2549
                                tuple = strings.TrimSpace(tuple)
×
2550
                                if len(tuple) == 0 {
×
2551
                                        return
×
2552
                                }
×
2553

2554
                                servers := strings.Split(tuple, ",")
×
2555
                                if len(servers) > 2 || len(servers) == 0 {
×
2556
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2557
                                                "seed tuple: %v", servers)
×
2558
                                        return
×
2559
                                }
×
2560

2561
                                copy(result[idx][:], servers)
×
2562
                        }
2563

2564
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2565
                }
2566

2567
                // Let users overwrite the DNS seed nodes. We only allow them
2568
                // for bitcoin mainnet/testnet/signet.
2569
                if s.cfg.Bitcoin.MainNet {
3✔
2570
                        setSeedList(
×
2571
                                s.cfg.Bitcoin.DNSSeeds,
×
2572
                                chainreg.BitcoinMainnetGenesis,
×
2573
                        )
×
2574
                }
×
2575
                if s.cfg.Bitcoin.TestNet3 {
3✔
2576
                        setSeedList(
×
2577
                                s.cfg.Bitcoin.DNSSeeds,
×
2578
                                chainreg.BitcoinTestnetGenesis,
×
2579
                        )
×
2580
                }
×
2581
                if s.cfg.Bitcoin.SigNet {
3✔
2582
                        setSeedList(
×
2583
                                s.cfg.Bitcoin.DNSSeeds,
×
2584
                                chainreg.BitcoinSignetGenesis,
×
2585
                        )
×
2586
                }
×
2587

2588
                // If network bootstrapping hasn't been disabled, then we'll
2589
                // configure the set of active bootstrappers, and launch a
2590
                // dedicated goroutine to maintain a set of persistent
2591
                // connections.
2592
                if shouldPeerBootstrap(s.cfg) {
3✔
2593
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2594
                        if err != nil {
×
2595
                                startErr = err
×
2596
                                return
×
2597
                        }
×
2598

2599
                        s.wg.Add(1)
×
2600
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2601
                } else {
3✔
2602
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2603
                }
3✔
2604

2605
                // Start the blockbeat after all other subsystems have been
2606
                // started so they are ready to receive new blocks.
2607
                cleanup = cleanup.add(func() error {
3✔
2608
                        s.blockbeatDispatcher.Stop()
×
2609
                        return nil
×
2610
                })
×
2611
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2612
                        startErr = err
×
2613
                        return
×
2614
                }
×
2615

2616
                // Set the active flag now that we've completed the full
2617
                // startup.
2618
                atomic.StoreInt32(&s.active, 1)
3✔
2619
        })
2620

2621
        if startErr != nil {
3✔
2622
                cleanup.run()
×
2623
        }
×
2624
        return startErr
3✔
2625
}
2626

2627
// Stop gracefully shutsdown the main daemon server. This function will signal
2628
// any active goroutines, or helper objects to exit, then blocks until they've
2629
// all successfully exited. Additionally, any/all listeners are closed.
2630
// NOTE: This function is safe for concurrent access.
2631
func (s *server) Stop() error {
3✔
2632
        s.stop.Do(func() {
6✔
2633
                atomic.StoreInt32(&s.stopping, 1)
3✔
2634

3✔
2635
                close(s.quit)
3✔
2636

3✔
2637
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2638
                s.connMgr.Stop()
3✔
2639

3✔
2640
                // Stop dispatching blocks to other systems immediately.
3✔
2641
                s.blockbeatDispatcher.Stop()
3✔
2642

3✔
2643
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2644
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2645
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2646
                }
×
2647
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2648
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2649
                }
×
2650
                if err := s.sphinx.Stop(); err != nil {
3✔
2651
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2652
                }
×
2653
                if err := s.invoices.Stop(); err != nil {
3✔
2654
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2655
                }
×
2656
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2657
                        srvrLog.Warnf("failed to stop interceptable "+
×
2658
                                "switch: %v", err)
×
2659
                }
×
2660
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2661
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2662
                                "modifier: %v", err)
×
2663
                }
×
2664
                if err := s.chanRouter.Stop(); err != nil {
3✔
2665
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2666
                }
×
2667
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2668
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2669
                }
×
2670
                if err := s.chainArb.Stop(); err != nil {
3✔
2671
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2672
                }
×
2673
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2674
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2675
                }
×
2676
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2677
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2678
                                err)
×
2679
                }
×
2680
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2681
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2682
                }
×
2683
                if err := s.authGossiper.Stop(); err != nil {
3✔
2684
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2685
                }
×
2686
                if err := s.sweeper.Stop(); err != nil {
3✔
2687
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2688
                }
×
2689
                if err := s.txPublisher.Stop(); err != nil {
3✔
2690
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2691
                }
×
2692
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2693
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2694
                }
×
2695
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2696
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2697
                }
×
2698
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2699
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2700
                }
×
2701

2702
                // Update channel.backup file. Make sure to do it before
2703
                // stopping chanSubSwapper.
2704
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2705
                        s.chanStateDB, s.addrSource,
3✔
2706
                )
3✔
2707
                if err != nil {
3✔
2708
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2709
                                err)
×
2710
                } else {
3✔
2711
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2712
                        if err != nil {
6✔
2713
                                srvrLog.Warnf("Manual update of channel "+
3✔
2714
                                        "backup failed: %v", err)
3✔
2715
                        }
3✔
2716
                }
2717

2718
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2719
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2720
                }
×
2721
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2722
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2723
                }
×
2724
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2725
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2726
                                err)
×
2727
                }
×
2728
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2729
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2730
                                err)
×
2731
                }
×
2732
                s.missionController.StopStoreTickers()
3✔
2733

3✔
2734
                // Disconnect from each active peers to ensure that
3✔
2735
                // peerTerminationWatchers signal completion to each peer.
3✔
2736
                for _, peer := range s.Peers() {
6✔
2737
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2738
                        if err != nil {
3✔
2739
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2740
                                        "received error: %v", peer.IdentityKey(),
×
2741
                                        err,
×
2742
                                )
×
2743
                        }
×
2744
                }
2745

2746
                // Now that all connections have been torn down, stop the tower
2747
                // client which will reliably flush all queued states to the
2748
                // tower. If this is halted for any reason, the force quit timer
2749
                // will kick in and abort to allow this method to return.
2750
                if s.towerClientMgr != nil {
6✔
2751
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2752
                                srvrLog.Warnf("Unable to shut down tower "+
×
2753
                                        "client manager: %v", err)
×
2754
                        }
×
2755
                }
2756

2757
                if s.hostAnn != nil {
3✔
2758
                        if err := s.hostAnn.Stop(); err != nil {
×
2759
                                srvrLog.Warnf("unable to shut down host "+
×
2760
                                        "annoucner: %v", err)
×
2761
                        }
×
2762
                }
2763

2764
                if s.livenessMonitor != nil {
6✔
2765
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2766
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2767
                                        "monitor: %v", err)
×
2768
                        }
×
2769
                }
2770

2771
                // Wait for all lingering goroutines to quit.
2772
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2773
                s.wg.Wait()
3✔
2774

3✔
2775
                srvrLog.Debug("Stopping buffer pools...")
3✔
2776
                s.sigPool.Stop()
3✔
2777
                s.writePool.Stop()
3✔
2778
                s.readPool.Stop()
3✔
2779
        })
2780

2781
        return nil
3✔
2782
}
2783

2784
// Stopped returns true if the server has been instructed to shutdown.
2785
// NOTE: This function is safe for concurrent access.
2786
func (s *server) Stopped() bool {
3✔
2787
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2788
}
3✔
2789

2790
// configurePortForwarding attempts to set up port forwarding for the different
2791
// ports that the server will be listening on.
2792
//
2793
// NOTE: This should only be used when using some kind of NAT traversal to
2794
// automatically set up forwarding rules.
2795
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2796
        ip, err := s.natTraversal.ExternalIP()
×
2797
        if err != nil {
×
2798
                return nil, err
×
2799
        }
×
2800
        s.lastDetectedIP = ip
×
2801

×
2802
        externalIPs := make([]string, 0, len(ports))
×
2803
        for _, port := range ports {
×
2804
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2805
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2806
                        continue
×
2807
                }
2808

2809
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2810
                externalIPs = append(externalIPs, hostIP)
×
2811
        }
2812

2813
        return externalIPs, nil
×
2814
}
2815

2816
// removePortForwarding attempts to clear the forwarding rules for the different
2817
// ports the server is currently listening on.
2818
//
2819
// NOTE: This should only be used when using some kind of NAT traversal to
2820
// automatically set up forwarding rules.
2821
func (s *server) removePortForwarding() {
×
2822
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2823
        for _, port := range forwardedPorts {
×
2824
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2825
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2826
                                "port %d: %v", port, err)
×
2827
                }
×
2828
        }
2829
}
2830

2831
// watchExternalIP continuously checks for an updated external IP address every
2832
// 15 minutes. Once a new IP address has been detected, it will automatically
2833
// handle port forwarding rules and send updated node announcements to the
2834
// currently connected peers.
2835
//
2836
// NOTE: This MUST be run as a goroutine.
2837
func (s *server) watchExternalIP() {
×
2838
        defer s.wg.Done()
×
2839

×
2840
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2841
        // up by the server.
×
2842
        defer s.removePortForwarding()
×
2843

×
2844
        // Keep track of the external IPs set by the user to avoid replacing
×
2845
        // them when detecting a new IP.
×
2846
        ipsSetByUser := make(map[string]struct{})
×
2847
        for _, ip := range s.cfg.ExternalIPs {
×
2848
                ipsSetByUser[ip.String()] = struct{}{}
×
2849
        }
×
2850

2851
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2852

×
2853
        ticker := time.NewTicker(15 * time.Minute)
×
2854
        defer ticker.Stop()
×
2855
out:
×
2856
        for {
×
2857
                select {
×
2858
                case <-ticker.C:
×
2859
                        // We'll start off by making sure a new IP address has
×
2860
                        // been detected.
×
2861
                        ip, err := s.natTraversal.ExternalIP()
×
2862
                        if err != nil {
×
2863
                                srvrLog.Debugf("Unable to retrieve the "+
×
2864
                                        "external IP address: %v", err)
×
2865
                                continue
×
2866
                        }
2867

2868
                        // Periodically renew the NAT port forwarding.
2869
                        for _, port := range forwardedPorts {
×
2870
                                err := s.natTraversal.AddPortMapping(port)
×
2871
                                if err != nil {
×
2872
                                        srvrLog.Warnf("Unable to automatically "+
×
2873
                                                "re-create port forwarding using %s: %v",
×
2874
                                                s.natTraversal.Name(), err)
×
2875
                                } else {
×
2876
                                        srvrLog.Debugf("Automatically re-created "+
×
2877
                                                "forwarding for port %d using %s to "+
×
2878
                                                "advertise external IP",
×
2879
                                                port, s.natTraversal.Name())
×
2880
                                }
×
2881
                        }
2882

2883
                        if ip.Equal(s.lastDetectedIP) {
×
2884
                                continue
×
2885
                        }
2886

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

×
2889
                        // Next, we'll craft the new addresses that will be
×
2890
                        // included in the new node announcement and advertised
×
2891
                        // to the network. Each address will consist of the new
×
2892
                        // IP detected and one of the currently advertised
×
2893
                        // ports.
×
2894
                        var newAddrs []net.Addr
×
2895
                        for _, port := range forwardedPorts {
×
2896
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2897
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2898
                                if err != nil {
×
2899
                                        srvrLog.Debugf("Unable to resolve "+
×
2900
                                                "host %v: %v", addr, err)
×
2901
                                        continue
×
2902
                                }
2903

2904
                                newAddrs = append(newAddrs, addr)
×
2905
                        }
2906

2907
                        // Skip the update if we weren't able to resolve any of
2908
                        // the new addresses.
2909
                        if len(newAddrs) == 0 {
×
2910
                                srvrLog.Debug("Skipping node announcement " +
×
2911
                                        "update due to not being able to " +
×
2912
                                        "resolve any new addresses")
×
2913
                                continue
×
2914
                        }
2915

2916
                        // Now, we'll need to update the addresses in our node's
2917
                        // announcement in order to propagate the update
2918
                        // throughout the network. We'll only include addresses
2919
                        // that have a different IP from the previous one, as
2920
                        // the previous IP is no longer valid.
2921
                        currentNodeAnn := s.getNodeAnnouncement()
×
2922

×
2923
                        for _, addr := range currentNodeAnn.Addresses {
×
2924
                                host, _, err := net.SplitHostPort(addr.String())
×
2925
                                if err != nil {
×
2926
                                        srvrLog.Debugf("Unable to determine "+
×
2927
                                                "host from address %v: %v",
×
2928
                                                addr, err)
×
2929
                                        continue
×
2930
                                }
2931

2932
                                // We'll also make sure to include external IPs
2933
                                // set manually by the user.
2934
                                _, setByUser := ipsSetByUser[addr.String()]
×
2935
                                if setByUser || host != s.lastDetectedIP.String() {
×
2936
                                        newAddrs = append(newAddrs, addr)
×
2937
                                }
×
2938
                        }
2939

2940
                        // Then, we'll generate a new timestamped node
2941
                        // announcement with the updated addresses and broadcast
2942
                        // it to our peers.
2943
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2944
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2945
                        )
×
2946
                        if err != nil {
×
2947
                                srvrLog.Debugf("Unable to generate new node "+
×
2948
                                        "announcement: %v", err)
×
2949
                                continue
×
2950
                        }
2951

2952
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2953
                        if err != nil {
×
2954
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2955
                                        "announcement to peers: %v", err)
×
2956
                                continue
×
2957
                        }
2958

2959
                        // Finally, update the last IP seen to the current one.
2960
                        s.lastDetectedIP = ip
×
2961
                case <-s.quit:
×
2962
                        break out
×
2963
                }
2964
        }
2965
}
2966

2967
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2968
// based on the server, and currently active bootstrap mechanisms as defined
2969
// within the current configuration.
2970
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2971
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2972

×
2973
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2974

×
2975
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2976
        // this can be used by default if we've already partially seeded the
×
2977
        // network.
×
2978
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2979
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2980
        if err != nil {
×
2981
                return nil, err
×
2982
        }
×
2983
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2984

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

×
2990
                // If we have a set of DNS seeds for this chain, then we'll add
×
2991
                // it as an additional bootstrapping source.
×
2992
                if ok {
×
2993
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2994
                                "seeds: %v", dnsSeeds)
×
2995

×
2996
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2997
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2998
                        )
×
2999
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3000
                }
×
3001
        }
3002

3003
        return bootStrappers, nil
×
3004
}
3005

3006
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3007
// needs to ignore, which is made of three parts,
3008
//   - the node itself needs to be skipped as it doesn't make sense to connect
3009
//     to itself.
3010
//   - the peers that already have connections with, as in s.peersByPub.
3011
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3012
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
3013
        s.mu.RLock()
×
3014
        defer s.mu.RUnlock()
×
3015

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

×
3018
        // We should ignore ourselves from bootstrapping.
×
3019
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
3020
        ignore[selfKey] = struct{}{}
×
3021

×
3022
        // Ignore all connected peers.
×
3023
        for _, peer := range s.peersByPub {
×
3024
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3025
                ignore[nID] = struct{}{}
×
3026
        }
×
3027

3028
        // Ignore all persistent peers as they have a dedicated reconnecting
3029
        // process.
3030
        for pubKeyStr := range s.persistentPeers {
×
3031
                var nID autopilot.NodeID
×
3032
                copy(nID[:], []byte(pubKeyStr))
×
3033
                ignore[nID] = struct{}{}
×
3034
        }
×
3035

3036
        return ignore
×
3037
}
3038

3039
// peerBootstrapper is a goroutine which is tasked with attempting to establish
3040
// and maintain a target minimum number of outbound connections. With this
3041
// invariant, we ensure that our node is connected to a diverse set of peers
3042
// and that nodes newly joining the network receive an up to date network view
3043
// as soon as possible.
3044
func (s *server) peerBootstrapper(numTargetPeers uint32,
3045
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3046

×
3047
        defer s.wg.Done()
×
3048

×
3049
        // Before we continue, init the ignore peers map.
×
3050
        ignoreList := s.createBootstrapIgnorePeers()
×
3051

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

×
3056
        // Once done, we'll attempt to maintain our target minimum number of
×
3057
        // peers.
×
3058
        //
×
3059
        // We'll use a 15 second backoff, and double the time every time an
×
3060
        // epoch fails up to a ceiling.
×
3061
        backOff := time.Second * 15
×
3062

×
3063
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
3064
        // see if we've reached our minimum number of peers.
×
3065
        sampleTicker := time.NewTicker(backOff)
×
3066
        defer sampleTicker.Stop()
×
3067

×
3068
        // We'll use the number of attempts and errors to determine if we need
×
3069
        // to increase the time between discovery epochs.
×
3070
        var epochErrors uint32 // To be used atomically.
×
3071
        var epochAttempts uint32
×
3072

×
3073
        for {
×
3074
                select {
×
3075
                // The ticker has just woken us up, so we'll need to check if
3076
                // we need to attempt to connect our to any more peers.
3077
                case <-sampleTicker.C:
×
3078
                        // Obtain the current number of peers, so we can gauge
×
3079
                        // if we need to sample more peers or not.
×
3080
                        s.mu.RLock()
×
3081
                        numActivePeers := uint32(len(s.peersByPub))
×
3082
                        s.mu.RUnlock()
×
3083

×
3084
                        // If we have enough peers, then we can loop back
×
3085
                        // around to the next round as we're done here.
×
3086
                        if numActivePeers >= numTargetPeers {
×
3087
                                continue
×
3088
                        }
3089

3090
                        // If all of our attempts failed during this last back
3091
                        // off period, then will increase our backoff to 5
3092
                        // minute ceiling to avoid an excessive number of
3093
                        // queries
3094
                        //
3095
                        // TODO(roasbeef): add reverse policy too?
3096

3097
                        if epochAttempts > 0 &&
×
3098
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3099

×
3100
                                sampleTicker.Stop()
×
3101

×
3102
                                backOff *= 2
×
3103
                                if backOff > bootstrapBackOffCeiling {
×
3104
                                        backOff = bootstrapBackOffCeiling
×
3105
                                }
×
3106

3107
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3108
                                        "%v", backOff)
×
3109
                                sampleTicker = time.NewTicker(backOff)
×
3110
                                continue
×
3111
                        }
3112

3113
                        atomic.StoreUint32(&epochErrors, 0)
×
3114
                        epochAttempts = 0
×
3115

×
3116
                        // Since we know need more peers, we'll compute the
×
3117
                        // exact number we need to reach our threshold.
×
3118
                        numNeeded := numTargetPeers - numActivePeers
×
3119

×
3120
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3121
                                "peers", numNeeded)
×
3122

×
3123
                        // With the number of peers we need calculated, we'll
×
3124
                        // query the network bootstrappers to sample a set of
×
3125
                        // random addrs for us.
×
3126
                        //
×
3127
                        // Before we continue, get a copy of the ignore peers
×
3128
                        // map.
×
3129
                        ignoreList = s.createBootstrapIgnorePeers()
×
3130

×
3131
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3132
                                ignoreList, numNeeded*2, bootstrappers...,
×
3133
                        )
×
3134
                        if err != nil {
×
3135
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3136
                                        "peers: %v", err)
×
3137
                                continue
×
3138
                        }
3139

3140
                        // Finally, we'll launch a new goroutine for each
3141
                        // prospective peer candidates.
3142
                        for _, addr := range peerAddrs {
×
3143
                                epochAttempts++
×
3144

×
3145
                                go func(a *lnwire.NetAddress) {
×
3146
                                        // TODO(roasbeef): can do AS, subnet,
×
3147
                                        // country diversity, etc
×
3148
                                        errChan := make(chan error, 1)
×
3149
                                        s.connectToPeer(
×
3150
                                                a, errChan,
×
3151
                                                s.cfg.ConnectionTimeout,
×
3152
                                        )
×
3153
                                        select {
×
3154
                                        case err := <-errChan:
×
3155
                                                if err == nil {
×
3156
                                                        return
×
3157
                                                }
×
3158

3159
                                                srvrLog.Errorf("Unable to "+
×
3160
                                                        "connect to %v: %v",
×
3161
                                                        a, err)
×
3162
                                                atomic.AddUint32(&epochErrors, 1)
×
3163
                                        case <-s.quit:
×
3164
                                        }
3165
                                }(addr)
3166
                        }
3167
                case <-s.quit:
×
3168
                        return
×
3169
                }
3170
        }
3171
}
3172

3173
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3174
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3175
// query back off each time we encounter a failure.
3176
const bootstrapBackOffCeiling = time.Minute * 5
3177

3178
// initialPeerBootstrap attempts to continuously connect to peers on startup
3179
// until the target number of peers has been reached. This ensures that nodes
3180
// receive an up to date network view as soon as possible.
3181
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
3182
        numTargetPeers uint32,
3183
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3184

×
3185
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3186
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3187

×
3188
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3189
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3190
        var delaySignal <-chan time.Time
×
3191
        delayTime := time.Second * 2
×
3192

×
3193
        // As want to be more aggressive, we'll use a lower back off celling
×
3194
        // then the main peer bootstrap logic.
×
3195
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3196

×
3197
        for attempts := 0; ; attempts++ {
×
3198
                // Check if the server has been requested to shut down in order
×
3199
                // to prevent blocking.
×
3200
                if s.Stopped() {
×
3201
                        return
×
3202
                }
×
3203

3204
                // We can exit our aggressive initial peer bootstrapping stage
3205
                // if we've reached out target number of peers.
3206
                s.mu.RLock()
×
3207
                numActivePeers := uint32(len(s.peersByPub))
×
3208
                s.mu.RUnlock()
×
3209

×
3210
                if numActivePeers >= numTargetPeers {
×
3211
                        return
×
3212
                }
×
3213

3214
                if attempts > 0 {
×
3215
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3216
                                "bootstrap peers (attempt #%v)", delayTime,
×
3217
                                attempts)
×
3218

×
3219
                        // We've completed at least one iterating and haven't
×
3220
                        // finished, so we'll start to insert a delay period
×
3221
                        // between each attempt.
×
3222
                        delaySignal = time.After(delayTime)
×
3223
                        select {
×
3224
                        case <-delaySignal:
×
3225
                        case <-s.quit:
×
3226
                                return
×
3227
                        }
3228

3229
                        // After our delay, we'll double the time we wait up to
3230
                        // the max back off period.
3231
                        delayTime *= 2
×
3232
                        if delayTime > backOffCeiling {
×
3233
                                delayTime = backOffCeiling
×
3234
                        }
×
3235
                }
3236

3237
                // Otherwise, we'll request for the remaining number of peers
3238
                // in order to reach our target.
3239
                peersNeeded := numTargetPeers - numActivePeers
×
3240
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3241
                        ignore, peersNeeded, bootstrappers...,
×
3242
                )
×
3243
                if err != nil {
×
3244
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3245
                                "peers: %v", err)
×
3246
                        continue
×
3247
                }
3248

3249
                // Then, we'll attempt to establish a connection to the
3250
                // different peer addresses retrieved by our bootstrappers.
3251
                var wg sync.WaitGroup
×
3252
                for _, bootstrapAddr := range bootstrapAddrs {
×
3253
                        wg.Add(1)
×
3254
                        go func(addr *lnwire.NetAddress) {
×
3255
                                defer wg.Done()
×
3256

×
3257
                                errChan := make(chan error, 1)
×
3258
                                go s.connectToPeer(
×
3259
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3260
                                )
×
3261

×
3262
                                // We'll only allow this connection attempt to
×
3263
                                // take up to 3 seconds. This allows us to move
×
3264
                                // quickly by discarding peers that are slowing
×
3265
                                // us down.
×
3266
                                select {
×
3267
                                case err := <-errChan:
×
3268
                                        if err == nil {
×
3269
                                                return
×
3270
                                        }
×
3271
                                        srvrLog.Errorf("Unable to connect to "+
×
3272
                                                "%v: %v", addr, err)
×
3273
                                // TODO: tune timeout? 3 seconds might be *too*
3274
                                // aggressive but works well.
3275
                                case <-time.After(3 * time.Second):
×
3276
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3277
                                                "to not establishing a "+
×
3278
                                                "connection within 3 seconds",
×
3279
                                                addr)
×
3280
                                case <-s.quit:
×
3281
                                }
3282
                        }(bootstrapAddr)
3283
                }
3284

3285
                wg.Wait()
×
3286
        }
3287
}
3288

3289
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3290
// order to listen for inbound connections over Tor.
3291
func (s *server) createNewHiddenService() error {
×
3292
        // Determine the different ports the server is listening on. The onion
×
3293
        // service's virtual port will map to these ports and one will be picked
×
3294
        // at random when the onion service is being accessed.
×
3295
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3296
        for _, listenAddr := range s.listenAddrs {
×
3297
                port := listenAddr.(*net.TCPAddr).Port
×
3298
                listenPorts = append(listenPorts, port)
×
3299
        }
×
3300

3301
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3302
        if err != nil {
×
3303
                return err
×
3304
        }
×
3305

3306
        // Once the port mapping has been set, we can go ahead and automatically
3307
        // create our onion service. The service's private key will be saved to
3308
        // disk in order to regain access to this service when restarting `lnd`.
3309
        onionCfg := tor.AddOnionConfig{
×
3310
                VirtualPort: defaultPeerPort,
×
3311
                TargetPorts: listenPorts,
×
3312
                Store: tor.NewOnionFile(
×
3313
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3314
                        encrypter,
×
3315
                ),
×
3316
        }
×
3317

×
3318
        switch {
×
3319
        case s.cfg.Tor.V2:
×
3320
                onionCfg.Type = tor.V2
×
3321
        case s.cfg.Tor.V3:
×
3322
                onionCfg.Type = tor.V3
×
3323
        }
3324

3325
        addr, err := s.torController.AddOnion(onionCfg)
×
3326
        if err != nil {
×
3327
                return err
×
3328
        }
×
3329

3330
        // Now that the onion service has been created, we'll add the onion
3331
        // address it can be reached at to our list of advertised addresses.
3332
        newNodeAnn, err := s.genNodeAnnouncement(
×
3333
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3334
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3335
                },
×
3336
        )
3337
        if err != nil {
×
3338
                return fmt.Errorf("unable to generate new node "+
×
3339
                        "announcement: %v", err)
×
3340
        }
×
3341

3342
        // Finally, we'll update the on-disk version of our announcement so it
3343
        // will eventually propagate to nodes in the network.
3344
        selfNode := &models.LightningNode{
×
3345
                HaveNodeAnnouncement: true,
×
3346
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3347
                Addresses:            newNodeAnn.Addresses,
×
3348
                Alias:                newNodeAnn.Alias.String(),
×
3349
                Features: lnwire.NewFeatureVector(
×
3350
                        newNodeAnn.Features, lnwire.Features,
×
3351
                ),
×
3352
                Color:        newNodeAnn.RGBColor,
×
3353
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3354
        }
×
3355
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3356
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3357
                return fmt.Errorf("can't set self node: %w", err)
×
3358
        }
×
3359

3360
        return nil
×
3361
}
3362

3363
// findChannel finds a channel given a public key and ChannelID. It is an
3364
// optimization that is quicker than seeking for a channel given only the
3365
// ChannelID.
3366
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3367
        *channeldb.OpenChannel, error) {
3✔
3368

3✔
3369
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3370
        if err != nil {
3✔
3371
                return nil, err
×
3372
        }
×
3373

3374
        for _, channel := range nodeChans {
6✔
3375
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3376
                        return channel, nil
3✔
3377
                }
3✔
3378
        }
3379

3380
        return nil, fmt.Errorf("unable to find channel")
3✔
3381
}
3382

3383
// getNodeAnnouncement fetches the current, fully signed node announcement.
3384
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3385
        s.mu.Lock()
3✔
3386
        defer s.mu.Unlock()
3✔
3387

3✔
3388
        return *s.currentNodeAnn
3✔
3389
}
3✔
3390

3391
// genNodeAnnouncement generates and returns the current fully signed node
3392
// announcement. The time stamp of the announcement will be updated in order
3393
// to ensure it propagates through the network.
3394
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3395
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3396

3✔
3397
        s.mu.Lock()
3✔
3398
        defer s.mu.Unlock()
3✔
3399

3✔
3400
        // First, try to update our feature manager with the updated set of
3✔
3401
        // features.
3✔
3402
        if features != nil {
6✔
3403
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3404
                        feature.SetNodeAnn: features,
3✔
3405
                }
3✔
3406
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3407
                if err != nil {
6✔
3408
                        return lnwire.NodeAnnouncement{}, err
3✔
3409
                }
3✔
3410

3411
                // If we could successfully update our feature manager, add
3412
                // an update modifier to include these new features to our
3413
                // set.
3414
                modifiers = append(
3✔
3415
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3416
                )
3✔
3417
        }
3418

3419
        // Always update the timestamp when refreshing to ensure the update
3420
        // propagates.
3421
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3422

3✔
3423
        // Apply the requested changes to the node announcement.
3✔
3424
        for _, modifier := range modifiers {
6✔
3425
                modifier(s.currentNodeAnn)
3✔
3426
        }
3✔
3427

3428
        // Sign a new update after applying all of the passed modifiers.
3429
        err := netann.SignNodeAnnouncement(
3✔
3430
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
3✔
3431
        )
3✔
3432
        if err != nil {
3✔
3433
                return lnwire.NodeAnnouncement{}, err
×
3434
        }
×
3435

3436
        return *s.currentNodeAnn, nil
3✔
3437
}
3438

3439
// updateAndBroadcastSelfNode generates a new node announcement
3440
// applying the giving modifiers and updating the time stamp
3441
// to ensure it propagates through the network. Then it broadcasts
3442
// it to the network.
3443
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
3444
        modifiers ...netann.NodeAnnModifier) error {
3✔
3445

3✔
3446
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3447
        if err != nil {
6✔
3448
                return fmt.Errorf("unable to generate new node "+
3✔
3449
                        "announcement: %v", err)
3✔
3450
        }
3✔
3451

3452
        // Update the on-disk version of our announcement.
3453
        // Load and modify self node istead of creating anew instance so we
3454
        // don't risk overwriting any existing values.
3455
        selfNode, err := s.graphDB.SourceNode()
3✔
3456
        if err != nil {
3✔
3457
                return fmt.Errorf("unable to get current source node: %w", err)
×
3458
        }
×
3459

3460
        selfNode.HaveNodeAnnouncement = true
3✔
3461
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3462
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3463
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3464
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3465
        selfNode.Color = newNodeAnn.RGBColor
3✔
3466
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3467

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

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

3474
        // Finally, propagate it to the nodes in the network.
3475
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3476
        if err != nil {
3✔
3477
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3478
                        "announcement to peers: %v", err)
×
3479
                return err
×
3480
        }
×
3481

3482
        return nil
3✔
3483
}
3484

3485
type nodeAddresses struct {
3486
        pubKey    *btcec.PublicKey
3487
        addresses []net.Addr
3488
}
3489

3490
// establishPersistentConnections attempts to establish persistent connections
3491
// to all our direct channel collaborators. In order to promote liveness of our
3492
// active channels, we instruct the connection manager to attempt to establish
3493
// and maintain persistent connections to all our direct channel counterparties.
3494
func (s *server) establishPersistentConnections() error {
3✔
3495
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3496
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3497
        // since other PubKey forms can't be compared.
3✔
3498
        nodeAddrsMap := map[string]*nodeAddresses{}
3✔
3499

3✔
3500
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3501
        // attempt to connect to based on our set of previous connections. Set
3✔
3502
        // the reconnection port to the default peer port.
3✔
3503
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3504
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3505
                return err
×
3506
        }
×
3507
        for _, node := range linkNodes {
6✔
3508
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3509
                nodeAddrs := &nodeAddresses{
3✔
3510
                        pubKey:    node.IdentityPub,
3✔
3511
                        addresses: node.Addresses,
3✔
3512
                }
3✔
3513
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3514
        }
3✔
3515

3516
        // After checking our previous connections for addresses to connect to,
3517
        // iterate through the nodes in our channel graph to find addresses
3518
        // that have been added via NodeAnnouncement messages.
3519
        sourceNode, err := s.graphDB.SourceNode()
3✔
3520
        if err != nil {
3✔
3521
                return err
×
3522
        }
×
3523

3524
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3525
        // each of the nodes.
3526
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
3✔
3527
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
3✔
3528
                tx kvdb.RTx,
3✔
3529
                chanInfo *models.ChannelEdgeInfo,
3✔
3530
                policy, _ *models.ChannelEdgePolicy) error {
6✔
3531

3✔
3532
                // If the remote party has announced the channel to us, but we
3✔
3533
                // haven't yet, then we won't have a policy. However, we don't
3✔
3534
                // need this to connect to the peer, so we'll log it and move on.
3✔
3535
                if policy == nil {
3✔
3536
                        srvrLog.Warnf("No channel policy found for "+
×
3537
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3538
                }
×
3539

3540
                // We'll now fetch the peer opposite from us within this
3541
                // channel so we can queue up a direct connection to them.
3542
                channelPeer, err := s.graphDB.FetchOtherNode(
3✔
3543
                        tx, chanInfo, selfPub,
3✔
3544
                )
3✔
3545
                if err != nil {
3✔
3546
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3547
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3548
                                err)
×
3549
                }
×
3550

3551
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3552

3✔
3553
                // Add all unique addresses from channel
3✔
3554
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3555
                // connect to for this peer.
3✔
3556
                addrSet := make(map[string]net.Addr)
3✔
3557
                for _, addr := range channelPeer.Addresses {
6✔
3558
                        switch addr.(type) {
3✔
3559
                        case *net.TCPAddr:
3✔
3560
                                addrSet[addr.String()] = addr
3✔
3561

3562
                        // We'll only attempt to connect to Tor addresses if Tor
3563
                        // outbound support is enabled.
3564
                        case *tor.OnionAddr:
×
3565
                                if s.cfg.Tor.Active {
×
3566
                                        addrSet[addr.String()] = addr
×
3567
                                }
×
3568
                        }
3569
                }
3570

3571
                // If this peer is also recorded as a link node, we'll add any
3572
                // additional addresses that have not already been selected.
3573
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3574
                if ok {
6✔
3575
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3576
                                switch lnAddress.(type) {
3✔
3577
                                case *net.TCPAddr:
3✔
3578
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3579

3580
                                // We'll only attempt to connect to Tor
3581
                                // addresses if Tor outbound support is enabled.
3582
                                case *tor.OnionAddr:
×
3583
                                        if s.cfg.Tor.Active {
×
3584
                                                addrSet[lnAddress.String()] = lnAddress
×
3585
                                        }
×
3586
                                }
3587
                        }
3588
                }
3589

3590
                // Construct a slice of the deduped addresses.
3591
                var addrs []net.Addr
3✔
3592
                for _, addr := range addrSet {
6✔
3593
                        addrs = append(addrs, addr)
3✔
3594
                }
3✔
3595

3596
                n := &nodeAddresses{
3✔
3597
                        addresses: addrs,
3✔
3598
                }
3✔
3599
                n.pubKey, err = channelPeer.PubKey()
3✔
3600
                if err != nil {
3✔
3601
                        return err
×
3602
                }
×
3603

3604
                nodeAddrsMap[pubStr] = n
3✔
3605
                return nil
3✔
3606
        })
3607
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
3✔
3608
                return err
×
3609
        }
×
3610

3611
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3612
                len(nodeAddrsMap))
3✔
3613

3✔
3614
        // Acquire and hold server lock until all persistent connection requests
3✔
3615
        // have been recorded and sent to the connection manager.
3✔
3616
        s.mu.Lock()
3✔
3617
        defer s.mu.Unlock()
3✔
3618

3✔
3619
        // Iterate through the combined list of addresses from prior links and
3✔
3620
        // node announcements and attempt to reconnect to each node.
3✔
3621
        var numOutboundConns int
3✔
3622
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3623
                // Add this peer to the set of peers we should maintain a
3✔
3624
                // persistent connection with. We set the value to false to
3✔
3625
                // indicate that we should not continue to reconnect if the
3✔
3626
                // number of channels returns to zero, since this peer has not
3✔
3627
                // been requested as perm by the user.
3✔
3628
                s.persistentPeers[pubStr] = false
3✔
3629
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3630
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3631
                }
3✔
3632

3633
                for _, address := range nodeAddr.addresses {
6✔
3634
                        // Create a wrapper address which couples the IP and
3✔
3635
                        // the pubkey so the brontide authenticated connection
3✔
3636
                        // can be established.
3✔
3637
                        lnAddr := &lnwire.NetAddress{
3✔
3638
                                IdentityKey: nodeAddr.pubKey,
3✔
3639
                                Address:     address,
3✔
3640
                        }
3✔
3641

3✔
3642
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3643
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3644
                }
3✔
3645

3646
                // We'll connect to the first 10 peers immediately, then
3647
                // randomly stagger any remaining connections if the
3648
                // stagger initial reconnect flag is set. This ensures
3649
                // that mobile nodes or nodes with a small number of
3650
                // channels obtain connectivity quickly, but larger
3651
                // nodes are able to disperse the costs of connecting to
3652
                // all peers at once.
3653
                if numOutboundConns < numInstantInitReconnect ||
3✔
3654
                        !s.cfg.StaggerInitialReconnect {
6✔
3655

3✔
3656
                        go s.connectToPersistentPeer(pubStr)
3✔
3657
                } else {
3✔
3658
                        go s.delayInitialReconnect(pubStr)
×
3659
                }
×
3660

3661
                numOutboundConns++
3✔
3662
        }
3663

3664
        return nil
3✔
3665
}
3666

3667
// delayInitialReconnect will attempt a reconnection to the given peer after
3668
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3669
//
3670
// NOTE: This method MUST be run as a goroutine.
3671
func (s *server) delayInitialReconnect(pubStr string) {
×
3672
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3673
        select {
×
3674
        case <-time.After(delay):
×
3675
                s.connectToPersistentPeer(pubStr)
×
3676
        case <-s.quit:
×
3677
        }
3678
}
3679

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

3✔
3686
        s.mu.Lock()
3✔
3687
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3688
                delete(s.persistentPeers, pubKeyStr)
3✔
3689
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3690
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3691
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3692
                s.mu.Unlock()
3✔
3693

3✔
3694
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3695
                        "peer has no open channels", compressedPubKey)
3✔
3696

3✔
3697
                return
3✔
3698
        }
3✔
3699
        s.mu.Unlock()
3✔
3700
}
3701

3702
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3703
// is instead used to remove persistent peer state for a peer that has been
3704
// disconnected for good cause by the server. Currently, a gossip ban from
3705
// sending garbage and the server running out of restricted-access
3706
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3707
// future, this function may expand when more ban criteria is added.
3708
//
3709
// NOTE: The server's write lock MUST be held when this is called.
NEW
3710
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
NEW
3711
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
NEW
3712
                delete(s.persistentPeers, remotePub)
×
NEW
3713
                delete(s.persistentPeersBackoff, remotePub)
×
NEW
3714
                delete(s.persistentPeerAddrs, remotePub)
×
NEW
3715
                s.cancelConnReqs(remotePub, nil)
×
NEW
3716
        }
×
3717
}
3718

3719
// BroadcastMessage sends a request to the server to broadcast a set of
3720
// messages to all peers other than the one specified by the `skips` parameter.
3721
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3722
// the target peers.
3723
//
3724
// NOTE: This function is safe for concurrent access.
3725
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3726
        msgs ...lnwire.Message) error {
3✔
3727

3✔
3728
        // Filter out peers found in the skips map. We synchronize access to
3✔
3729
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3730
        // exact set of peers present at the time of invocation.
3✔
3731
        s.mu.RLock()
3✔
3732
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3733
        for pubStr, sPeer := range s.peersByPub {
6✔
3734
                if skips != nil {
6✔
3735
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3736
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3737
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3738
                                continue
3✔
3739
                        }
3740
                }
3741

3742
                peers = append(peers, sPeer)
3✔
3743
        }
3744
        s.mu.RUnlock()
3✔
3745

3✔
3746
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3747
        // all messages to each of peers.
3✔
3748
        var wg sync.WaitGroup
3✔
3749
        for _, sPeer := range peers {
6✔
3750
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3751
                        sPeer.PubKey())
3✔
3752

3✔
3753
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3754
                wg.Add(1)
3✔
3755
                s.wg.Add(1)
3✔
3756
                go func(p lnpeer.Peer) {
6✔
3757
                        defer s.wg.Done()
3✔
3758
                        defer wg.Done()
3✔
3759

3✔
3760
                        p.SendMessageLazy(false, msgs...)
3✔
3761
                }(sPeer)
3✔
3762
        }
3763

3764
        // Wait for all messages to have been dispatched before returning to
3765
        // caller.
3766
        wg.Wait()
3✔
3767

3✔
3768
        return nil
3✔
3769
}
3770

3771
// NotifyWhenOnline can be called by other subsystems to get notified when a
3772
// particular peer comes online. The peer itself is sent across the peerChan.
3773
//
3774
// NOTE: This function is safe for concurrent access.
3775
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3776
        peerChan chan<- lnpeer.Peer) {
3✔
3777

3✔
3778
        s.mu.Lock()
3✔
3779

3✔
3780
        // Compute the target peer's identifier.
3✔
3781
        pubStr := string(peerKey[:])
3✔
3782

3✔
3783
        // Check if peer is connected.
3✔
3784
        peer, ok := s.peersByPub[pubStr]
3✔
3785
        if ok {
6✔
3786
                // Unlock here so that the mutex isn't held while we are
3✔
3787
                // waiting for the peer to become active.
3✔
3788
                s.mu.Unlock()
3✔
3789

3✔
3790
                // Wait until the peer signals that it is actually active
3✔
3791
                // rather than only in the server's maps.
3✔
3792
                select {
3✔
3793
                case <-peer.ActiveSignal():
3✔
3794
                case <-peer.QuitSignal():
×
3795
                        // The peer quit, so we'll add the channel to the slice
×
3796
                        // and return.
×
3797
                        s.mu.Lock()
×
3798
                        s.peerConnectedListeners[pubStr] = append(
×
3799
                                s.peerConnectedListeners[pubStr], peerChan,
×
3800
                        )
×
3801
                        s.mu.Unlock()
×
3802
                        return
×
3803
                }
3804

3805
                // Connected, can return early.
3806
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3807

3✔
3808
                select {
3✔
3809
                case peerChan <- peer:
3✔
3810
                case <-s.quit:
×
3811
                }
3812

3813
                return
3✔
3814
        }
3815

3816
        // Not connected, store this listener such that it can be notified when
3817
        // the peer comes online.
3818
        s.peerConnectedListeners[pubStr] = append(
3✔
3819
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3820
        )
3✔
3821
        s.mu.Unlock()
3✔
3822
}
3823

3824
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3825
// the given public key has been disconnected. The notification is signaled by
3826
// closing the channel returned.
3827
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3828
        s.mu.Lock()
3✔
3829
        defer s.mu.Unlock()
3✔
3830

3✔
3831
        c := make(chan struct{})
3✔
3832

3✔
3833
        // If the peer is already offline, we can immediately trigger the
3✔
3834
        // notification.
3✔
3835
        peerPubKeyStr := string(peerPubKey[:])
3✔
3836
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3837
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3838
                close(c)
×
3839
                return c
×
3840
        }
×
3841

3842
        // Otherwise, the peer is online, so we'll keep track of the channel to
3843
        // trigger the notification once the server detects the peer
3844
        // disconnects.
3845
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3846
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3847
        )
3✔
3848

3✔
3849
        return c
3✔
3850
}
3851

3852
// FindPeer will return the peer that corresponds to the passed in public key.
3853
// This function is used by the funding manager, allowing it to update the
3854
// daemon's local representation of the remote peer.
3855
//
3856
// NOTE: This function is safe for concurrent access.
3857
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3858
        s.mu.RLock()
3✔
3859
        defer s.mu.RUnlock()
3✔
3860

3✔
3861
        pubStr := string(peerKey.SerializeCompressed())
3✔
3862

3✔
3863
        return s.findPeerByPubStr(pubStr)
3✔
3864
}
3✔
3865

3866
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3867
// which should be a string representation of the peer's serialized, compressed
3868
// public key.
3869
//
3870
// NOTE: This function is safe for concurrent access.
3871
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3872
        s.mu.RLock()
3✔
3873
        defer s.mu.RUnlock()
3✔
3874

3✔
3875
        return s.findPeerByPubStr(pubStr)
3✔
3876
}
3✔
3877

3878
// findPeerByPubStr is an internal method that retrieves the specified peer from
3879
// the server's internal state using.
3880
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3881
        peer, ok := s.peersByPub[pubStr]
3✔
3882
        if !ok {
6✔
3883
                return nil, ErrPeerNotConnected
3✔
3884
        }
3✔
3885

3886
        return peer, nil
3✔
3887
}
3888

3889
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3890
// exponential backoff. If no previous backoff was known, the default is
3891
// returned.
3892
func (s *server) nextPeerBackoff(pubStr string,
3893
        startTime time.Time) time.Duration {
3✔
3894

3✔
3895
        // Now, determine the appropriate backoff to use for the retry.
3✔
3896
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3897
        if !ok {
6✔
3898
                // If an existing backoff was unknown, use the default.
3✔
3899
                return s.cfg.MinBackoff
3✔
3900
        }
3✔
3901

3902
        // If the peer failed to start properly, we'll just use the previous
3903
        // backoff to compute the subsequent randomized exponential backoff
3904
        // duration. This will roughly double on average.
3905
        if startTime.IsZero() {
3✔
3906
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3907
        }
×
3908

3909
        // The peer succeeded in starting. If the connection didn't last long
3910
        // enough to be considered stable, we'll continue to back off retries
3911
        // with this peer.
3912
        connDuration := time.Since(startTime)
3✔
3913
        if connDuration < defaultStableConnDuration {
6✔
3914
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3915
        }
3✔
3916

3917
        // The peer succeed in starting and this was stable peer, so we'll
3918
        // reduce the timeout duration by the length of the connection after
3919
        // applying randomized exponential backoff. We'll only apply this in the
3920
        // case that:
3921
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3922
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3923
        if relaxedBackoff > s.cfg.MinBackoff {
×
3924
                return relaxedBackoff
×
3925
        }
×
3926

3927
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3928
        // the stable connection lasted much longer than our previous backoff.
3929
        // To reward such good behavior, we'll reconnect after the default
3930
        // timeout.
3931
        return s.cfg.MinBackoff
×
3932
}
3933

3934
// shouldDropLocalConnection determines if our local connection to a remote peer
3935
// should be dropped in the case of concurrent connection establishment. In
3936
// order to deterministically decide which connection should be dropped, we'll
3937
// utilize the ordering of the local and remote public key. If we didn't use
3938
// such a tie breaker, then we risk _both_ connections erroneously being
3939
// dropped.
3940
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3941
        localPubBytes := local.SerializeCompressed()
×
3942
        remotePubPbytes := remote.SerializeCompressed()
×
3943

×
3944
        // The connection that comes from the node with a "smaller" pubkey
×
3945
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3946
        // should drop our established connection.
×
3947
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3948
}
×
3949

3950
// InboundPeerConnected initializes a new peer in response to a new inbound
3951
// connection.
3952
//
3953
// NOTE: This function is safe for concurrent access.
3954
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3955
        // Exit early if we have already been instructed to shutdown, this
3✔
3956
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3957
        if s.Stopped() {
3✔
3958
                return
×
3959
        }
×
3960

3961
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3962
        pubSer := nodePub.SerializeCompressed()
3✔
3963
        pubStr := string(pubSer)
3✔
3964

3✔
3965
        var pubBytes [33]byte
3✔
3966
        copy(pubBytes[:], pubSer)
3✔
3967

3✔
3968
        s.mu.Lock()
3✔
3969
        defer s.mu.Unlock()
3✔
3970

3✔
3971
        // If the remote node's public key is banned, drop the connection.
3✔
3972
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
3✔
3973
        if err != nil {
3✔
NEW
3974
                // Clean up the persistent peer maps if we're dropping this
×
NEW
3975
                // connection.
×
NEW
3976
                s.bannedPersistentPeerConnection(pubStr)
×
UNCOV
3977

×
NEW
3978
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
NEW
3979
                        "of restricted-access connection slots: %v.", pubSer,
×
NEW
3980
                        err)
×
3981

×
3982
                conn.Close()
×
3983

×
3984
                return
×
3985
        }
×
3986

3987
        // If we already have an outbound connection to this peer, then ignore
3988
        // this new connection.
3989
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
3990
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3991
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3992
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3993

3✔
3994
                conn.Close()
3✔
3995
                return
3✔
3996
        }
3✔
3997

3998
        // If we already have a valid connection that is scheduled to take
3999
        // precedence once the prior peer has finished disconnecting, we'll
4000
        // ignore this connection.
4001
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
4002
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4003
                        "scheduled", conn.RemoteAddr(), p)
×
4004
                conn.Close()
×
4005
                return
×
4006
        }
×
4007

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

3✔
4010
        // Check to see if we already have a connection with this peer. If so,
3✔
4011
        // we may need to drop our existing connection. This prevents us from
3✔
4012
        // having duplicate connections to the same peer. We forgo adding a
3✔
4013
        // default case as we expect these to be the only error values returned
3✔
4014
        // from findPeerByPubStr.
3✔
4015
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4016
        switch err {
3✔
4017
        case ErrPeerNotConnected:
3✔
4018
                // We were unable to locate an existing connection with the
3✔
4019
                // target peer, proceed to connect.
3✔
4020
                s.cancelConnReqs(pubStr, nil)
3✔
4021
                s.peerConnected(conn, nil, true, access)
3✔
4022

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

×
4033
                        srvrLog.Warnf("Received inbound connection from "+
×
4034
                                "peer %v, but already have outbound "+
×
4035
                                "connection, dropping conn", connectedPeer)
×
4036
                        conn.Close()
×
4037
                        return
×
4038
                }
×
4039

4040
                // Otherwise, if we should drop the connection, then we'll
4041
                // disconnect our already connected peer.
4042
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4043
                        connectedPeer)
×
4044

×
4045
                s.cancelConnReqs(pubStr, nil)
×
4046

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

4058
// OutboundPeerConnected initializes a new peer in response to a new outbound
4059
// connection.
4060
// NOTE: This function is safe for concurrent access.
4061
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4062
        // Exit early if we have already been instructed to shutdown, this
3✔
4063
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4064
        if s.Stopped() {
3✔
4065
                return
×
4066
        }
×
4067

4068
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4069
        pubSer := nodePub.SerializeCompressed()
3✔
4070
        pubStr := string(pubSer)
3✔
4071

3✔
4072
        var pubBytes [33]byte
3✔
4073
        copy(pubBytes[:], pubSer)
3✔
4074

3✔
4075
        s.mu.Lock()
3✔
4076
        defer s.mu.Unlock()
3✔
4077

3✔
4078
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
3✔
4079
        if err != nil {
3✔
NEW
4080
                // Clean up the persistent peer maps if we're dropping this
×
NEW
4081
                // connection.
×
NEW
4082
                s.bannedPersistentPeerConnection(pubStr)
×
UNCOV
4083

×
NEW
4084
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
NEW
4085
                        "of restricted-access connection slots: %v.", pubSer,
×
NEW
4086
                        err)
×
4087

×
4088
                if connReq != nil {
×
4089
                        s.connMgr.Remove(connReq.ID())
×
4090
                }
×
4091

4092
                conn.Close()
×
4093

×
4094
                return
×
4095
        }
4096

4097
        // If we already have an inbound connection to this peer, then ignore
4098
        // this new connection.
4099
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4100
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4101
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4102
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4103

3✔
4104
                if connReq != nil {
6✔
4105
                        s.connMgr.Remove(connReq.ID())
3✔
4106
                }
3✔
4107
                conn.Close()
3✔
4108
                return
3✔
4109
        }
4110
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4111
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4112
                s.connMgr.Remove(connReq.ID())
×
4113
                conn.Close()
×
4114
                return
×
4115
        }
×
4116

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

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

4127
                conn.Close()
×
4128
                return
×
4129
        }
4130

4131
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
3✔
4132
                conn.RemoteAddr())
3✔
4133

3✔
4134
        if connReq != nil {
6✔
4135
                // A successful connection was returned by the connmgr.
3✔
4136
                // Immediately cancel all pending requests, excluding the
3✔
4137
                // outbound connection we just established.
3✔
4138
                ignore := connReq.ID()
3✔
4139
                s.cancelConnReqs(pubStr, &ignore)
3✔
4140
        } else {
6✔
4141
                // This was a successful connection made by some other
3✔
4142
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4143
                s.cancelConnReqs(pubStr, nil)
3✔
4144
        }
3✔
4145

4146
        // If we already have a connection with this peer, decide whether or not
4147
        // we need to drop the stale connection. We forgo adding a default case
4148
        // as we expect these to be the only error values returned from
4149
        // findPeerByPubStr.
4150
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4151
        switch err {
3✔
4152
        case ErrPeerNotConnected:
3✔
4153
                // We were unable to locate an existing connection with the
3✔
4154
                // target peer, proceed to connect.
3✔
4155
                s.peerConnected(conn, connReq, false, access)
3✔
4156

4157
        case nil:
×
4158
                // We already have a connection with the incoming peer. If the
×
4159
                // connection we've already established should be kept and is
×
4160
                // not of the same type of the new connection (outbound), then
×
4161
                // we'll close out the new connection s.t there's only a single
×
4162
                // connection between us.
×
4163
                localPub := s.identityECDH.PubKey()
×
4164
                if connectedPeer.Inbound() &&
×
4165
                        shouldDropLocalConnection(localPub, nodePub) {
×
4166

×
4167
                        srvrLog.Warnf("Established outbound connection to "+
×
4168
                                "peer %v, but already have inbound "+
×
4169
                                "connection, dropping conn", connectedPeer)
×
4170
                        if connReq != nil {
×
4171
                                s.connMgr.Remove(connReq.ID())
×
4172
                        }
×
4173
                        conn.Close()
×
4174
                        return
×
4175
                }
4176

4177
                // Otherwise, _their_ connection should be dropped. So we'll
4178
                // disconnect the peer and send the now obsolete peer to the
4179
                // server for garbage collection.
4180
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4181
                        connectedPeer)
×
4182

×
4183
                // Remove the current peer from the server's internal state and
×
4184
                // signal that the peer termination watcher does not need to
×
4185
                // execute for this peer.
×
4186
                s.removePeer(connectedPeer)
×
4187
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4188
                s.scheduledPeerConnection[pubStr] = func() {
×
NEW
4189
                        s.peerConnected(conn, connReq, false, access)
×
4190
                }
×
4191
        }
4192
}
4193

4194
// UnassignedConnID is the default connection ID that a request can have before
4195
// it actually is submitted to the connmgr.
4196
// TODO(conner): move into connmgr package, or better, add connmgr method for
4197
// generating atomic IDs
4198
const UnassignedConnID uint64 = 0
4199

4200
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4201
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4202
// Afterwards, each connection request removed from the connmgr. The caller can
4203
// optionally specify a connection ID to ignore, which prevents us from
4204
// canceling a successful request. All persistent connreqs for the provided
4205
// pubkey are discarded after the operationjw.
4206
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4207
        // First, cancel any lingering persistent retry attempts, which will
3✔
4208
        // prevent retries for any with backoffs that are still maturing.
3✔
4209
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4210
                close(cancelChan)
3✔
4211
                delete(s.persistentRetryCancels, pubStr)
3✔
4212
        }
3✔
4213

4214
        // Next, check to see if we have any outstanding persistent connection
4215
        // requests to this peer. If so, then we'll remove all of these
4216
        // connection requests, and also delete the entry from the map.
4217
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4218
        if !ok {
6✔
4219
                return
3✔
4220
        }
3✔
4221

4222
        for _, connReq := range connReqs {
6✔
4223
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4224

3✔
4225
                // Atomically capture the current request identifier.
3✔
4226
                connID := connReq.ID()
3✔
4227

3✔
4228
                // Skip any zero IDs, this indicates the request has not
3✔
4229
                // yet been schedule.
3✔
4230
                if connID == UnassignedConnID {
3✔
4231
                        continue
×
4232
                }
4233

4234
                // Skip a particular connection ID if instructed.
4235
                if skip != nil && connID == *skip {
6✔
4236
                        continue
3✔
4237
                }
4238

4239
                s.connMgr.Remove(connID)
3✔
4240
        }
4241

4242
        delete(s.persistentConnReqs, pubStr)
3✔
4243
}
4244

4245
// handleCustomMessage dispatches an incoming custom peers message to
4246
// subscribers.
4247
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4248
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4249
                peer, msg.Type)
3✔
4250

3✔
4251
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4252
                Peer: peer,
3✔
4253
                Msg:  msg,
3✔
4254
        })
3✔
4255
}
3✔
4256

4257
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4258
// messages.
4259
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4260
        return s.customMessageServer.Subscribe()
3✔
4261
}
3✔
4262

4263
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4264
// the channelNotifier's NotifyOpenChannelEvent.
4265
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4266
        remotePub *btcec.PublicKey) error {
3✔
4267

3✔
4268
        // Call newOpenChan to update the access manager's maps for this peer.
3✔
4269
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
6✔
4270
                return err
3✔
4271
        }
3✔
4272

4273
        // Notify subscribers about this open channel event.
4274
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4275

3✔
4276
        return nil
3✔
4277
}
4278

4279
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4280
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4281
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4282
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) error {
3✔
4283

3✔
4284
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4285
        // peer.
3✔
4286
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
NEW
4287
                return err
×
NEW
4288
        }
×
4289

4290
        // Notify subscribers about this event.
4291
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4292

3✔
4293
        return nil
3✔
4294
}
4295

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

×
NEW
4301
        // Call newPendingCloseChan to potentially demote the peer.
×
NEW
4302
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
×
NEW
4303
        if err == ErrNoMoreRestrictedAccessSlots {
×
NEW
4304
                s.DisconnectPeer(remotePub)
×
NEW
4305
        }
×
4306

4307
        // Notify subscribers about this event.
NEW
4308
        s.channelNotifier.NotifyFundingTimeout(op)
×
NEW
4309

×
NEW
4310
        return nil
×
4311
}
4312

4313
// peerConnected is a function that handles initialization a newly connected
4314
// peer by adding it to the server's global list of all active peers, and
4315
// starting all the goroutines the peer needs to function properly. The inbound
4316
// boolean should be true if the peer initiated the connection to us.
4317
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4318
        inbound bool, access peerAccessStatus,
4319
) {
3✔
4320
        brontideConn := conn.(*brontide.Conn)
3✔
4321
        addr := conn.RemoteAddr()
3✔
4322
        pubKey := brontideConn.RemotePub()
3✔
4323

3✔
4324
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4325
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4326

3✔
4327
        peerAddr := &lnwire.NetAddress{
3✔
4328
                IdentityKey: pubKey,
3✔
4329
                Address:     addr,
3✔
4330
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4331
        }
3✔
4332

3✔
4333
        // With the brontide connection established, we'll now craft the feature
3✔
4334
        // vectors to advertise to the remote node.
3✔
4335
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4336
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4337

3✔
4338
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4339
        // found, create a fresh buffer.
3✔
4340
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4341
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4342
        if !ok {
6✔
4343
                var err error
3✔
4344
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4345
                if err != nil {
3✔
4346
                        srvrLog.Errorf("unable to create peer %v", err)
×
4347
                        return
×
4348
                }
×
4349
        }
4350

4351
        // If we directly set the peer.Config TowerClient member to the
4352
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4353
        // the peer.Config's TowerClient member will not evaluate to nil even
4354
        // though the underlying value is nil. To avoid this gotcha which can
4355
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4356
        // TowerClient if needed.
4357
        var towerClient wtclient.ClientManager
3✔
4358
        if s.towerClientMgr != nil {
6✔
4359
                towerClient = s.towerClientMgr
3✔
4360
        }
3✔
4361

4362
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4363
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4364

3✔
4365
        // Now that we've established a connection, create a peer, and it to the
3✔
4366
        // set of currently active peers. Configure the peer with the incoming
3✔
4367
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
3✔
4368
        // offered that would trigger channel closure. In case of outgoing
3✔
4369
        // htlcs, an extra block is added to prevent the channel from being
3✔
4370
        // closed when the htlc is outstanding and a new block comes in.
3✔
4371
        pCfg := peer.Config{
3✔
4372
                Conn:                    brontideConn,
3✔
4373
                ConnReq:                 connReq,
3✔
4374
                Addr:                    peerAddr,
3✔
4375
                Inbound:                 inbound,
3✔
4376
                Features:                initFeatures,
3✔
4377
                LegacyFeatures:          legacyFeatures,
3✔
4378
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
3✔
4379
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
3✔
4380
                ErrorBuffer:             errBuffer,
3✔
4381
                WritePool:               s.writePool,
3✔
4382
                ReadPool:                s.readPool,
3✔
4383
                Switch:                  s.htlcSwitch,
3✔
4384
                InterceptSwitch:         s.interceptableSwitch,
3✔
4385
                ChannelDB:               s.chanStateDB,
3✔
4386
                ChannelGraph:            s.graphDB,
3✔
4387
                ChainArb:                s.chainArb,
3✔
4388
                AuthGossiper:            s.authGossiper,
3✔
4389
                ChanStatusMgr:           s.chanStatusMgr,
3✔
4390
                ChainIO:                 s.cc.ChainIO,
3✔
4391
                FeeEstimator:            s.cc.FeeEstimator,
3✔
4392
                Signer:                  s.cc.Wallet.Cfg.Signer,
3✔
4393
                SigPool:                 s.sigPool,
3✔
4394
                Wallet:                  s.cc.Wallet,
3✔
4395
                ChainNotifier:           s.cc.ChainNotifier,
3✔
4396
                BestBlockView:           s.cc.BestBlockTracker,
3✔
4397
                RoutingPolicy:           s.cc.RoutingPolicy,
3✔
4398
                Sphinx:                  s.sphinx,
3✔
4399
                WitnessBeacon:           s.witnessBeacon,
3✔
4400
                Invoices:                s.invoices,
3✔
4401
                ChannelNotifier:         s.channelNotifier,
3✔
4402
                HtlcNotifier:            s.htlcNotifier,
3✔
4403
                TowerClient:             towerClient,
3✔
4404
                DisconnectPeer:          s.DisconnectPeer,
3✔
4405
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
3✔
4406
                        lnwire.NodeAnnouncement, error) {
6✔
4407

3✔
4408
                        return s.genNodeAnnouncement(nil)
3✔
4409
                },
3✔
4410

4411
                PongBuf: s.pongBuf,
4412

4413
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4414

4415
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4416

4417
                FundingManager: s.fundingMgr,
4418

4419
                Hodl:                    s.cfg.Hodl,
4420
                UnsafeReplay:            s.cfg.UnsafeReplay,
4421
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4422
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4423
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4424
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4425
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4426
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4427
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4428
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4429
                HandleCustomMessage:    s.handleCustomMessage,
4430
                GetAliases:             s.aliasMgr.GetAliases,
4431
                RequestAlias:           s.aliasMgr.RequestAlias,
4432
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4433
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4434
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4435
                MaxFeeExposure:         thresholdMSats,
4436
                Quit:                   s.quit,
4437
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4438
                AuxSigner:              s.implCfg.AuxSigner,
4439
                MsgRouter:              s.implCfg.MsgRouter,
4440
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4441
                AuxResolver:            s.implCfg.AuxContractResolver,
4442
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4443
                ShouldFwdExpEndorsement: func() bool {
3✔
4444
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4445
                                return false
3✔
4446
                        }
3✔
4447

4448
                        return clock.NewDefaultClock().Now().Before(
3✔
4449
                                EndorsementExperimentEnd,
3✔
4450
                        )
3✔
4451
                },
4452
        }
4453

4454
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4455
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4456

3✔
4457
        p := peer.NewBrontide(pCfg)
3✔
4458

3✔
4459
        // Update the access manager with the access permission for this peer.
3✔
4460
        s.peerAccessMan.addPeerAccess(pubKey, access)
3✔
4461

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

3✔
4465
        s.addPeer(p)
3✔
4466

3✔
4467
        // Once we have successfully added the peer to the server, we can
3✔
4468
        // delete the previous error buffer from the server's map of error
3✔
4469
        // buffers.
3✔
4470
        delete(s.peerErrors, pkStr)
3✔
4471

3✔
4472
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4473
        // includes sending and receiving Init messages, which would be a DOS
3✔
4474
        // vector if we held the server's mutex throughout the procedure.
3✔
4475
        s.wg.Add(1)
3✔
4476
        go s.peerInitializer(p)
3✔
4477
}
4478

4479
// addPeer adds the passed peer to the server's global state of all active
4480
// peers.
4481
func (s *server) addPeer(p *peer.Brontide) {
3✔
4482
        if p == nil {
3✔
4483
                return
×
4484
        }
×
4485

4486
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4487

3✔
4488
        // Ignore new peers if we're shutting down.
3✔
4489
        if s.Stopped() {
3✔
4490
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4491
                        pubBytes)
×
4492
                p.Disconnect(ErrServerShuttingDown)
×
4493

×
4494
                return
×
4495
        }
×
4496

4497
        // Track the new peer in our indexes so we can quickly look it up either
4498
        // according to its public key, or its peer ID.
4499
        // TODO(roasbeef): pipe all requests through to the
4500
        // queryHandler/peerManager
4501

4502
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4503
        // be human-readable.
4504
        pubStr := string(pubBytes)
3✔
4505

3✔
4506
        s.peersByPub[pubStr] = p
3✔
4507

3✔
4508
        if p.Inbound() {
6✔
4509
                s.inboundPeers[pubStr] = p
3✔
4510
        } else {
6✔
4511
                s.outboundPeers[pubStr] = p
3✔
4512
        }
3✔
4513

4514
        // Inform the peer notifier of a peer online event so that it can be reported
4515
        // to clients listening for peer events.
4516
        var pubKey [33]byte
3✔
4517
        copy(pubKey[:], pubBytes)
3✔
4518

3✔
4519
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4520
}
4521

4522
// peerInitializer asynchronously starts a newly connected peer after it has
4523
// been added to the server's peer map. This method sets up a
4524
// peerTerminationWatcher for the given peer, and ensures that it executes even
4525
// if the peer failed to start. In the event of a successful connection, this
4526
// method reads the negotiated, local feature-bits and spawns the appropriate
4527
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4528
// be signaled of the new peer once the method returns.
4529
//
4530
// NOTE: This MUST be launched as a goroutine.
4531
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4532
        defer s.wg.Done()
3✔
4533

3✔
4534
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4535

3✔
4536
        // Avoid initializing peers while the server is exiting.
3✔
4537
        if s.Stopped() {
3✔
4538
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4539
                        pubBytes)
×
4540
                return
×
4541
        }
×
4542

4543
        // Create a channel that will be used to signal a successful start of
4544
        // the link. This prevents the peer termination watcher from beginning
4545
        // its duty too early.
4546
        ready := make(chan struct{})
3✔
4547

3✔
4548
        // Before starting the peer, launch a goroutine to watch for the
3✔
4549
        // unexpected termination of this peer, which will ensure all resources
3✔
4550
        // are properly cleaned up, and re-establish persistent connections when
3✔
4551
        // necessary. The peer termination watcher will be short circuited if
3✔
4552
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4553
        // that the server has already handled the removal of this peer.
3✔
4554
        s.wg.Add(1)
3✔
4555
        go s.peerTerminationWatcher(p, ready)
3✔
4556

3✔
4557
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4558
        // will unblock the peerTerminationWatcher.
3✔
4559
        if err := p.Start(); err != nil {
6✔
4560
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4561

3✔
4562
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4563
                return
3✔
4564
        }
3✔
4565

4566
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4567
        // was successful, and to begin watching the peer's wait group.
4568
        close(ready)
3✔
4569

3✔
4570
        s.mu.Lock()
3✔
4571
        defer s.mu.Unlock()
3✔
4572

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

3✔
4576
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4577
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4578
        pubStr := string(pubBytes)
3✔
4579
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4580
                select {
3✔
4581
                case peerChan <- p:
3✔
4582
                case <-s.quit:
×
4583
                        return
×
4584
                }
4585
        }
4586
        delete(s.peerConnectedListeners, pubStr)
3✔
4587
}
4588

4589
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4590
// and then cleans up all resources allocated to the peer, notifies relevant
4591
// sub-systems of its demise, and finally handles re-connecting to the peer if
4592
// it's persistent. If the server intentionally disconnects a peer, it should
4593
// have a corresponding entry in the ignorePeerTermination map which will cause
4594
// the cleanup routine to exit early. The passed `ready` chan is used to
4595
// synchronize when WaitForDisconnect should begin watching on the peer's
4596
// waitgroup. The ready chan should only be signaled if the peer starts
4597
// successfully, otherwise the peer should be disconnected instead.
4598
//
4599
// NOTE: This MUST be launched as a goroutine.
4600
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4601
        defer s.wg.Done()
3✔
4602

3✔
4603
        p.WaitForDisconnect(ready)
3✔
4604

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

3✔
4607
        // If the server is exiting then we can bail out early ourselves as all
3✔
4608
        // the other sub-systems will already be shutting down.
3✔
4609
        if s.Stopped() {
6✔
4610
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
3✔
4611
                return
3✔
4612
        }
3✔
4613

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

3✔
4620
        pubKey := p.IdentityKey()
3✔
4621

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

3✔
4626
        // Tell the switch to remove all links associated with this peer.
3✔
4627
        // Passing nil as the target link indicates that all links associated
3✔
4628
        // with this interface should be closed.
3✔
4629
        //
3✔
4630
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4631
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4632
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4633
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4634
        }
×
4635

4636
        for _, link := range links {
6✔
4637
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4638
        }
3✔
4639

4640
        s.mu.Lock()
3✔
4641
        defer s.mu.Unlock()
3✔
4642

3✔
4643
        // If there were any notification requests for when this peer
3✔
4644
        // disconnected, we can trigger them now.
3✔
4645
        srvrLog.Debugf("Notifying that peer %v is offline", p)
3✔
4646
        pubStr := string(pubKey.SerializeCompressed())
3✔
4647
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4648
                close(offlineChan)
3✔
4649
        }
3✔
4650
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4651

3✔
4652
        // If the server has already removed this peer, we can short circuit the
3✔
4653
        // peer termination watcher and skip cleanup.
3✔
4654
        if _, ok := s.ignorePeerTermination[p]; ok {
3✔
4655
                delete(s.ignorePeerTermination, p)
×
4656

×
4657
                pubKey := p.PubKey()
×
4658
                pubStr := string(pubKey[:])
×
4659

×
4660
                // If a connection callback is present, we'll go ahead and
×
4661
                // execute it now that previous peer has fully disconnected. If
×
4662
                // the callback is not present, this likely implies the peer was
×
4663
                // purposefully disconnected via RPC, and that no reconnect
×
4664
                // should be attempted.
×
4665
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4666
                if ok {
×
4667
                        delete(s.scheduledPeerConnection, pubStr)
×
4668
                        connCallback()
×
4669
                }
×
4670
                return
×
4671
        }
4672

4673
        // First, cleanup any remaining state the server has regarding the peer
4674
        // in question.
4675
        s.removePeer(p)
3✔
4676

3✔
4677
        // Next, check to see if this is a persistent peer or not.
3✔
4678
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4679
                return
3✔
4680
        }
3✔
4681

4682
        // Get the last address that we used to connect to the peer.
4683
        addrs := []net.Addr{
3✔
4684
                p.NetAddress().Address,
3✔
4685
        }
3✔
4686

3✔
4687
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4688
        // reconnection purposes.
3✔
4689
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
3✔
4690
        switch {
3✔
4691
        // We found advertised addresses, so use them.
4692
        case err == nil:
3✔
4693
                addrs = advertisedAddrs
3✔
4694

4695
        // The peer doesn't have an advertised address.
4696
        case err == errNoAdvertisedAddr:
3✔
4697
                // If it is an outbound peer then we fall back to the existing
3✔
4698
                // peer address.
3✔
4699
                if !p.Inbound() {
6✔
4700
                        break
3✔
4701
                }
4702

4703
                // Fall back to the existing peer address if
4704
                // we're not accepting connections over Tor.
4705
                if s.torController == nil {
6✔
4706
                        break
3✔
4707
                }
4708

4709
                // If we are, the peer's address won't be known
4710
                // to us (we'll see a private address, which is
4711
                // the address used by our onion service to dial
4712
                // to lnd), so we don't have enough information
4713
                // to attempt a reconnect.
4714
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4715
                        "to inbound peer %v without "+
×
4716
                        "advertised address", p)
×
4717
                return
×
4718

4719
        // We came across an error retrieving an advertised
4720
        // address, log it, and fall back to the existing peer
4721
        // address.
4722
        default:
3✔
4723
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4724
                        "address for node %x: %v", p.PubKey(),
3✔
4725
                        err)
3✔
4726
        }
4727

4728
        // Make an easy lookup map so that we can check if an address
4729
        // is already in the address list that we have stored for this peer.
4730
        existingAddrs := make(map[string]bool)
3✔
4731
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4732
                existingAddrs[addr.String()] = true
3✔
4733
        }
3✔
4734

4735
        // Add any missing addresses for this peer to persistentPeerAddr.
4736
        for _, addr := range addrs {
6✔
4737
                if existingAddrs[addr.String()] {
3✔
4738
                        continue
×
4739
                }
4740

4741
                s.persistentPeerAddrs[pubStr] = append(
3✔
4742
                        s.persistentPeerAddrs[pubStr],
3✔
4743
                        &lnwire.NetAddress{
3✔
4744
                                IdentityKey: p.IdentityKey(),
3✔
4745
                                Address:     addr,
3✔
4746
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4747
                        },
3✔
4748
                )
3✔
4749
        }
4750

4751
        // Record the computed backoff in the backoff map.
4752
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4753
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4754

3✔
4755
        // Initialize a retry canceller for this peer if one does not
3✔
4756
        // exist.
3✔
4757
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4758
        if !ok {
6✔
4759
                cancelChan = make(chan struct{})
3✔
4760
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4761
        }
3✔
4762

4763
        // We choose not to wait group this go routine since the Connect
4764
        // call can stall for arbitrarily long if we shutdown while an
4765
        // outbound connection attempt is being made.
4766
        go func() {
6✔
4767
                srvrLog.Debugf("Scheduling connection re-establishment to "+
3✔
4768
                        "persistent peer %x in %s",
3✔
4769
                        p.IdentityKey().SerializeCompressed(), backoff)
3✔
4770

3✔
4771
                select {
3✔
4772
                case <-time.After(backoff):
3✔
4773
                case <-cancelChan:
3✔
4774
                        return
3✔
4775
                case <-s.quit:
3✔
4776
                        return
3✔
4777
                }
4778

4779
                srvrLog.Debugf("Attempting to re-establish persistent "+
3✔
4780
                        "connection to peer %x",
3✔
4781
                        p.IdentityKey().SerializeCompressed())
3✔
4782

3✔
4783
                s.connectToPersistentPeer(pubStr)
3✔
4784
        }()
4785
}
4786

4787
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4788
// to connect to the peer. It creates connection requests if there are
4789
// currently none for a given address and it removes old connection requests
4790
// if the associated address is no longer in the latest address list for the
4791
// peer.
4792
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4793
        s.mu.Lock()
3✔
4794
        defer s.mu.Unlock()
3✔
4795

3✔
4796
        // Create an easy lookup map of the addresses we have stored for the
3✔
4797
        // peer. We will remove entries from this map if we have existing
3✔
4798
        // connection requests for the associated address and then any leftover
3✔
4799
        // entries will indicate which addresses we should create new
3✔
4800
        // connection requests for.
3✔
4801
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4802
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4803
                addrMap[addr.String()] = addr
3✔
4804
        }
3✔
4805

4806
        // Go through each of the existing connection requests and
4807
        // check if they correspond to the latest set of addresses. If
4808
        // there is a connection requests that does not use one of the latest
4809
        // advertised addresses then remove that connection request.
4810
        var updatedConnReqs []*connmgr.ConnReq
3✔
4811
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4812
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4813

3✔
4814
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4815
                // If the existing connection request is using one of the
4816
                // latest advertised addresses for the peer then we add it to
4817
                // updatedConnReqs and remove the associated address from
4818
                // addrMap so that we don't recreate this connReq later on.
4819
                case true:
×
4820
                        updatedConnReqs = append(
×
4821
                                updatedConnReqs, connReq,
×
4822
                        )
×
4823
                        delete(addrMap, lnAddr)
×
4824

4825
                // If the existing connection request is using an address that
4826
                // is not one of the latest advertised addresses for the peer
4827
                // then we remove the connecting request from the connection
4828
                // manager.
4829
                case false:
3✔
4830
                        srvrLog.Info(
3✔
4831
                                "Removing conn req:", connReq.Addr.String(),
3✔
4832
                        )
3✔
4833
                        s.connMgr.Remove(connReq.ID())
3✔
4834
                }
4835
        }
4836

4837
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4838

3✔
4839
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4840
        if !ok {
6✔
4841
                cancelChan = make(chan struct{})
3✔
4842
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4843
        }
3✔
4844

4845
        // Any addresses left in addrMap are new ones that we have not made
4846
        // connection requests for. So create new connection requests for those.
4847
        // If there is more than one address in the address map, stagger the
4848
        // creation of the connection requests for those.
4849
        go func() {
6✔
4850
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4851
                defer ticker.Stop()
3✔
4852

3✔
4853
                for _, addr := range addrMap {
6✔
4854
                        // Send the persistent connection request to the
3✔
4855
                        // connection manager, saving the request itself so we
3✔
4856
                        // can cancel/restart the process as needed.
3✔
4857
                        connReq := &connmgr.ConnReq{
3✔
4858
                                Addr:      addr,
3✔
4859
                                Permanent: true,
3✔
4860
                        }
3✔
4861

3✔
4862
                        s.mu.Lock()
3✔
4863
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4864
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4865
                        )
3✔
4866
                        s.mu.Unlock()
3✔
4867

3✔
4868
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4869
                                "channel peer %v", addr)
3✔
4870

3✔
4871
                        go s.connMgr.Connect(connReq)
3✔
4872

3✔
4873
                        select {
3✔
4874
                        case <-s.quit:
3✔
4875
                                return
3✔
4876
                        case <-cancelChan:
3✔
4877
                                return
3✔
4878
                        case <-ticker.C:
3✔
4879
                        }
4880
                }
4881
        }()
4882
}
4883

4884
// removePeer removes the passed peer from the server's state of all active
4885
// peers.
4886
func (s *server) removePeer(p *peer.Brontide) {
3✔
4887
        if p == nil {
3✔
4888
                return
×
4889
        }
×
4890

4891
        srvrLog.Debugf("removing peer %v", p)
3✔
4892

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

3✔
4897
        // If this peer had an active persistent connection request, remove it.
3✔
4898
        if p.ConnReq() != nil {
6✔
4899
                s.connMgr.Remove(p.ConnReq().ID())
3✔
4900
        }
3✔
4901

4902
        // Ignore deleting peers if we're shutting down.
4903
        if s.Stopped() {
3✔
4904
                return
×
4905
        }
×
4906

4907
        pKey := p.PubKey()
3✔
4908
        pubSer := pKey[:]
3✔
4909
        pubStr := string(pubSer)
3✔
4910

3✔
4911
        delete(s.peersByPub, pubStr)
3✔
4912

3✔
4913
        if p.Inbound() {
6✔
4914
                delete(s.inboundPeers, pubStr)
3✔
4915
        } else {
6✔
4916
                delete(s.outboundPeers, pubStr)
3✔
4917
        }
3✔
4918

4919
        // Remove the peer's access permission from the access manager.
4920
        s.peerAccessMan.removePeerAccess(p.IdentityKey())
3✔
4921

3✔
4922
        // Copy the peer's error buffer across to the server if it has any items
3✔
4923
        // in it so that we can restore peer errors across connections.
3✔
4924
        if p.ErrorBuffer().Total() > 0 {
6✔
4925
                s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4926
        }
3✔
4927

4928
        // Inform the peer notifier of a peer offline event so that it can be
4929
        // reported to clients listening for peer events.
4930
        var pubKey [33]byte
3✔
4931
        copy(pubKey[:], pubSer)
3✔
4932

3✔
4933
        s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4934
}
4935

4936
// ConnectToPeer requests that the server connect to a Lightning Network peer
4937
// at the specified address. This function will *block* until either a
4938
// connection is established, or the initial handshake process fails.
4939
//
4940
// NOTE: This function is safe for concurrent access.
4941
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4942
        perm bool, timeout time.Duration) error {
3✔
4943

3✔
4944
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4945

3✔
4946
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4947
        // better granularity.  In certain conditions, this method requires
3✔
4948
        // making an outbound connection to a remote peer, which requires the
3✔
4949
        // lock to be released, and subsequently reacquired.
3✔
4950
        s.mu.Lock()
3✔
4951

3✔
4952
        // Ensure we're not already connected to this peer.
3✔
4953
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4954
        if err == nil {
6✔
4955
                s.mu.Unlock()
3✔
4956
                return &errPeerAlreadyConnected{peer: peer}
3✔
4957
        }
3✔
4958

4959
        // Peer was not found, continue to pursue connection with peer.
4960

4961
        // If there's already a pending connection request for this pubkey,
4962
        // then we ignore this request to ensure we don't create a redundant
4963
        // connection.
4964
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
4965
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
4966
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
4967
        }
3✔
4968

4969
        // If there's not already a pending or active connection to this node,
4970
        // then instruct the connection manager to attempt to establish a
4971
        // persistent connection to the peer.
4972
        srvrLog.Debugf("Connecting to %v", addr)
3✔
4973
        if perm {
6✔
4974
                connReq := &connmgr.ConnReq{
3✔
4975
                        Addr:      addr,
3✔
4976
                        Permanent: true,
3✔
4977
                }
3✔
4978

3✔
4979
                // Since the user requested a permanent connection, we'll set
3✔
4980
                // the entry to true which will tell the server to continue
3✔
4981
                // reconnecting even if the number of channels with this peer is
3✔
4982
                // zero.
3✔
4983
                s.persistentPeers[targetPub] = true
3✔
4984
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
4985
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
4986
                }
3✔
4987
                s.persistentConnReqs[targetPub] = append(
3✔
4988
                        s.persistentConnReqs[targetPub], connReq,
3✔
4989
                )
3✔
4990
                s.mu.Unlock()
3✔
4991

3✔
4992
                go s.connMgr.Connect(connReq)
3✔
4993

3✔
4994
                return nil
3✔
4995
        }
4996
        s.mu.Unlock()
3✔
4997

3✔
4998
        // If we're not making a persistent connection, then we'll attempt to
3✔
4999
        // connect to the target peer. If the we can't make the connection, or
3✔
5000
        // the crypto negotiation breaks down, then return an error to the
3✔
5001
        // caller.
3✔
5002
        errChan := make(chan error, 1)
3✔
5003
        s.connectToPeer(addr, errChan, timeout)
3✔
5004

3✔
5005
        select {
3✔
5006
        case err := <-errChan:
3✔
5007
                return err
3✔
5008
        case <-s.quit:
×
5009
                return ErrServerShuttingDown
×
5010
        }
5011
}
5012

5013
// connectToPeer establishes a connection to a remote peer. errChan is used to
5014
// notify the caller if the connection attempt has failed. Otherwise, it will be
5015
// closed.
5016
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5017
        errChan chan<- error, timeout time.Duration) {
3✔
5018

3✔
5019
        conn, err := brontide.Dial(
3✔
5020
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5021
        )
3✔
5022
        if err != nil {
6✔
5023
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5024
                select {
3✔
5025
                case errChan <- err:
3✔
5026
                case <-s.quit:
×
5027
                }
5028
                return
3✔
5029
        }
5030

5031
        close(errChan)
3✔
5032

3✔
5033
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5034
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5035

3✔
5036
        s.OutboundPeerConnected(nil, conn)
3✔
5037
}
5038

5039
// DisconnectPeer sends the request to server to close the connection with peer
5040
// identified by public key.
5041
//
5042
// NOTE: This function is safe for concurrent access.
5043
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5044
        pubBytes := pubKey.SerializeCompressed()
3✔
5045
        pubStr := string(pubBytes)
3✔
5046

3✔
5047
        s.mu.Lock()
3✔
5048
        defer s.mu.Unlock()
3✔
5049

3✔
5050
        // Check that were actually connected to this peer. If not, then we'll
3✔
5051
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5052
        // currently connected to.
3✔
5053
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5054
        if err == ErrPeerNotConnected {
6✔
5055
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5056
        }
3✔
5057

5058
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5059

3✔
5060
        s.cancelConnReqs(pubStr, nil)
3✔
5061

3✔
5062
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5063
        // them from this map so we don't attempt to re-connect after we
3✔
5064
        // disconnect.
3✔
5065
        delete(s.persistentPeers, pubStr)
3✔
5066
        delete(s.persistentPeersBackoff, pubStr)
3✔
5067

3✔
5068
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5069
        // removePeer, which bypassed the peerTerminationWatcher.
3✔
5070
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5071

3✔
5072
        return nil
3✔
5073
}
5074

5075
// OpenChannel sends a request to the server to open a channel to the specified
5076
// peer identified by nodeKey with the passed channel funding parameters.
5077
//
5078
// NOTE: This function is safe for concurrent access.
5079
func (s *server) OpenChannel(
5080
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5081

3✔
5082
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5083
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5084
        // not blocked if the caller is not reading the updates.
3✔
5085
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5086
        req.Err = make(chan error, 1)
3✔
5087

3✔
5088
        // First attempt to locate the target peer to open a channel with, if
3✔
5089
        // we're unable to locate the peer then this request will fail.
3✔
5090
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5091
        s.mu.RLock()
3✔
5092
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5093
        if !ok {
3✔
5094
                s.mu.RUnlock()
×
5095

×
5096
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5097
                return req.Updates, req.Err
×
5098
        }
×
5099
        req.Peer = peer
3✔
5100
        s.mu.RUnlock()
3✔
5101

3✔
5102
        // We'll wait until the peer is active before beginning the channel
3✔
5103
        // opening process.
3✔
5104
        select {
3✔
5105
        case <-peer.ActiveSignal():
3✔
5106
        case <-peer.QuitSignal():
×
5107
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5108
                return req.Updates, req.Err
×
5109
        case <-s.quit:
×
5110
                req.Err <- ErrServerShuttingDown
×
5111
                return req.Updates, req.Err
×
5112
        }
5113

5114
        // If the fee rate wasn't specified at this point we fail the funding
5115
        // because of the missing fee rate information. The caller of the
5116
        // `OpenChannel` method needs to make sure that default values for the
5117
        // fee rate are set beforehand.
5118
        if req.FundingFeePerKw == 0 {
3✔
5119
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5120
                        "the channel opening transaction")
×
5121

×
5122
                return req.Updates, req.Err
×
5123
        }
×
5124

5125
        // Spawn a goroutine to send the funding workflow request to the funding
5126
        // manager. This allows the server to continue handling queries instead
5127
        // of blocking on this request which is exported as a synchronous
5128
        // request to the outside world.
5129
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5130

3✔
5131
        return req.Updates, req.Err
3✔
5132
}
5133

5134
// Peers returns a slice of all active peers.
5135
//
5136
// NOTE: This function is safe for concurrent access.
5137
func (s *server) Peers() []*peer.Brontide {
3✔
5138
        s.mu.RLock()
3✔
5139
        defer s.mu.RUnlock()
3✔
5140

3✔
5141
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5142
        for _, peer := range s.peersByPub {
6✔
5143
                peers = append(peers, peer)
3✔
5144
        }
3✔
5145

5146
        return peers
3✔
5147
}
5148

5149
// computeNextBackoff uses a truncated exponential backoff to compute the next
5150
// backoff using the value of the exiting backoff. The returned duration is
5151
// randomized in either direction by 1/20 to prevent tight loops from
5152
// stabilizing.
5153
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5154
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5155
        nextBackoff := 2 * currBackoff
3✔
5156
        if nextBackoff > maxBackoff {
6✔
5157
                nextBackoff = maxBackoff
3✔
5158
        }
3✔
5159

5160
        // Using 1/10 of our duration as a margin, compute a random offset to
5161
        // avoid the nodes entering connection cycles.
5162
        margin := nextBackoff / 10
3✔
5163

3✔
5164
        var wiggle big.Int
3✔
5165
        wiggle.SetUint64(uint64(margin))
3✔
5166
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5167
                // Randomizing is not mission critical, so we'll just return the
×
5168
                // current backoff.
×
5169
                return nextBackoff
×
5170
        }
×
5171

5172
        // Otherwise add in our wiggle, but subtract out half of the margin so
5173
        // that the backoff can tweaked by 1/20 in either direction.
5174
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5175
}
5176

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

5181
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5182
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
5183
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5184
        if err != nil {
3✔
5185
                return nil, err
×
5186
        }
×
5187

5188
        node, err := s.graphDB.FetchLightningNode(vertex)
3✔
5189
        if err != nil {
6✔
5190
                return nil, err
3✔
5191
        }
3✔
5192

5193
        if len(node.Addresses) == 0 {
6✔
5194
                return nil, errNoAdvertisedAddr
3✔
5195
        }
3✔
5196

5197
        return node.Addresses, nil
3✔
5198
}
5199

5200
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5201
// channel update for a target channel.
5202
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5203
        *lnwire.ChannelUpdate1, error) {
3✔
5204

3✔
5205
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5206
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5207
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5208
                if err != nil {
6✔
5209
                        return nil, err
3✔
5210
                }
3✔
5211

5212
                return netann.ExtractChannelUpdate(
3✔
5213
                        ourPubKey[:], info, edge1, edge2,
3✔
5214
                )
3✔
5215
        }
5216
}
5217

5218
// applyChannelUpdate applies the channel update to the different sub-systems of
5219
// the server. The useAlias boolean denotes whether or not to send an alias in
5220
// place of the real SCID.
5221
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5222
        op *wire.OutPoint, useAlias bool) error {
3✔
5223

3✔
5224
        var (
3✔
5225
                peerAlias    *lnwire.ShortChannelID
3✔
5226
                defaultAlias lnwire.ShortChannelID
3✔
5227
        )
3✔
5228

3✔
5229
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5230

3✔
5231
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5232
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5233
        if useAlias {
6✔
5234
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5235
                if foundAlias != defaultAlias {
6✔
5236
                        peerAlias = &foundAlias
3✔
5237
                }
3✔
5238
        }
5239

5240
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5241
                update, discovery.RemoteAlias(peerAlias),
3✔
5242
        )
3✔
5243
        select {
3✔
5244
        case err := <-errChan:
3✔
5245
                return err
3✔
5246
        case <-s.quit:
×
5247
                return ErrServerShuttingDown
×
5248
        }
5249
}
5250

5251
// SendCustomMessage sends a custom message to the peer with the specified
5252
// pubkey.
5253
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5254
        data []byte) error {
3✔
5255

3✔
5256
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5257
        if err != nil {
3✔
5258
                return err
×
5259
        }
×
5260

5261
        // We'll wait until the peer is active.
5262
        select {
3✔
5263
        case <-peer.ActiveSignal():
3✔
5264
        case <-peer.QuitSignal():
×
5265
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5266
        case <-s.quit:
×
5267
                return ErrServerShuttingDown
×
5268
        }
5269

5270
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5271
        if err != nil {
6✔
5272
                return err
3✔
5273
        }
3✔
5274

5275
        // Send the message as low-priority. For now we assume that all
5276
        // application-defined message are low priority.
5277
        return peer.SendMessageLazy(true, msg)
3✔
5278
}
5279

5280
// newSweepPkScriptGen creates closure that generates a new public key script
5281
// which should be used to sweep any funds into the on-chain wallet.
5282
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5283
// (p2wkh) output.
5284
func newSweepPkScriptGen(
5285
        wallet lnwallet.WalletController,
5286
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5287

3✔
5288
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5289
                sweepAddr, err := wallet.NewAddress(
3✔
5290
                        lnwallet.TaprootPubkey, false,
3✔
5291
                        lnwallet.DefaultAccountName,
3✔
5292
                )
3✔
5293
                if err != nil {
3✔
5294
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5295
                }
×
5296

5297
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5298
                if err != nil {
3✔
5299
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5300
                }
×
5301

5302
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5303
                        wallet, netParams, addr,
3✔
5304
                )
3✔
5305
                if err != nil {
3✔
5306
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5307
                }
×
5308

5309
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5310
                        DeliveryAddress: addr,
3✔
5311
                        InternalKey:     internalKeyDesc,
3✔
5312
                })
3✔
5313
        }
5314
}
5315

5316
// shouldPeerBootstrap returns true if we should attempt to perform peer
5317
// bootstrapping to actively seek our peers using the set of active network
5318
// bootstrappers.
5319
func shouldPeerBootstrap(cfg *Config) bool {
3✔
5320
        isSimnet := cfg.Bitcoin.SimNet
3✔
5321
        isSignet := cfg.Bitcoin.SigNet
3✔
5322
        isRegtest := cfg.Bitcoin.RegTest
3✔
5323
        isDevNetwork := isSimnet || isSignet || isRegtest
3✔
5324

3✔
5325
        // TODO(yy): remove the check on simnet/regtest such that the itest is
3✔
5326
        // covering the bootstrapping process.
3✔
5327
        return !cfg.NoNetBootstrap && !isDevNetwork
3✔
5328
}
3✔
5329

5330
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5331
// finished.
5332
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5333
        // Get a list of closed channels.
3✔
5334
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5335
        if err != nil {
3✔
5336
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5337
                return nil
×
5338
        }
×
5339

5340
        // Save the SCIDs in a map.
5341
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5342
        for _, c := range channels {
6✔
5343
                // If the channel is not pending, its FC has been finalized.
3✔
5344
                if !c.IsPending {
6✔
5345
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5346
                }
3✔
5347
        }
5348

5349
        // Double check whether the reported closed channel has indeed finished
5350
        // closing.
5351
        //
5352
        // NOTE: There are misalignments regarding when a channel's FC is
5353
        // marked as finalized. We double check the pending channels to make
5354
        // sure the returned SCIDs are indeed terminated.
5355
        //
5356
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5357
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5358
        if err != nil {
3✔
5359
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5360
                return nil
×
5361
        }
×
5362

5363
        for _, c := range pendings {
6✔
5364
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5365
                        continue
3✔
5366
                }
5367

5368
                // If the channel is still reported as pending, remove it from
5369
                // the map.
5370
                delete(closedSCIDs, c.ShortChannelID)
×
5371

×
5372
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5373
                        c.ShortChannelID)
×
5374
        }
5375

5376
        return closedSCIDs
3✔
5377
}
5378

5379
// getStartingBeat returns the current beat. This is used during the startup to
5380
// initialize blockbeat consumers.
5381
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5382
        // beat is the current blockbeat.
3✔
5383
        var beat *chainio.Beat
3✔
5384

3✔
5385
        // We should get a notification with the current best block immediately
3✔
5386
        // by passing a nil block.
3✔
5387
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5388
        if err != nil {
3✔
5389
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5390
        }
×
5391
        defer blockEpochs.Cancel()
3✔
5392

3✔
5393
        // We registered for the block epochs with a nil request. The notifier
3✔
5394
        // should send us the current best block immediately. So we need to
3✔
5395
        // wait for it here because we need to know the current best height.
3✔
5396
        select {
3✔
5397
        case bestBlock := <-blockEpochs.Epochs:
3✔
5398
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5399
                        bestBlock.Hash, bestBlock.Height)
3✔
5400

3✔
5401
                // Update the current blockbeat.
3✔
5402
                beat = chainio.NewBeat(*bestBlock)
3✔
5403

5404
        case <-s.quit:
×
5405
                srvrLog.Debug("LND shutting down")
×
5406
        }
5407

5408
        return beat, nil
3✔
5409
}
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