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

lightningnetwork / lnd / 22762658126

06 Mar 2026 12:03PM UTC coverage: 62.235% (+0.03%) from 62.205%
22762658126

Pull #10065

github

web-flow
Merge a26765d44 into 6ea479189
Pull Request #10065: graph/db: async graph cache population

200 of 212 new or added lines in 6 files covered. (94.34%)

76 existing lines in 18 files now uncovered.

139787 of 224610 relevant lines covered (62.24%)

19628.27 hits per line

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

69.6
/server.go
1
package lnd
2

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

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

89
const (
90
        // defaultMinPeers is the minimum number of peers nodes should always be
91
        // connected to.
92
        defaultMinPeers = 3
93

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

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

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

112
        // multiAddrConnectionStagger is the number of seconds to wait between
113
        // attempting to a peer with each of its advertised addresses.
114
        multiAddrConnectionStagger = 10 * time.Second
115
)
116

117
var (
118
        // ErrPeerNotConnected signals that the server has no connection to the
119
        // given peer.
120
        ErrPeerNotConnected = errors.New("peer is not connected")
121

122
        // ErrServerNotActive indicates that the server has started but hasn't
123
        // fully finished the startup process.
124
        ErrServerNotActive = errors.New("server is still in the process of " +
125
                "starting")
126

127
        // ErrServerShuttingDown indicates that the server is in the process of
128
        // gracefully exiting.
129
        ErrServerShuttingDown = errors.New("server is shutting down")
130

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

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

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

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

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

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

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

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

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

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

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

195
// String returns a human-readable representation of the status code.
196
func (p peerAccessStatus) String() string {
3✔
197
        switch p {
3✔
198
        case peerStatusRestricted:
3✔
199
                return "restricted"
3✔
200

201
        case peerStatusTemporary:
3✔
202
                return "temporary"
3✔
203

204
        case peerStatusProtected:
3✔
205
                return "protected"
3✔
206

207
        default:
×
208
                return "unknown"
×
209
        }
210
}
211

212
// peerSlotStatus determines whether a peer gets access to one of our free
213
// slots or gets to bypass this safety mechanism.
214
type peerSlotStatus struct {
215
        // state determines which privileges the peer has with our server.
216
        state peerAccessStatus
217
}
218

219
// server is the main server of the Lightning Network Daemon. The server houses
220
// global state pertaining to the wallet, database, and the rpcserver.
221
// Additionally, the server is also used as a central messaging bus to interact
222
// with any of its companion objects.
223
type server struct {
224
        active   int32 // atomic
225
        stopping int32 // atomic
226

227
        start sync.Once
228
        stop  sync.Once
229

230
        cfg *Config
231

232
        implCfg *ImplementationCfg
233

234
        // identityECDH is an ECDH capable wrapper for the private key used
235
        // to authenticate any incoming connections.
236
        identityECDH keychain.SingleKeyECDH
237

238
        // identityKeyLoc is the key locator for the above wrapped identity key.
239
        identityKeyLoc keychain.KeyLocator
240

241
        // nodeSigner is an implementation of the MessageSigner implementation
242
        // that's backed by the identity private key of the running lnd node.
243
        nodeSigner *netann.NodeSigner
244

245
        chanStatusMgr *netann.ChanStatusManager
246

247
        // listenAddrs is the list of addresses the server is currently
248
        // listening on.
249
        listenAddrs []net.Addr
250

251
        // torController is a client that will communicate with a locally
252
        // running Tor server. This client will handle initiating and
253
        // authenticating the connection to the Tor server, automatically
254
        // creating and setting up onion services, etc.
255
        torController *tor.Controller
256

257
        // natTraversal is the specific NAT traversal technique used to
258
        // automatically set up port forwarding rules in order to advertise to
259
        // the network that the node is accepting inbound connections.
260
        natTraversal nat.Traversal
261

262
        // lastDetectedIP is the last IP detected by the NAT traversal technique
263
        // above. This IP will be watched periodically in a goroutine in order
264
        // to handle dynamic IP changes.
265
        lastDetectedIP net.IP
266

267
        mu sync.RWMutex
268

269
        // peersByPub is a map of the active peers.
270
        //
271
        // NOTE: The key used here is the raw bytes of the peer's public key to
272
        // string conversion, which means it cannot be printed using `%s` as it
273
        // will just print the binary.
274
        //
275
        // TODO(yy): Use the hex string instead.
276
        peersByPub map[string]*peer.Brontide
277

278
        inboundPeers  map[string]*peer.Brontide
279
        outboundPeers map[string]*peer.Brontide
280

281
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
282
        peerDisconnectedListeners map[string][]chan<- struct{}
283

284
        // TODO(yy): the Brontide.Start doesn't know this value, which means it
285
        // will continue to send messages even if there are no active channels
286
        // and the value below is false. Once it's pruned, all its connections
287
        // will be closed, thus the Brontide.Start will return an error.
288
        persistentPeers        map[string]bool
289
        persistentPeersBackoff map[string]time.Duration
290
        persistentPeerAddrs    map[string][]*lnwire.NetAddress
291
        persistentConnReqs     map[string][]*connmgr.ConnReq
292
        persistentRetryCancels map[string]chan struct{}
293

294
        // peerErrors keeps a set of peer error buffers for peers that have
295
        // disconnected from us. This allows us to track historic peer errors
296
        // over connections. The string of the peer's compressed pubkey is used
297
        // as a key for this map.
298
        peerErrors map[string]*queue.CircularBuffer
299

300
        // ignorePeerTermination tracks peers for which the server has initiated
301
        // a disconnect. Adding a peer to this map causes the peer termination
302
        // watcher to short circuit in the event that peers are purposefully
303
        // disconnected.
304
        ignorePeerTermination map[*peer.Brontide]struct{}
305

306
        // scheduledPeerConnection maps a pubkey string to a callback that
307
        // should be executed in the peerTerminationWatcher the prior peer with
308
        // the same pubkey exits.  This allows the server to wait until the
309
        // prior peer has cleaned up successfully, before adding the new peer
310
        // intended to replace it.
311
        scheduledPeerConnection map[string]func()
312

313
        // pongBuf is a shared pong reply buffer we'll use across all active
314
        // peer goroutines. We know the max size of a pong message
315
        // (lnwire.MaxPongBytes), so we can allocate this ahead of time, and
316
        // avoid allocations each time we need to send a pong message.
317
        pongBuf []byte
318

319
        cc *chainreg.ChainControl
320

321
        fundingMgr *funding.Manager
322

323
        graphDB *graphdb.ChannelGraph
324
        v1Graph *graphdb.VersionedGraph
325

326
        chanStateDB *channeldb.ChannelStateDB
327

328
        addrSource channeldb.AddrSource
329

330
        // miscDB is the DB that contains all "other" databases within the main
331
        // channel DB that haven't been separated out yet.
332
        miscDB *channeldb.DB
333

334
        invoicesDB invoices.InvoiceDB
335

336
        // paymentsDB is the DB that contains all functions for managing
337
        // payments.
338
        paymentsDB paymentsdb.DB
339

340
        aliasMgr *aliasmgr.Manager
341

342
        htlcSwitch *htlcswitch.Switch
343

344
        interceptableSwitch *htlcswitch.InterceptableSwitch
345

346
        invoices *invoices.InvoiceRegistry
347

348
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
349

350
        channelNotifier *channelnotifier.ChannelNotifier
351

352
        peerNotifier *peernotifier.PeerNotifier
353

354
        htlcNotifier *htlcswitch.HtlcNotifier
355

356
        witnessBeacon contractcourt.WitnessBeacon
357

358
        breachArbitrator *contractcourt.BreachArbitrator
359

360
        missionController *routing.MissionController
361
        defaultMC         *routing.MissionControl
362

363
        graphBuilder *graph.Builder
364

365
        chanRouter *routing.ChannelRouter
366

367
        controlTower routing.ControlTower
368

369
        authGossiper *discovery.AuthenticatedGossiper
370

371
        localChanMgr *localchans.Manager
372

373
        utxoNursery *contractcourt.UtxoNursery
374

375
        sweeper *sweep.UtxoSweeper
376

377
        chainArb *contractcourt.ChainArbitrator
378

379
        sphinx *hop.OnionProcessor
380

381
        towerClientMgr *wtclient.Manager
382

383
        connMgr *connmgr.ConnManager
384

385
        sigPool *lnwallet.SigPool
386

387
        writePool *pool.Write
388

389
        readPool *pool.Read
390

391
        tlsManager *TLSManager
392

393
        // featureMgr dispatches feature vectors for various contexts within the
394
        // daemon.
395
        featureMgr *feature.Manager
396

397
        // currentNodeAnn is the node announcement that has been broadcast to
398
        // the network upon startup, if the attributes of the node (us) has
399
        // changed since last start.
400
        currentNodeAnn *lnwire.NodeAnnouncement1
401

402
        // chansToRestore is the set of channels that upon starting, the server
403
        // should attempt to restore/recover.
404
        chansToRestore walletunlocker.ChannelsToRecover
405

406
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
407
        // backups are consistent at all times. It interacts with the
408
        // channelNotifier to be notified of newly opened and closed channels.
409
        chanSubSwapper *chanbackup.SubSwapper
410

411
        // chanEventStore tracks the behaviour of channels and their remote peers to
412
        // provide insights into their health and performance.
413
        chanEventStore *chanfitness.ChannelEventStore
414

415
        hostAnn *netann.HostAnnouncer
416

417
        // livenessMonitor monitors that lnd has access to critical resources.
418
        livenessMonitor *healthcheck.Monitor
419

420
        customMessageServer *subscribe.Server
421

422
        onionMessageServer *subscribe.Server
423

424
        // txPublisher is a publisher with fee-bumping capability.
425
        txPublisher *sweep.TxPublisher
426

427
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
428
        // of new blocks.
429
        blockbeatDispatcher *chainio.BlockbeatDispatcher
430

431
        // peerAccessMan implements peer access controls.
432
        peerAccessMan *accessMan
433

434
        quit chan struct{}
435

436
        wg sync.WaitGroup
437
}
438

439
// updatePersistentPeerAddrs subscribes to topology changes and stores
440
// advertised addresses for any NodeAnnouncements from our persisted peers.
441
func (s *server) updatePersistentPeerAddrs() error {
3✔
442
        graphSub, err := s.graphDB.SubscribeTopology()
3✔
443
        if err != nil {
3✔
444
                return err
×
445
        }
×
446

447
        s.wg.Add(1)
3✔
448
        go func() {
6✔
449
                defer func() {
6✔
450
                        graphSub.Cancel()
3✔
451
                        s.wg.Done()
3✔
452
                }()
3✔
453

454
                for {
6✔
455
                        select {
3✔
456
                        case <-s.quit:
3✔
457
                                return
3✔
458

459
                        case topChange, ok := <-graphSub.TopologyChanges:
3✔
460
                                // If the router is shutting down, then we will
3✔
461
                                // as well.
3✔
462
                                if !ok {
3✔
463
                                        return
×
464
                                }
×
465

466
                                for _, update := range topChange.NodeUpdates {
6✔
467
                                        pubKeyStr := string(
3✔
468
                                                update.IdentityKey.
3✔
469
                                                        SerializeCompressed(),
3✔
470
                                        )
3✔
471

3✔
472
                                        // We only care about updates from
3✔
473
                                        // our persistentPeers.
3✔
474
                                        s.mu.RLock()
3✔
475
                                        _, ok := s.persistentPeers[pubKeyStr]
3✔
476
                                        s.mu.RUnlock()
3✔
477
                                        if !ok {
6✔
478
                                                continue
3✔
479
                                        }
480

481
                                        addrs := make([]*lnwire.NetAddress, 0,
3✔
482
                                                len(update.Addresses))
3✔
483

3✔
484
                                        for _, addr := range update.Addresses {
6✔
485
                                                addrs = append(addrs,
3✔
486
                                                        &lnwire.NetAddress{
3✔
487
                                                                IdentityKey: update.IdentityKey,
3✔
488
                                                                Address:     addr,
3✔
489
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
490
                                                        },
3✔
491
                                                )
3✔
492
                                        }
3✔
493

494
                                        s.mu.Lock()
3✔
495

3✔
496
                                        // Update the stored addresses for this
3✔
497
                                        // to peer to reflect the new set.
3✔
498
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
3✔
499

3✔
500
                                        // If there are no outstanding
3✔
501
                                        // connection requests for this peer
3✔
502
                                        // then our work is done since we are
3✔
503
                                        // not currently trying to connect to
3✔
504
                                        // them.
3✔
505
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
6✔
506
                                                s.mu.Unlock()
3✔
507
                                                continue
3✔
508
                                        }
509

510
                                        s.mu.Unlock()
3✔
511

3✔
512
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
513
                                }
514
                        }
515
                }
516
        }()
517

518
        return nil
3✔
519
}
520

521
// CustomMessage is a custom message that is received from a peer.
522
type CustomMessage struct {
523
        // Peer is the peer pubkey
524
        Peer [33]byte
525

526
        // Msg is the custom wire message.
527
        Msg *lnwire.Custom
528
}
529

530
// parseAddr parses an address from its string format to a net.Addr.
531
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
3✔
532
        var (
3✔
533
                host string
3✔
534
                port int
3✔
535
        )
3✔
536

3✔
537
        // Split the address into its host and port components.
3✔
538
        h, p, err := net.SplitHostPort(address)
3✔
539
        if err != nil {
3✔
540
                // If a port wasn't specified, we'll assume the address only
×
541
                // contains the host so we'll use the default port.
×
542
                host = address
×
543
                port = defaultPeerPort
×
544
        } else {
3✔
545
                // Otherwise, we'll note both the host and ports.
3✔
546
                host = h
3✔
547
                portNum, err := strconv.Atoi(p)
3✔
548
                if err != nil {
3✔
549
                        return nil, err
×
550
                }
×
551
                port = portNum
3✔
552
        }
553

554
        if tor.IsOnionHost(host) {
3✔
555
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
556
        }
×
557

558
        // If the host is part of a TCP address, we'll use the network
559
        // specific ResolveTCPAddr function in order to resolve these
560
        // addresses over Tor in order to prevent leaking your real IP
561
        // address.
562
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
3✔
563
        return netCfg.ResolveTCPAddr("tcp", hostPort)
3✔
564
}
565

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

3✔
571
        return func(a net.Addr) (net.Conn, error) {
6✔
572
                lnAddr := a.(*lnwire.NetAddress)
3✔
573
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
574
        }
3✔
575
}
576

577
// newServer creates a new instance of the server which is to listen using the
578
// passed listener address.
579
//
580
//nolint:funlen
581
func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr,
582
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
583
        nodeKeyDesc *keychain.KeyDescriptor,
584
        chansToRestore walletunlocker.ChannelsToRecover,
585
        chanPredicate chanacceptor.ChannelAcceptor,
586
        torController *tor.Controller, tlsManager *TLSManager,
587
        leaderElector cluster.LeaderElector,
588
        implCfg *ImplementationCfg) (*server, error) {
3✔
589

3✔
590
        var (
3✔
591
                err         error
3✔
592
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
593

3✔
594
                // We just derived the full descriptor, so we know the public
3✔
595
                // key is set on it.
3✔
596
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
3✔
597
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
3✔
598
                )
3✔
599
        )
3✔
600

3✔
601
        netParams := cfg.ActiveNetParams.Params
3✔
602

3✔
603
        // Initialize the sphinx router.
3✔
604
        replayLog := htlcswitch.NewDecayedLog(
3✔
605
                dbs.DecayedLogDB, cc.ChainNotifier,
3✔
606
        )
3✔
607
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
3✔
608

3✔
609
        writeBufferPool := pool.NewWriteBuffer(
3✔
610
                pool.DefaultWriteBufferGCInterval,
3✔
611
                pool.DefaultWriteBufferExpiryInterval,
3✔
612
        )
3✔
613

3✔
614
        writePool := pool.NewWrite(
3✔
615
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
616
        )
3✔
617

3✔
618
        readBufferPool := pool.NewReadBuffer(
3✔
619
                pool.DefaultReadBufferGCInterval,
3✔
620
                pool.DefaultReadBufferExpiryInterval,
3✔
621
        )
3✔
622

3✔
623
        readPool := pool.NewRead(
3✔
624
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
625
        )
3✔
626

3✔
627
        // If the taproot overlay flag is set, but we don't have an aux funding
3✔
628
        // controller, then we'll exit as this is incompatible.
3✔
629
        if cfg.ProtocolOptions.TaprootOverlayChans &&
3✔
630
                implCfg.AuxFundingController.IsNone() {
3✔
631

×
632
                return nil, fmt.Errorf("taproot overlay flag set, but " +
×
633
                        "overlay channels are not supported " +
×
634
                        "in a standalone lnd build")
×
635
        }
×
636

637
        //nolint:ll
638
        featureMgr, err := feature.NewManager(feature.Config{
3✔
639
                NoTLVOnion:                   cfg.ProtocolOptions.LegacyOnion(),
3✔
640
                NoStaticRemoteKey:            cfg.ProtocolOptions.NoStaticRemoteKey(),
3✔
641
                NoAnchors:                    cfg.ProtocolOptions.NoAnchorCommitments(),
3✔
642
                NoWumbo:                      !cfg.ProtocolOptions.Wumbo(),
3✔
643
                NoScriptEnforcementLease:     cfg.ProtocolOptions.NoScriptEnforcementLease(),
3✔
644
                NoKeysend:                    !cfg.AcceptKeySend,
3✔
645
                NoOptionScidAlias:            !cfg.ProtocolOptions.ScidAlias(),
3✔
646
                NoZeroConf:                   !cfg.ProtocolOptions.ZeroConf(),
3✔
647
                NoAnySegwit:                  cfg.ProtocolOptions.NoAnySegwit(),
3✔
648
                CustomFeatures:               cfg.ProtocolOptions.CustomFeatures(),
3✔
649
                NoTaprootChans:               !cfg.ProtocolOptions.TaprootChans,
3✔
650
                NoTaprootOverlay:             !cfg.ProtocolOptions.TaprootOverlayChans,
3✔
651
                NoRouteBlinding:              cfg.ProtocolOptions.NoRouteBlinding(),
3✔
652
                NoExperimentalAccountability: cfg.ProtocolOptions.NoExpAccountability(),
3✔
653
                NoQuiescence:                 cfg.ProtocolOptions.NoQuiescence(),
3✔
654
                NoRbfCoopClose:               !cfg.ProtocolOptions.RbfCoopClose,
3✔
655
        })
3✔
656
        if err != nil {
3✔
657
                return nil, err
×
658
        }
×
659

660
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
661
        registryConfig := invoices.RegistryConfig{
3✔
662
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
663
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
664
                Clock:                       clock.NewDefaultClock(),
3✔
665
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
666
                AcceptAMP:                   cfg.AcceptAMP,
3✔
667
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
668
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
669
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
670
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
671
        }
3✔
672

3✔
673
        v1Graph := graphdb.NewVersionedGraph(
3✔
674
                dbs.GraphDB, lnwire.GossipVersion1,
3✔
675
        )
3✔
676

3✔
677
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, v1Graph)
3✔
678

3✔
679
        s := &server{
3✔
680
                cfg:            cfg,
3✔
681
                implCfg:        implCfg,
3✔
682
                graphDB:        dbs.GraphDB,
3✔
683
                v1Graph:        v1Graph,
3✔
684
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
685
                addrSource:     addrSource,
3✔
686
                miscDB:         dbs.ChanStateDB,
3✔
687
                invoicesDB:     dbs.InvoiceDB,
3✔
688
                paymentsDB:     dbs.PaymentsDB,
3✔
689
                cc:             cc,
3✔
690
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
691
                writePool:      writePool,
3✔
692
                readPool:       readPool,
3✔
693
                chansToRestore: chansToRestore,
3✔
694

3✔
695
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
696
                        cc.ChainNotifier,
3✔
697
                ),
3✔
698
                channelNotifier: channelnotifier.New(
3✔
699
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
700
                ),
3✔
701

3✔
702
                identityECDH:   nodeKeyECDH,
3✔
703
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
704
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
705

3✔
706
                listenAddrs: listenAddrs,
3✔
707

3✔
708
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
709
                // schedule
3✔
710
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
711

3✔
712
                torController: torController,
3✔
713

3✔
714
                persistentPeers:         make(map[string]bool),
3✔
715
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
716
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
717
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
718
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
719
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
720
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
721
                scheduledPeerConnection: make(map[string]func()),
3✔
722
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
723

3✔
724
                peersByPub:                make(map[string]*peer.Brontide),
3✔
725
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
726
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
727
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
728
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
729

3✔
730
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
731

3✔
732
                customMessageServer: subscribe.NewServer(),
3✔
733

3✔
734
                onionMessageServer: subscribe.NewServer(),
3✔
735

3✔
736
                tlsManager: tlsManager,
3✔
737

3✔
738
                featureMgr: featureMgr,
3✔
739
                quit:       make(chan struct{}),
3✔
740
        }
3✔
741

3✔
742
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
743
        if err != nil {
3✔
744
                return nil, err
×
745
        }
×
746

747
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
748
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
749
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
750
        )
3✔
751
        s.invoices = invoices.NewRegistry(
3✔
752
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
753
        )
3✔
754

3✔
755
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
756

3✔
757
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
758
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
759

3✔
760
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
761
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
762
                if err != nil {
3✔
763
                        return err
×
764
                }
×
765

766
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
767

3✔
768
                return nil
3✔
769
        }
770

771
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
772
        if err != nil {
3✔
773
                return nil, err
×
774
        }
×
775

776
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
777
                DB:                   dbs.ChanStateDB,
3✔
778
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
779
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
780
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
781
                LocalChannelClose: func(pubKey []byte,
3✔
782
                        request *htlcswitch.ChanClose) {
6✔
783

3✔
784
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
785
                        if err != nil {
3✔
786
                                srvrLog.Errorf("unable to close channel, peer"+
×
787
                                        " with %v id can't be found: %v",
×
788
                                        pubKey, err,
×
789
                                )
×
790
                                return
×
791
                        }
×
792

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

828
        s.witnessBeacon = newPreimageBeacon(
3✔
829
                dbs.ChanStateDB.NewWitnessCache(),
3✔
830
                s.interceptableSwitch.ForwardPacket,
3✔
831
        )
3✔
832

3✔
833
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
834
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
835
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
836
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
837
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
838
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
839
                MessageSigner:            s.nodeSigner,
3✔
840
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
841
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
842
                DB:                       s.chanStateDB,
3✔
843
                Graph:                    dbs.GraphDB,
3✔
844
        }
3✔
845

3✔
846
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
847
        if err != nil {
3✔
848
                return nil, err
×
849
        }
×
850
        s.chanStatusMgr = chanStatusMgr
3✔
851

3✔
852
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
853
        // port forwarding for users behind a NAT.
3✔
854
        if cfg.NAT {
3✔
855
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
856

×
857
                discoveryTimeout := time.Duration(10 * time.Second)
×
858

×
859
                ctx, cancel := context.WithTimeout(
×
860
                        context.Background(), discoveryTimeout,
×
861
                )
×
862
                defer cancel()
×
863
                upnp, err := nat.DiscoverUPnP(ctx)
×
864
                if err == nil {
×
865
                        s.natTraversal = upnp
×
866
                } else {
×
867
                        // If we were not able to discover a UPnP enabled device
×
868
                        // on the local network, we'll fall back to attempting
×
869
                        // to discover a NAT-PMP enabled device.
×
870
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
871
                                "device on the local network: %v", err)
×
872

×
873
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
874
                                "enabled device")
×
875

×
876
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
877
                        if err != nil {
×
878
                                err := fmt.Errorf("unable to discover a "+
×
879
                                        "NAT-PMP enabled device on the local "+
×
880
                                        "network: %v", err)
×
881
                                srvrLog.Error(err)
×
882
                                return nil, err
×
883
                        }
×
884

885
                        s.natTraversal = pmp
×
886
                }
887
        }
888

889
        nodePubKey := route.NewVertex(nodeKeyDesc.PubKey)
3✔
890
        // Set the self node which represents our node in the graph.
3✔
891
        err = s.setSelfNode(ctx, nodePubKey, listenAddrs)
3✔
892
        if err != nil {
3✔
893
                return nil, err
×
894
        }
×
895

896
        // The router will get access to the payment ID sequencer, such that it
897
        // can generate unique payment IDs.
898
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
899
        if err != nil {
3✔
900
                return nil, err
×
901
        }
×
902

903
        // Instantiate mission control with config from the sub server.
904
        //
905
        // TODO(joostjager): When we are further in the process of moving to sub
906
        // servers, the mission control instance itself can be moved there too.
907
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
908

3✔
909
        // We only initialize a probability estimator if there's no custom one.
3✔
910
        var estimator routing.Estimator
3✔
911
        if cfg.Estimator != nil {
3✔
912
                estimator = cfg.Estimator
×
913
        } else {
3✔
914
                switch routingConfig.ProbabilityEstimatorType {
3✔
915
                case routing.AprioriEstimatorName:
3✔
916
                        aCfg := routingConfig.AprioriConfig
3✔
917
                        aprioriConfig := routing.AprioriConfig{
3✔
918
                                AprioriHopProbability: aCfg.HopProbability,
3✔
919
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
920
                                AprioriWeight:         aCfg.Weight,
3✔
921
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
922
                        }
3✔
923

3✔
924
                        estimator, err = routing.NewAprioriEstimator(
3✔
925
                                aprioriConfig,
3✔
926
                        )
3✔
927
                        if err != nil {
3✔
928
                                return nil, err
×
929
                        }
×
930

931
                case routing.BimodalEstimatorName:
×
932
                        bCfg := routingConfig.BimodalConfig
×
933
                        bimodalConfig := routing.BimodalConfig{
×
934
                                BimodalNodeWeight: bCfg.NodeWeight,
×
935
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
936
                                        bCfg.Scale,
×
937
                                ),
×
938
                                BimodalDecayTime: bCfg.DecayTime,
×
939
                        }
×
940

×
941
                        estimator, err = routing.NewBimodalEstimator(
×
942
                                bimodalConfig,
×
943
                        )
×
944
                        if err != nil {
×
945
                                return nil, err
×
946
                        }
×
947

948
                default:
×
949
                        return nil, fmt.Errorf("unknown estimator type %v",
×
950
                                routingConfig.ProbabilityEstimatorType)
×
951
                }
952
        }
953

954
        mcCfg := &routing.MissionControlConfig{
3✔
955
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
956
                Estimator:               estimator,
3✔
957
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
958
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
959
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
960
        }
3✔
961

3✔
962
        s.missionController, err = routing.NewMissionController(
3✔
963
                dbs.ChanStateDB, nodePubKey, mcCfg,
3✔
964
        )
3✔
965
        if err != nil {
3✔
966
                return nil, fmt.Errorf("can't create mission control "+
×
967
                        "manager: %w", err)
×
968
        }
×
969
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
970
                routing.DefaultMissionControlNamespace,
3✔
971
        )
3✔
972
        if err != nil {
3✔
973
                return nil, fmt.Errorf("can't create mission control in the "+
×
974
                        "default namespace: %w", err)
×
975
        }
×
976

977
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
978
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
979
                int64(routingConfig.AttemptCost),
3✔
980
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
981
                routingConfig.MinRouteProbability)
3✔
982

3✔
983
        pathFindingConfig := routing.PathFindingConfig{
3✔
984
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
985
                        routingConfig.AttemptCost,
3✔
986
                ),
3✔
987
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
988
                MinProbability: routingConfig.MinRouteProbability,
3✔
989
        }
3✔
990

3✔
991
        sourceNode, err := s.v1Graph.SourceNode(ctx)
3✔
992
        if err != nil {
3✔
993
                return nil, fmt.Errorf("error getting source node: %w", err)
×
994
        }
×
995
        paymentSessionSource := &routing.SessionSource{
3✔
996
                GraphSessionFactory: dbs.GraphDB,
3✔
997
                SourceNode:          sourceNode,
3✔
998
                MissionControl:      s.defaultMC,
3✔
999
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1000
                PathFindingConfig:   pathFindingConfig,
3✔
1001
        }
3✔
1002

3✔
1003
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
3✔
1004

3✔
1005
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1006
                cfg.Routing.StrictZombiePruning
3✔
1007

3✔
1008
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1009
                SelfNode:            nodePubKey,
3✔
1010
                Graph:               dbs.GraphDB,
3✔
1011
                Chain:               cc.ChainIO,
3✔
1012
                ChainView:           cc.ChainView,
3✔
1013
                Notifier:            cc.ChainNotifier,
3✔
1014
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1015
                GraphPruneInterval:  time.Hour,
3✔
1016
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1017
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1018
                StrictZombiePruning: strictPruning,
3✔
1019
                IsAlias:             aliasmgr.IsAlias,
3✔
1020
        })
3✔
1021
        if err != nil {
3✔
1022
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1023
        }
×
1024

1025
        s.chanRouter, err = routing.New(routing.Config{
3✔
1026
                SelfNode:                  nodePubKey,
3✔
1027
                RoutingGraph:              dbs.GraphDB,
3✔
1028
                Chain:                     cc.ChainIO,
3✔
1029
                Payer:                     s.htlcSwitch,
3✔
1030
                Control:                   s.controlTower,
3✔
1031
                MissionControl:            s.defaultMC,
3✔
1032
                SessionSource:             paymentSessionSource,
3✔
1033
                GetLink:                   s.htlcSwitch.GetLinkByShortID,
3✔
1034
                NextPaymentID:             sequencer.NextID,
3✔
1035
                PathFindingConfig:         pathFindingConfig,
3✔
1036
                Clock:                     clock.NewDefaultClock(),
3✔
1037
                ApplyChannelUpdate:        s.graphBuilder.ApplyChannelUpdate,
3✔
1038
                ClosedSCIDs:               s.fetchClosedChannelSCIDs(),
3✔
1039
                TrafficShaper:             implCfg.TrafficShaper,
3✔
1040
                KeepFailedPaymentAttempts: cfg.KeepFailedPaymentAttempts,
3✔
1041
        })
3✔
1042
        if err != nil {
3✔
1043
                return nil, fmt.Errorf("can't create router: %w", err)
×
1044
        }
×
1045

1046
        chanSeries := discovery.NewChanSeries(
3✔
1047
                graphdb.NewVersionedGraph(s.graphDB, lnwire.GossipVersion1),
3✔
1048
        )
3✔
1049
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1050
        if err != nil {
3✔
1051
                return nil, err
×
1052
        }
×
1053
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1054
        if err != nil {
3✔
1055
                return nil, err
×
1056
        }
×
1057

1058
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1059

3✔
1060
        s.authGossiper = discovery.New(discovery.Config{
3✔
1061
                Graph:                 s.graphBuilder,
3✔
1062
                ChainIO:               s.cc.ChainIO,
3✔
1063
                Notifier:              s.cc.ChainNotifier,
3✔
1064
                ChainParams:           s.cfg.ActiveNetParams.Params,
3✔
1065
                Broadcast:             s.BroadcastMessage,
3✔
1066
                ChanSeries:            chanSeries,
3✔
1067
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1068
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1069
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1070
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement1,
3✔
1071
                        error) {
3✔
1072

×
1073
                        return s.genNodeAnnouncement(nil)
×
1074
                },
×
1075
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1076
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1077
                RetransmitTicker:        ticker.New(time.Minute * 30),
1078
                RebroadcastInterval:     time.Hour * 24,
1079
                WaitingProofStore:       waitingProofStore,
1080
                MessageStore:            gossipMessageStore,
1081
                AnnSigner:               s.nodeSigner,
1082
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1083
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1084
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1085
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1086
                MinimumBatchSize:        10,
1087
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1088
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1089
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1090
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1091
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1092
                IsAlias:                 aliasmgr.IsAlias,
1093
                SignAliasUpdate:         s.signAliasUpdate,
1094
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1095
                GetAlias:                s.aliasMgr.GetPeerAlias,
1096
                FindChannel:             s.findChannel,
1097
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1098
                ScidCloser:              scidCloserMan,
1099
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1100
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1101
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1102
                FilterConcurrency:       cfg.Gossip.FilterConcurrency,
1103
                BanThreshold:            cfg.Gossip.BanThreshold,
1104
                PeerMsgRateBytes:        cfg.Gossip.PeerMsgRateBytes,
1105
        }, nodeKeyDesc)
1106

1107
        accessCfg := &accessManConfig{
3✔
1108
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1109
                        error) {
6✔
1110

3✔
1111
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1112
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1113
                                genesisHash[:],
3✔
1114
                        )
3✔
1115
                },
3✔
1116
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1117
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1118
        }
1119

1120
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1121
        if err != nil {
3✔
1122
                return nil, err
×
1123
        }
×
1124

1125
        s.peerAccessMan = peerAccessMan
3✔
1126

3✔
1127
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1128
        //nolint:ll
3✔
1129
        s.localChanMgr = &localchans.Manager{
3✔
1130
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1131
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1132
                ForAllOutgoingChannels: func(ctx context.Context,
3✔
1133
                        cb func(*models.ChannelEdgeInfo,
3✔
1134
                                *models.ChannelEdgePolicy) error,
3✔
1135
                        reset func()) error {
6✔
1136

3✔
1137
                        return s.v1Graph.ForEachNodeChannel(
3✔
1138
                                ctx, selfVertex,
3✔
1139
                                func(c *models.ChannelEdgeInfo,
3✔
1140
                                        e *models.ChannelEdgePolicy,
3✔
1141
                                        _ *models.ChannelEdgePolicy) error {
6✔
1142

3✔
1143
                                        // NOTE: The invoked callback here may
3✔
1144
                                        // receive a nil channel policy.
3✔
1145
                                        return cb(c, e)
3✔
1146
                                }, reset,
3✔
1147
                        )
1148
                },
1149
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1150
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1151
                FetchChannel:              s.chanStateDB.FetchChannel,
1152
                AddEdge: func(ctx context.Context,
1153
                        edge *models.ChannelEdgeInfo) error {
×
1154

×
1155
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1156
                },
×
1157
        }
1158

1159
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1160
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1161
        )
3✔
1162
        if err != nil {
3✔
1163
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1164
                return nil, err
×
1165
        }
×
1166

1167
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1168
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1169
        )
3✔
1170
        if err != nil {
3✔
1171
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1172
                return nil, err
×
1173
        }
×
1174

1175
        aggregator := sweep.NewBudgetAggregator(
3✔
1176
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1177
                s.implCfg.AuxSweeper,
3✔
1178
        )
3✔
1179

3✔
1180
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1181
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1182
                Wallet:     cc.Wallet,
3✔
1183
                Estimator:  cc.FeeEstimator,
3✔
1184
                Notifier:   cc.ChainNotifier,
3✔
1185
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1186
        })
3✔
1187

3✔
1188
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1189
                FeeEstimator: cc.FeeEstimator,
3✔
1190
                GenSweepScript: newSweepPkScriptGen(
3✔
1191
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1192
                ),
3✔
1193
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1194
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1195
                Mempool:              cc.MempoolNotifier,
3✔
1196
                Notifier:             cc.ChainNotifier,
3✔
1197
                Store:                sweeperStore,
3✔
1198
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1199
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1200
                Aggregator:           aggregator,
3✔
1201
                Publisher:            s.txPublisher,
3✔
1202
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1203
        })
3✔
1204

3✔
1205
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1206
                ChainIO:             cc.ChainIO,
3✔
1207
                ConfDepth:           1,
3✔
1208
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1209
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1210
                Notifier:            cc.ChainNotifier,
3✔
1211
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1212
                Store:               utxnStore,
3✔
1213
                SweepInput:          s.sweeper.SweepInput,
3✔
1214
                Budget:              s.cfg.Sweeper.Budget,
3✔
1215
        })
3✔
1216

3✔
1217
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1218
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1219
                closureType contractcourt.ChannelCloseType) {
6✔
1220
                // TODO(conner): Properly respect the update and error channels
3✔
1221
                // returned by CloseLink.
3✔
1222

3✔
1223
                // Instruct the switch to close the channel.  Provide no close out
3✔
1224
                // delivery script or target fee per kw because user input is not
3✔
1225
                // available when the remote peer closes the channel.
3✔
1226
                s.htlcSwitch.CloseLink(
3✔
1227
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1228
                )
3✔
1229
        }
3✔
1230

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

3✔
1235
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1236
                &contractcourt.BreachConfig{
3✔
1237
                        CloseLink: closeLink,
3✔
1238
                        DB:        s.chanStateDB,
3✔
1239
                        Estimator: s.cc.FeeEstimator,
3✔
1240
                        GenSweepScript: newSweepPkScriptGen(
3✔
1241
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1242
                        ),
3✔
1243
                        Notifier:           cc.ChainNotifier,
3✔
1244
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1245
                        ContractBreaches:   contractBreaches,
3✔
1246
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1247
                        Store: contractcourt.NewRetributionStore(
3✔
1248
                                dbs.ChanStateDB,
3✔
1249
                        ),
3✔
1250
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1251
                },
3✔
1252
        )
3✔
1253

3✔
1254
        //nolint:ll
3✔
1255
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1256
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1257
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1258
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1259
                NewSweepAddr: func() ([]byte, error) {
3✔
1260
                        addr, err := newSweepPkScriptGen(
×
1261
                                cc.Wallet, netParams,
×
1262
                        )().Unpack()
×
1263
                        if err != nil {
×
1264
                                return nil, err
×
1265
                        }
×
1266

1267
                        return addr.DeliveryAddress, nil
×
1268
                },
1269
                PublishTx: cc.Wallet.PublishTransaction,
1270
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1271
                        for _, msg := range msgs {
6✔
1272
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1273
                                if err != nil {
3✔
1274
                                        return err
×
1275
                                }
×
1276
                        }
1277
                        return nil
3✔
1278
                },
1279
                IncubateOutputs: func(chanPoint wire.OutPoint,
1280
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1281
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1282
                        broadcastHeight uint32,
1283
                        deadlineHeight fn.Option[int32]) error {
3✔
1284

3✔
1285
                        return s.utxoNursery.IncubateOutputs(
3✔
1286
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1287
                                broadcastHeight, deadlineHeight,
3✔
1288
                        )
3✔
1289
                },
3✔
1290
                PreimageDB:   s.witnessBeacon,
1291
                Notifier:     cc.ChainNotifier,
1292
                Mempool:      cc.MempoolNotifier,
1293
                Signer:       cc.Wallet.Cfg.Signer,
1294
                FeeEstimator: cc.FeeEstimator,
1295
                ChainIO:      cc.ChainIO,
1296
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1297
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1298
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1299
                        return nil
3✔
1300
                },
3✔
1301
                IsOurAddress: cc.Wallet.IsOurAddress,
1302
                ContractBreach: func(chanPoint wire.OutPoint,
1303
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1304

3✔
1305
                        // processACK will handle the BreachArbitrator ACKing
3✔
1306
                        // the event.
3✔
1307
                        finalErr := make(chan error, 1)
3✔
1308
                        processACK := func(brarErr error) {
6✔
1309
                                if brarErr != nil {
3✔
1310
                                        finalErr <- brarErr
×
1311
                                        return
×
1312
                                }
×
1313

1314
                                // If the BreachArbitrator successfully handled
1315
                                // the event, we can signal that the handoff
1316
                                // was successful.
1317
                                finalErr <- nil
3✔
1318
                        }
1319

1320
                        event := &contractcourt.ContractBreachEvent{
3✔
1321
                                ChanPoint:         chanPoint,
3✔
1322
                                ProcessACK:        processACK,
3✔
1323
                                BreachRetribution: breachRet,
3✔
1324
                        }
3✔
1325

3✔
1326
                        // Send the contract breach event to the
3✔
1327
                        // BreachArbitrator.
3✔
1328
                        select {
3✔
1329
                        case contractBreaches <- event:
3✔
1330
                        case <-s.quit:
×
1331
                                return ErrServerShuttingDown
×
1332
                        }
1333

1334
                        // We'll wait for a final error to be available from
1335
                        // the BreachArbitrator.
1336
                        select {
3✔
1337
                        case err := <-finalErr:
3✔
1338
                                return err
3✔
1339
                        case <-s.quit:
×
1340
                                return ErrServerShuttingDown
×
1341
                        }
1342
                },
1343
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1344
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1345
                },
3✔
1346
                Sweeper:                       s.sweeper,
1347
                Registry:                      s.invoices,
1348
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1349
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1350
                OnionProcessor:                s.sphinx,
1351
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1352
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1353
                Clock:                         clock.NewDefaultClock(),
1354
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1355
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1356
                HtlcNotifier:                  s.htlcNotifier,
1357
                Budget:                        *s.cfg.Sweeper.Budget,
1358

1359
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1360
                QueryIncomingCircuit: func(
1361
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1362

3✔
1363
                        // Get the circuit map.
3✔
1364
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1365

3✔
1366
                        // Lookup the outgoing circuit.
3✔
1367
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1368
                        if pc == nil {
5✔
1369
                                return nil
2✔
1370
                        }
2✔
1371

1372
                        return &pc.Incoming
3✔
1373
                },
1374
                AuxLeafStore: implCfg.AuxLeafStore,
1375
                AuxSigner:    implCfg.AuxSigner,
1376
                AuxResolver:  implCfg.AuxContractResolver,
1377
                AuxCloser: fn.MapOption(
1378
                        func(c chcl.AuxChanCloser) contractcourt.AuxChanCloser {
×
1379
                                return c
×
1380
                        },
×
1381
                )(implCfg.AuxChanCloser),
1382
                ChannelCloseConfs: s.cfg.Dev.ChannelCloseConfs(),
1383
        }, dbs.ChanStateDB)
1384

1385
        // Select the configuration and funding parameters for Bitcoin.
1386
        chainCfg := cfg.Bitcoin
3✔
1387
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1388
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1389

3✔
1390
        var chanIDSeed [32]byte
3✔
1391
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1392
                return nil, err
×
1393
        }
×
1394

1395
        // Wrap the DeleteChannelEdges method so that the funding manager can
1396
        // use it without depending on several layers of indirection.
1397
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1398
                *models.ChannelEdgePolicy, error) {
6✔
1399

3✔
1400
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1401
                        context.TODO(), scid.ToUint64(),
3✔
1402
                )
3✔
1403
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1404
                        // This is unlikely but there is a slim chance of this
×
1405
                        // being hit if lnd was killed via SIGKILL and the
×
1406
                        // funding manager was stepping through the delete
×
1407
                        // alias edge logic.
×
1408
                        return nil, nil
×
1409
                } else if err != nil {
3✔
1410
                        return nil, err
×
1411
                }
×
1412

1413
                // Grab our key to find our policy.
1414
                var ourKey [33]byte
3✔
1415
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1416

3✔
1417
                var ourPolicy *models.ChannelEdgePolicy
3✔
1418
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1419
                        ourPolicy = e1
3✔
1420
                } else {
6✔
1421
                        ourPolicy = e2
3✔
1422
                }
3✔
1423

1424
                if ourPolicy == nil {
3✔
1425
                        // Something is wrong, so return an error.
×
1426
                        return nil, fmt.Errorf("we don't have an edge")
×
1427
                }
×
1428

1429
                err = s.v1Graph.DeleteChannelEdges(
3✔
1430
                        context.TODO(), false, false, scid.ToUint64(),
3✔
1431
                )
3✔
1432
                return ourPolicy, err
3✔
1433
        }
1434

1435
        // For the reservationTimeout and the zombieSweeperInterval different
1436
        // values are set in case we are in a dev environment so enhance test
1437
        // capacilities.
1438
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1439
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1440

3✔
1441
        // Get the development config for funding manager. If we are not in
3✔
1442
        // development mode, this would be nil.
3✔
1443
        var devCfg *funding.DevConfig
3✔
1444
        if lncfg.IsDevBuild() {
6✔
1445
                devCfg = &funding.DevConfig{
3✔
1446
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1447
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1448
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1449
                }
3✔
1450

3✔
1451
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1452
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1453

3✔
1454
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1455
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1456
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1457
        }
3✔
1458

1459
        // Attempt to parse the provided upfront-shutdown address (if any).
1460
        script, err := chcl.ParseUpfrontShutdownAddress(
3✔
1461
                cfg.UpfrontShutdownAddr, cfg.ActiveNetParams.Params,
3✔
1462
        )
3✔
1463
        if err != nil {
3✔
1464
                return nil, fmt.Errorf("error parsing upfront shutdown: %w",
×
1465
                        err)
×
1466
        }
×
1467

1468
        //nolint:ll
1469
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1470
                Dev:                devCfg,
3✔
1471
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1472
                IDKey:              nodeKeyDesc.PubKey,
3✔
1473
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1474
                Wallet:             cc.Wallet,
3✔
1475
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1476
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1477
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1478
                },
3✔
1479
                Notifier:     cc.ChainNotifier,
1480
                ChannelDB:    s.chanStateDB,
1481
                FeeEstimator: cc.FeeEstimator,
1482
                SignMessage:  cc.MsgSigner.SignMessage,
1483
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement1,
1484
                        error) {
3✔
1485

3✔
1486
                        return s.genNodeAnnouncement(nil)
3✔
1487
                },
3✔
1488
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1489
                NotifyWhenOnline:     s.NotifyWhenOnline,
1490
                TempChanIDSeed:       chanIDSeed,
1491
                FindChannel:          s.findChannel,
1492
                DefaultRoutingPolicy: cc.RoutingPolicy,
1493
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1494
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1495
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1496
                        // In case the user has explicitly specified
3✔
1497
                        // a default value for the number of
3✔
1498
                        // confirmations, we use it.
3✔
1499
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1500
                        if defaultConf != 0 {
6✔
1501
                                return defaultConf
3✔
1502
                        }
3✔
1503

1504
                        // Otherwise, scale the number of confirmations based on
1505
                        // the channel amount and push amount. For large
1506
                        // channels we increase the number of
1507
                        // confirmations we require for the channel to be
1508
                        // considered open. As it is always the
1509
                        // responder that gets to choose value, the
1510
                        // pushAmt is value being pushed to us. This
1511
                        // means we have more to lose in the case this
1512
                        // gets re-orged out, and we will require more
1513
                        // confirmations before we consider it open.
1514
                        return lnwallet.FundingConfsForAmounts(chanAmt, pushAmt)
×
1515
                },
1516
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1517
                        // We scale the remote CSV delay (the time the
3✔
1518
                        // remote have to claim funds in case of a unilateral
3✔
1519
                        // close) linearly from minRemoteDelay blocks
3✔
1520
                        // for small channels, to maxRemoteDelay blocks
3✔
1521
                        // for channels of size MaxFundingAmount.
3✔
1522

3✔
1523
                        // In case the user has explicitly specified
3✔
1524
                        // a default value for the remote delay, we
3✔
1525
                        // use it.
3✔
1526
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1527
                        if defaultDelay > 0 {
6✔
1528
                                return defaultDelay
3✔
1529
                        }
3✔
1530

1531
                        // If this is a wumbo channel, then we'll require the
1532
                        // max value.
1533
                        if chanAmt > MaxFundingAmount {
×
1534
                                return maxRemoteDelay
×
1535
                        }
×
1536

1537
                        // If not we scale according to channel size.
1538
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1539
                                chanAmt / MaxFundingAmount)
×
1540
                        if delay < minRemoteDelay {
×
1541
                                delay = minRemoteDelay
×
1542
                        }
×
1543
                        if delay > maxRemoteDelay {
×
1544
                                delay = maxRemoteDelay
×
1545
                        }
×
1546
                        return delay
×
1547
                },
1548
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1549
                        peerKey *btcec.PublicKey) error {
3✔
1550

3✔
1551
                        // First, we'll mark this new peer as a persistent peer
3✔
1552
                        // for re-connection purposes. If the peer is not yet
3✔
1553
                        // tracked or the user hasn't requested it to be perm,
3✔
1554
                        // we'll set false to prevent the server from continuing
3✔
1555
                        // to connect to this peer even if the number of
3✔
1556
                        // channels with this peer is zero.
3✔
1557
                        s.mu.Lock()
3✔
1558
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1559
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1560
                                s.persistentPeers[pubStr] = false
3✔
1561
                        }
3✔
1562
                        s.mu.Unlock()
3✔
1563

3✔
1564
                        // With that taken care of, we'll send this channel to
3✔
1565
                        // the chain arb so it can react to on-chain events.
3✔
1566
                        return s.chainArb.WatchNewChannel(channel)
3✔
1567
                },
1568
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1569
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1570
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1571
                },
3✔
1572
                RequiredRemoteChanReserve: func(chanAmt,
1573
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1574

3✔
1575
                        // By default, we'll require the remote peer to maintain
3✔
1576
                        // at least 1% of the total channel capacity at all
3✔
1577
                        // times. If this value ends up dipping below the dust
3✔
1578
                        // limit, then we'll use the dust limit itself as the
3✔
1579
                        // reserve as required by BOLT #2.
3✔
1580
                        reserve := chanAmt / 100
3✔
1581
                        if reserve < dustLimit {
6✔
1582
                                reserve = dustLimit
3✔
1583
                        }
3✔
1584

1585
                        return reserve
3✔
1586
                },
1587
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1588
                        // By default, we'll allow the remote peer to fully
3✔
1589
                        // utilize the full bandwidth of the channel, minus our
3✔
1590
                        // required reserve.
3✔
1591
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1592
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1593
                },
3✔
1594
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1595
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1596
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1597
                        }
3✔
1598

1599
                        // By default, we'll permit them to utilize the full
1600
                        // channel bandwidth.
1601
                        return uint16(input.MaxHTLCNumber / 2)
×
1602
                },
1603
                ZombieSweeperInterval:         zombieSweeperInterval,
1604
                ReservationTimeout:            reservationTimeout,
1605
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1606
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1607
                MaxPendingChannels:            cfg.MaxPendingChannels,
1608
                RejectPush:                    cfg.RejectPush,
1609
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1610
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1611
                OpenChannelPredicate:          chanPredicate,
1612
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1613
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1614
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1615
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1616
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1617
                DeleteAliasEdge:      deleteAliasEdge,
1618
                AliasManager:         s.aliasMgr,
1619
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1620
                AuxFundingController: implCfg.AuxFundingController,
1621
                AuxSigner:            implCfg.AuxSigner,
1622
                AuxResolver:          implCfg.AuxContractResolver,
1623
                AuxChannelNegotiator: implCfg.AuxChannelNegotiator,
1624
                ShutdownScript:       peer.ChooseAddr(script),
1625
        })
1626
        if err != nil {
3✔
1627
                return nil, err
×
1628
        }
×
1629

1630
        // Next, we'll assemble the sub-system that will maintain an on-disk
1631
        // static backup of the latest channel state.
1632
        chanNotifier := &channelNotifier{
3✔
1633
                chanNotifier: s.channelNotifier,
3✔
1634
                addrs:        s.addrSource,
3✔
1635
        }
3✔
1636
        backupFile := chanbackup.NewMultiFile(
3✔
1637
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1638
        )
3✔
1639
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1640
                ctx, s.chanStateDB, s.addrSource,
3✔
1641
        )
3✔
1642
        if err != nil {
3✔
1643
                return nil, err
×
1644
        }
×
1645
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1646
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1647
        )
3✔
1648
        if err != nil {
3✔
1649
                return nil, err
×
1650
        }
×
1651

1652
        // Assemble a peer notifier which will provide clients with subscriptions
1653
        // to peer online and offline events.
1654
        s.peerNotifier = peernotifier.New()
3✔
1655

3✔
1656
        // Create a channel event store which monitors all open channels.
3✔
1657
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1658
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1659
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1660
                },
3✔
1661
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1662
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1663
                },
3✔
1664
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1665
                Clock:           clock.NewDefaultClock(),
1666
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1667
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1668
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1669
        })
1670

1671
        if cfg.WtClient.Active {
6✔
1672
                policy := wtpolicy.DefaultPolicy()
3✔
1673
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1674

3✔
1675
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1676
                // protocol operations on sat/kw.
3✔
1677
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1678
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1679
                )
3✔
1680

3✔
1681
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1682

3✔
1683
                if err := policy.Validate(); err != nil {
3✔
1684
                        return nil, err
×
1685
                }
×
1686

1687
                // authDial is the wrapper around the btrontide.Dial for the
1688
                // watchtower.
1689
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1690
                        netAddr *lnwire.NetAddress,
3✔
1691
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1692

3✔
1693
                        return brontide.Dial(
3✔
1694
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1695
                        )
3✔
1696
                }
3✔
1697

1698
                // buildBreachRetribution is a call-back that can be used to
1699
                // query the BreachRetribution info and channel type given a
1700
                // channel ID and commitment height.
1701
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1702
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1703
                        channeldb.ChannelType, error) {
6✔
1704

3✔
1705
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1706
                                nil, chanID,
3✔
1707
                        )
3✔
1708
                        if err != nil {
3✔
1709
                                return nil, 0, err
×
1710
                        }
×
1711

1712
                        br, err := lnwallet.NewBreachRetribution(
3✔
1713
                                channel, commitHeight, 0, nil,
3✔
1714
                                implCfg.AuxLeafStore,
3✔
1715
                                implCfg.AuxContractResolver,
3✔
1716
                        )
3✔
1717
                        if err != nil {
3✔
1718
                                return nil, 0, err
×
1719
                        }
×
1720

1721
                        return br, channel.ChanType, nil
3✔
1722
                }
1723

1724
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1725

3✔
1726
                // Copy the policy for legacy channels and set the blob flag
3✔
1727
                // signalling support for anchor channels.
3✔
1728
                anchorPolicy := policy
3✔
1729
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1730

3✔
1731
                // Copy the policy for legacy channels and set the blob flag
3✔
1732
                // signalling support for taproot channels.
3✔
1733
                taprootPolicy := policy
3✔
1734
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1735
                        blob.FlagTaprootChannel,
3✔
1736
                )
3✔
1737

3✔
1738
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1739
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1740
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1741
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1742
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1743
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1744
                                error) {
6✔
1745

3✔
1746
                                return s.channelNotifier.
3✔
1747
                                        SubscribeChannelEvents()
3✔
1748
                        },
3✔
1749
                        Signer: cc.Wallet.Cfg.Signer,
1750
                        NewAddress: func() ([]byte, error) {
3✔
1751
                                addr, err := newSweepPkScriptGen(
3✔
1752
                                        cc.Wallet, netParams,
3✔
1753
                                )().Unpack()
3✔
1754
                                if err != nil {
3✔
1755
                                        return nil, err
×
1756
                                }
×
1757

1758
                                return addr.DeliveryAddress, nil
3✔
1759
                        },
1760
                        SecretKeyRing:      s.cc.KeyRing,
1761
                        Dial:               cfg.net.Dial,
1762
                        AuthDial:           authDial,
1763
                        DB:                 dbs.TowerClientDB,
1764
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1765
                        MinBackoff:         10 * time.Second,
1766
                        MaxBackoff:         5 * time.Minute,
1767
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1768
                }, policy, anchorPolicy, taprootPolicy)
1769
                if err != nil {
3✔
1770
                        return nil, err
×
1771
                }
×
1772
        }
1773

1774
        if len(cfg.ExternalHosts) != 0 {
3✔
1775
                advertisedIPs := make(map[string]struct{})
×
1776
                for _, addr := range s.currentNodeAnn.Addresses {
×
1777
                        advertisedIPs[addr.String()] = struct{}{}
×
1778
                }
×
1779

1780
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1781
                        Hosts:         cfg.ExternalHosts,
×
1782
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1783
                        LookupHost: func(host string) (net.Addr, error) {
×
1784
                                return lncfg.ParseAddressString(
×
1785
                                        host, strconv.Itoa(defaultPeerPort),
×
1786
                                        cfg.net.ResolveTCPAddr,
×
1787
                                )
×
1788
                        },
×
1789
                        AdvertisedIPs: advertisedIPs,
1790
                        AnnounceNewIPs: netann.IPAnnouncer(
1791
                                func(modifier ...netann.NodeAnnModifier) (
1792
                                        lnwire.NodeAnnouncement1, error) {
×
1793

×
1794
                                        return s.genNodeAnnouncement(
×
1795
                                                nil, modifier...,
×
1796
                                        )
×
1797
                                }),
×
1798
                })
1799
        }
1800

1801
        // Create liveness monitor.
1802
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1803

3✔
1804
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1805
        for i, listenAddr := range listenAddrs {
6✔
1806
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1807
                // doesn't need to call the general lndResolveTCP function
3✔
1808
                // since we are resolving a local address.
3✔
1809

3✔
1810
                // RESOLVE: We are actually partially accepting inbound
3✔
1811
                // connection requests when we call NewListener.
3✔
1812
                listeners[i], err = brontide.NewListener(
3✔
1813
                        nodeKeyECDH, listenAddr.String(),
3✔
1814
                        // TODO(yy): remove this check and unify the inbound
3✔
1815
                        // connection check inside `InboundPeerConnected`.
3✔
1816
                        s.peerAccessMan.checkAcceptIncomingConn,
3✔
1817
                )
3✔
1818
                if err != nil {
3✔
1819
                        return nil, err
×
1820
                }
×
1821
        }
1822

1823
        // Create the connection manager which will be responsible for
1824
        // maintaining persistent outbound connections and also accepting new
1825
        // incoming connections
1826
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1827
                Listeners:      listeners,
3✔
1828
                OnAccept:       s.InboundPeerConnected,
3✔
1829
                RetryDuration:  time.Second * 5,
3✔
1830
                TargetOutbound: 100,
3✔
1831
                Dial: noiseDial(
3✔
1832
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1833
                ),
3✔
1834
                OnConnection: s.OutboundPeerConnected,
3✔
1835
        })
3✔
1836
        if err != nil {
3✔
1837
                return nil, err
×
1838
        }
×
1839
        s.connMgr = cmgr
3✔
1840

3✔
1841
        // Finally, register the subsystems in blockbeat.
3✔
1842
        s.registerBlockConsumers()
3✔
1843

3✔
1844
        return s, nil
3✔
1845
}
1846

1847
// UpdateRoutingConfig is a callback function to update the routing config
1848
// values in the main cfg.
1849
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1850
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1851

3✔
1852
        switch c := cfg.Estimator.Config().(type) {
3✔
1853
        case routing.AprioriConfig:
3✔
1854
                routerCfg.ProbabilityEstimatorType =
3✔
1855
                        routing.AprioriEstimatorName
3✔
1856

3✔
1857
                targetCfg := routerCfg.AprioriConfig
3✔
1858
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1859
                targetCfg.Weight = c.AprioriWeight
3✔
1860
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1861
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1862

1863
        case routing.BimodalConfig:
3✔
1864
                routerCfg.ProbabilityEstimatorType =
3✔
1865
                        routing.BimodalEstimatorName
3✔
1866

3✔
1867
                targetCfg := routerCfg.BimodalConfig
3✔
1868
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1869
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1870
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1871
        }
1872

1873
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1874
}
1875

1876
// registerBlockConsumers registers the subsystems that consume block events.
1877
// By calling `RegisterQueue`, a list of subsystems are registered in the
1878
// blockbeat for block notifications. When a new block arrives, the subsystems
1879
// in the same queue are notified sequentially, and different queues are
1880
// notified concurrently.
1881
//
1882
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1883
// a new `RegisterQueue` call.
1884
func (s *server) registerBlockConsumers() {
3✔
1885
        // In this queue, when a new block arrives, it will be received and
3✔
1886
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
1887
        consumers := []chainio.Consumer{
3✔
1888
                s.chainArb,
3✔
1889
                s.sweeper,
3✔
1890
                s.txPublisher,
3✔
1891
        }
3✔
1892
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
1893
}
3✔
1894

1895
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1896
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1897
// may differ from what is on disk.
1898
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1899
        error) {
3✔
1900

3✔
1901
        data, err := u.DataToSign()
3✔
1902
        if err != nil {
3✔
1903
                return nil, err
×
1904
        }
×
1905

1906
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1907
}
1908

1909
// createLivenessMonitor creates a set of health checks using our configured
1910
// values and uses these checks to create a liveness monitor. Available
1911
// health checks,
1912
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1913
//   - diskCheck
1914
//   - tlsHealthCheck
1915
//   - torController, only created when tor is enabled.
1916
//
1917
// If a health check has been disabled by setting attempts to 0, our monitor
1918
// will not run it.
1919
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1920
        leaderElector cluster.LeaderElector) {
3✔
1921

3✔
1922
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1923
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1924
                srvrLog.Info("Disabling chain backend checks for " +
×
1925
                        "nochainbackend mode")
×
1926

×
1927
                chainBackendAttempts = 0
×
1928
        }
×
1929

1930
        chainHealthCheck := healthcheck.NewObservation(
3✔
1931
                "chain backend",
3✔
1932
                cc.HealthCheck,
3✔
1933
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1934
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1935
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1936
                chainBackendAttempts,
3✔
1937
        )
3✔
1938

3✔
1939
        diskCheck := healthcheck.NewObservation(
3✔
1940
                "disk space",
3✔
1941
                func() error {
3✔
1942
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1943
                                cfg.LndDir,
×
1944
                        )
×
1945
                        if err != nil {
×
1946
                                return err
×
1947
                        }
×
1948

1949
                        // If we have more free space than we require,
1950
                        // we return a nil error.
1951
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1952
                                return nil
×
1953
                        }
×
1954

1955
                        return fmt.Errorf("require: %v free space, got: %v",
×
1956
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1957
                                free)
×
1958
                },
1959
                cfg.HealthChecks.DiskCheck.Interval,
1960
                cfg.HealthChecks.DiskCheck.Timeout,
1961
                cfg.HealthChecks.DiskCheck.Backoff,
1962
                cfg.HealthChecks.DiskCheck.Attempts,
1963
        )
1964

1965
        tlsHealthCheck := healthcheck.NewObservation(
3✔
1966
                "tls",
3✔
1967
                func() error {
3✔
1968
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1969
                                s.cc.KeyRing,
×
1970
                        )
×
1971
                        if err != nil {
×
1972
                                return err
×
1973
                        }
×
1974
                        if expired {
×
1975
                                return fmt.Errorf("TLS certificate is "+
×
1976
                                        "expired as of %v", expTime)
×
1977
                        }
×
1978

1979
                        // If the certificate is not outdated, no error needs
1980
                        // to be returned
1981
                        return nil
×
1982
                },
1983
                cfg.HealthChecks.TLSCheck.Interval,
1984
                cfg.HealthChecks.TLSCheck.Timeout,
1985
                cfg.HealthChecks.TLSCheck.Backoff,
1986
                cfg.HealthChecks.TLSCheck.Attempts,
1987
        )
1988

1989
        checks := []*healthcheck.Observation{
3✔
1990
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
1991
        }
3✔
1992

3✔
1993
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
1994
        if s.torController != nil {
3✔
1995
                torConnectionCheck := healthcheck.NewObservation(
×
1996
                        "tor connection",
×
1997
                        func() error {
×
1998
                                return healthcheck.CheckTorServiceStatus(
×
1999
                                        s.torController,
×
2000
                                        func() error {
×
2001
                                                return s.createNewHiddenService(
×
2002
                                                        context.TODO(),
×
2003
                                                )
×
2004
                                        },
×
2005
                                )
2006
                        },
2007
                        cfg.HealthChecks.TorConnection.Interval,
2008
                        cfg.HealthChecks.TorConnection.Timeout,
2009
                        cfg.HealthChecks.TorConnection.Backoff,
2010
                        cfg.HealthChecks.TorConnection.Attempts,
2011
                )
2012
                checks = append(checks, torConnectionCheck)
×
2013
        }
2014

2015
        // If remote signing is enabled, add the healthcheck for the remote
2016
        // signing RPC interface.
2017
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2018
                // Because we have two cascading timeouts here, we need to add
3✔
2019
                // some slack to the "outer" one of them in case the "inner"
3✔
2020
                // returns exactly on time.
3✔
2021
                overhead := time.Millisecond * 10
3✔
2022

3✔
2023
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2024
                        "remote signer connection",
3✔
2025
                        rpcwallet.HealthCheck(
3✔
2026
                                s.cfg.RemoteSigner,
3✔
2027

3✔
2028
                                // For the health check we might to be even
3✔
2029
                                // stricter than the initial/normal connect, so
3✔
2030
                                // we use the health check timeout here.
3✔
2031
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2032
                        ),
3✔
2033
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2034
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2035
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2036
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2037
                )
3✔
2038
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2039
        }
3✔
2040

2041
        // If we have a leader elector, we add a health check to ensure we are
2042
        // still the leader. During normal operation, we should always be the
2043
        // leader, but there are circumstances where this may change, such as
2044
        // when we lose network connectivity for long enough expiring out lease.
2045
        if leaderElector != nil {
3✔
2046
                leaderCheck := healthcheck.NewObservation(
×
2047
                        "leader status",
×
2048
                        func() error {
×
2049
                                // Check if we are still the leader. Note that
×
2050
                                // we don't need to use a timeout context here
×
2051
                                // as the healthcheck observer will handle the
×
2052
                                // timeout case for us.
×
2053
                                timeoutCtx, cancel := context.WithTimeout(
×
2054
                                        context.Background(),
×
2055
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2056
                                )
×
2057
                                defer cancel()
×
2058

×
2059
                                leader, err := leaderElector.IsLeader(
×
2060
                                        timeoutCtx,
×
2061
                                )
×
2062
                                if err != nil {
×
2063
                                        return fmt.Errorf("unable to check if "+
×
2064
                                                "still leader: %v", err)
×
2065
                                }
×
2066

2067
                                if !leader {
×
2068
                                        srvrLog.Debug("Not the current leader")
×
2069
                                        return fmt.Errorf("not the current " +
×
2070
                                                "leader")
×
2071
                                }
×
2072

2073
                                return nil
×
2074
                        },
2075
                        cfg.HealthChecks.LeaderCheck.Interval,
2076
                        cfg.HealthChecks.LeaderCheck.Timeout,
2077
                        cfg.HealthChecks.LeaderCheck.Backoff,
2078
                        cfg.HealthChecks.LeaderCheck.Attempts,
2079
                )
2080

2081
                checks = append(checks, leaderCheck)
×
2082
        }
2083

2084
        // If we have not disabled all of our health checks, we create a
2085
        // liveness monitor with our configured checks.
2086
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2087
                &healthcheck.Config{
3✔
2088
                        Checks:   checks,
3✔
2089
                        Shutdown: srvrLog.Criticalf,
3✔
2090
                },
3✔
2091
        )
3✔
2092
}
2093

2094
// Started returns true if the server has been started, and false otherwise.
2095
// NOTE: This function is safe for concurrent access.
2096
func (s *server) Started() bool {
3✔
2097
        return atomic.LoadInt32(&s.active) != 0
3✔
2098
}
3✔
2099

2100
// cleaner is used to aggregate "cleanup" functions during an operation that
2101
// starts several subsystems. In case one of the subsystem fails to start
2102
// and a proper resource cleanup is required, the "run" method achieves this
2103
// by running all these added "cleanup" functions.
2104
type cleaner []func() error
2105

2106
// add is used to add a cleanup function to be called when
2107
// the run function is executed.
2108
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2109
        return append(c, cleanup)
3✔
2110
}
3✔
2111

2112
// run is used to run all the previousely added cleanup functions.
2113
func (c cleaner) run() {
×
2114
        for i := len(c) - 1; i >= 0; i-- {
×
2115
                if err := c[i](); err != nil {
×
2116
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2117
                }
×
2118
        }
2119
}
2120

2121
// Start starts the main daemon server, all requested listeners, and any helper
2122
// goroutines.
2123
// NOTE: This function is safe for concurrent access.
2124
//
2125
//nolint:funlen
2126
func (s *server) Start(ctx context.Context) error {
3✔
2127
        var startErr error
3✔
2128

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

3✔
2134
        s.start.Do(func() {
6✔
2135
                // Before starting any subsystems, repair any link nodes that
3✔
2136
                // may have been incorrectly pruned due to the race condition
3✔
2137
                // that was fixed in the link node pruning logic. This must
3✔
2138
                // happen before the chain arbitrator and other subsystems load
3✔
2139
                // channels, to ensure the invariant "link node exists iff
3✔
2140
                // channels exist" is maintained.
3✔
2141
                err := s.chanStateDB.RepairLinkNodes(s.cfg.ActiveNetParams.Net)
3✔
2142
                if err != nil {
3✔
2143
                        srvrLog.Errorf("Failed to repair link nodes: %v", err)
×
2144

×
2145
                        startErr = err
×
2146

×
2147
                        return
×
2148
                }
×
2149

2150
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2151
                if err := s.customMessageServer.Start(); err != nil {
3✔
2152
                        startErr = err
×
2153
                        return
×
2154
                }
×
2155

2156
                cleanup = cleanup.add(s.onionMessageServer.Stop)
3✔
2157
                if err := s.onionMessageServer.Start(); err != nil {
3✔
2158
                        startErr = err
×
2159
                        return
×
2160
                }
×
2161

2162
                if s.hostAnn != nil {
3✔
2163
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2164
                        if err := s.hostAnn.Start(); err != nil {
×
2165
                                startErr = err
×
2166
                                return
×
2167
                        }
×
2168
                }
2169

2170
                if s.livenessMonitor != nil {
6✔
2171
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2172
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
2173
                                startErr = err
×
2174
                                return
×
2175
                        }
×
2176
                }
2177

2178
                // Start the notification server. This is used so channel
2179
                // management goroutines can be notified when a funding
2180
                // transaction reaches a sufficient number of confirmations, or
2181
                // when the input for the funding transaction is spent in an
2182
                // attempt at an uncooperative close by the counterparty.
2183
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2184
                if err := s.sigPool.Start(); err != nil {
3✔
2185
                        startErr = err
×
2186
                        return
×
2187
                }
×
2188

2189
                cleanup = cleanup.add(s.writePool.Stop)
3✔
2190
                if err := s.writePool.Start(); err != nil {
3✔
2191
                        startErr = err
×
2192
                        return
×
2193
                }
×
2194

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

2201
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2202
                if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2203
                        startErr = err
×
2204
                        return
×
2205
                }
×
2206

2207
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
2208
                if err := s.cc.BestBlockTracker.Start(); err != nil {
3✔
2209
                        startErr = err
×
2210
                        return
×
2211
                }
×
2212

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

2219
                cleanup = cleanup.add(func() error {
3✔
2220
                        return s.peerNotifier.Stop()
×
2221
                })
×
2222
                if err := s.peerNotifier.Start(); err != nil {
3✔
2223
                        startErr = err
×
2224
                        return
×
2225
                }
×
2226

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

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

2241
                beat, err := s.getStartingBeat()
3✔
2242
                if err != nil {
3✔
2243
                        startErr = err
×
2244
                        return
×
2245
                }
×
2246

2247
                cleanup = cleanup.add(s.txPublisher.Stop)
3✔
2248
                if err := s.txPublisher.Start(beat); err != nil {
3✔
2249
                        startErr = err
×
2250
                        return
×
2251
                }
×
2252

2253
                cleanup = cleanup.add(s.sweeper.Stop)
3✔
2254
                if err := s.sweeper.Start(beat); err != nil {
3✔
2255
                        startErr = err
×
2256
                        return
×
2257
                }
×
2258

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

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

2271
                cleanup = cleanup.add(s.fundingMgr.Stop)
3✔
2272
                if err := s.fundingMgr.Start(); err != nil {
3✔
2273
                        startErr = err
×
2274
                        return
×
2275
                }
×
2276

2277
                // htlcSwitch must be started before chainArb since the latter
2278
                // relies on htlcSwitch to deliver resolution message upon
2279
                // start.
2280
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2281
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2282
                        startErr = err
×
2283
                        return
×
2284
                }
×
2285

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

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

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

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

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

2316
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2317
                if err := s.chanRouter.Start(); err != nil {
3✔
2318
                        startErr = err
×
2319
                        return
×
2320
                }
×
2321
                // The authGossiper depends on the chanRouter and therefore
2322
                // should be started after it.
2323
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2324
                if err := s.authGossiper.Start(); err != nil {
3✔
2325
                        startErr = err
×
2326
                        return
×
2327
                }
×
2328

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

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

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

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

2353
                cleanup.add(func() error {
3✔
2354
                        s.missionController.StopStoreTickers()
×
2355
                        return nil
×
2356
                })
×
2357
                s.missionController.RunStoreTickers()
3✔
2358

3✔
2359
                // Before we start the connMgr, we'll check to see if we have
3✔
2360
                // any backups to recover. We do this now as we want to ensure
3✔
2361
                // that have all the information we need to handle channel
3✔
2362
                // recovery _before_ we even accept connections from any peers.
3✔
2363
                chanRestorer := &chanDBRestorer{
3✔
2364
                        db:         s.chanStateDB,
3✔
2365
                        secretKeys: s.cc.KeyRing,
3✔
2366
                        chainArb:   s.chainArb,
3✔
2367
                }
3✔
2368
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2369
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2370
                                s.chansToRestore.PackedSingleChanBackups,
×
2371
                                s.cc.KeyRing, chanRestorer, s,
×
2372
                        )
×
2373
                        if err != nil {
×
2374
                                startErr = fmt.Errorf("unable to unpack single "+
×
2375
                                        "backups: %v", err)
×
2376
                                return
×
2377
                        }
×
2378
                }
2379
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2380
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2381
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2382
                                s.cc.KeyRing, chanRestorer, s,
3✔
2383
                        )
3✔
2384
                        if err != nil {
3✔
2385
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2386
                                        "backup: %v", err)
×
2387
                                return
×
2388
                        }
×
2389
                }
2390

2391
                // chanSubSwapper must be started after the `channelNotifier`
2392
                // because it depends on channel events as a synchronization
2393
                // point.
2394
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2395
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2396
                        startErr = err
×
2397
                        return
×
2398
                }
×
2399

2400
                if s.torController != nil {
3✔
2401
                        cleanup = cleanup.add(s.torController.Stop)
×
2402
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2403
                                startErr = err
×
2404
                                return
×
2405
                        }
×
2406
                }
2407

2408
                if s.natTraversal != nil {
3✔
2409
                        s.wg.Add(1)
×
2410
                        go s.watchExternalIP()
×
2411
                }
×
2412

2413
                // Start connmgr last to prevent connections before init.
2414
                cleanup = cleanup.add(func() error {
3✔
2415
                        s.connMgr.Stop()
×
2416
                        return nil
×
2417
                })
×
2418

2419
                // RESOLVE: s.connMgr.Start() is called here, but
2420
                // brontide.NewListener() is called in newServer. This means
2421
                // that we are actually listening and partially accepting
2422
                // inbound connections even before the connMgr starts.
2423
                //
2424
                // TODO(yy): move the log into the connMgr's `Start` method.
2425
                srvrLog.Info("connMgr starting...")
3✔
2426
                s.connMgr.Start()
3✔
2427
                srvrLog.Debug("connMgr started")
3✔
2428

3✔
2429
                // If peers are specified as a config option, we'll add those
3✔
2430
                // peers first.
3✔
2431
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2432
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2433
                                peerAddrCfg,
3✔
2434
                        )
3✔
2435
                        if err != nil {
3✔
2436
                                startErr = fmt.Errorf("unable to parse peer "+
×
2437
                                        "pubkey from config: %v", err)
×
2438
                                return
×
2439
                        }
×
2440
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2441
                        if err != nil {
3✔
2442
                                startErr = fmt.Errorf("unable to parse peer "+
×
2443
                                        "address provided as a config option: "+
×
2444
                                        "%v", err)
×
2445
                                return
×
2446
                        }
×
2447

2448
                        peerAddr := &lnwire.NetAddress{
3✔
2449
                                IdentityKey: parsedPubkey,
3✔
2450
                                Address:     addr,
3✔
2451
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2452
                        }
3✔
2453

3✔
2454
                        err = s.ConnectToPeer(
3✔
2455
                                peerAddr, true,
3✔
2456
                                s.cfg.ConnectionTimeout,
3✔
2457
                        )
3✔
2458
                        if err != nil {
3✔
2459
                                startErr = fmt.Errorf("unable to connect to "+
×
2460
                                        "peer address provided as a config "+
×
2461
                                        "option: %v", err)
×
2462
                                return
×
2463
                        }
×
2464
                }
2465

2466
                // Subscribe to NodeAnnouncements that advertise new addresses
2467
                // our persistent peers.
2468
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2469
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2470
                                "addr: %v", err)
×
2471

×
2472
                        startErr = err
×
2473
                        return
×
2474
                }
×
2475

2476
                // With all the relevant sub-systems started, we'll now attempt
2477
                // to establish persistent connections to our direct channel
2478
                // collaborators within the network. Before doing so however,
2479
                // we'll prune our set of link nodes to ensure we don't
2480
                // reconnect to any nodes we no longer have open channels with.
2481
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2482
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2483

×
2484
                        startErr = err
×
2485
                        return
×
2486
                }
×
2487

2488
                if err := s.establishPersistentConnections(ctx); err != nil {
3✔
2489
                        srvrLog.Errorf("Failed to establish persistent "+
×
2490
                                "connections: %v", err)
×
2491
                }
×
2492

2493
                // setSeedList is a helper function that turns multiple DNS seed
2494
                // server tuples from the command line or config file into the
2495
                // data structure we need and does a basic formal sanity check
2496
                // in the process.
2497
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2498
                        if len(tuples) == 0 {
×
2499
                                return
×
2500
                        }
×
2501

2502
                        result := make([][2]string, len(tuples))
×
2503
                        for idx, tuple := range tuples {
×
2504
                                tuple = strings.TrimSpace(tuple)
×
2505
                                if len(tuple) == 0 {
×
2506
                                        return
×
2507
                                }
×
2508

2509
                                servers := strings.Split(tuple, ",")
×
2510
                                if len(servers) > 2 || len(servers) == 0 {
×
2511
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2512
                                                "seed tuple: %v", servers)
×
2513
                                        return
×
2514
                                }
×
2515

2516
                                copy(result[idx][:], servers)
×
2517
                        }
2518

2519
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2520
                }
2521

2522
                // Let users overwrite the DNS seed nodes. We only allow them
2523
                // for bitcoin mainnet/testnet/signet.
2524
                if s.cfg.Bitcoin.MainNet {
3✔
2525
                        setSeedList(
×
2526
                                s.cfg.Bitcoin.DNSSeeds,
×
2527
                                chainreg.BitcoinMainnetGenesis,
×
2528
                        )
×
2529
                }
×
2530
                if s.cfg.Bitcoin.TestNet3 {
3✔
2531
                        setSeedList(
×
2532
                                s.cfg.Bitcoin.DNSSeeds,
×
2533
                                chainreg.BitcoinTestnetGenesis,
×
2534
                        )
×
2535
                }
×
2536
                if s.cfg.Bitcoin.TestNet4 {
3✔
2537
                        setSeedList(
×
2538
                                s.cfg.Bitcoin.DNSSeeds,
×
2539
                                chainreg.BitcoinTestnet4Genesis,
×
2540
                        )
×
2541
                }
×
2542
                if s.cfg.Bitcoin.SigNet {
3✔
2543
                        setSeedList(
×
2544
                                s.cfg.Bitcoin.DNSSeeds,
×
2545
                                chainreg.BitcoinSignetGenesis,
×
2546
                        )
×
2547
                }
×
2548

2549
                // If network bootstrapping hasn't been disabled, then we'll
2550
                // configure the set of active bootstrappers, and launch a
2551
                // dedicated goroutine to maintain a set of persistent
2552
                // connections.
2553
                if !s.cfg.NoNetBootstrap {
6✔
2554
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2555
                        if err != nil {
3✔
2556
                                startErr = err
×
2557
                                return
×
2558
                        }
×
2559

2560
                        s.wg.Add(1)
3✔
2561
                        go s.peerBootstrapper(
3✔
2562
                                ctx, defaultMinPeers, bootstrappers,
3✔
2563
                        )
3✔
2564
                } else {
3✔
2565
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2566
                }
3✔
2567

2568
                // Start the blockbeat after all other subsystems have been
2569
                // started so they are ready to receive new blocks.
2570
                cleanup = cleanup.add(func() error {
3✔
2571
                        s.blockbeatDispatcher.Stop()
×
2572
                        return nil
×
2573
                })
×
2574
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2575
                        startErr = err
×
2576
                        return
×
2577
                }
×
2578

2579
                // Set the active flag now that we've completed the full
2580
                // startup.
2581
                atomic.StoreInt32(&s.active, 1)
3✔
2582
        })
2583

2584
        if startErr != nil {
3✔
2585
                cleanup.run()
×
2586
        }
×
2587
        return startErr
3✔
2588
}
2589

2590
// Stop gracefully shutsdown the main daemon server. This function will signal
2591
// any active goroutines, or helper objects to exit, then blocks until they've
2592
// all successfully exited. Additionally, any/all listeners are closed.
2593
// NOTE: This function is safe for concurrent access.
2594
func (s *server) Stop() error {
3✔
2595
        s.stop.Do(func() {
6✔
2596
                atomic.StoreInt32(&s.stopping, 1)
3✔
2597

3✔
2598
                ctx := context.Background()
3✔
2599

3✔
2600
                close(s.quit)
3✔
2601

3✔
2602
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2603
                s.connMgr.Stop()
3✔
2604

3✔
2605
                // Stop dispatching blocks to other systems immediately.
3✔
2606
                s.blockbeatDispatcher.Stop()
3✔
2607

3✔
2608
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2609
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2610
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2611
                }
×
2612
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2613
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2614
                }
×
2615
                if err := s.sphinx.Stop(); err != nil {
3✔
2616
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2617
                }
×
2618
                if err := s.invoices.Stop(); err != nil {
3✔
2619
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2620
                }
×
2621
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2622
                        srvrLog.Warnf("failed to stop interceptable "+
×
2623
                                "switch: %v", err)
×
2624
                }
×
2625
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2626
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2627
                                "modifier: %v", err)
×
2628
                }
×
2629
                if err := s.chanRouter.Stop(); err != nil {
3✔
2630
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2631
                }
×
2632
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2633
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2634
                }
×
2635
                if err := s.graphDB.Stop(); err != nil {
3✔
2636
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2637
                }
×
2638
                if err := s.chainArb.Stop(); err != nil {
3✔
2639
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2640
                }
×
2641
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2642
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2643
                }
×
2644
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2645
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2646
                                err)
×
2647
                }
×
2648
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2649
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2650
                }
×
2651
                if err := s.authGossiper.Stop(); err != nil {
3✔
2652
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2653
                }
×
2654
                if err := s.sweeper.Stop(); err != nil {
3✔
2655
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2656
                }
×
2657
                if err := s.txPublisher.Stop(); err != nil {
3✔
2658
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2659
                }
×
2660
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2661
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2662
                }
×
2663
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2664
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2665
                }
×
2666
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2667
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2668
                }
×
2669

2670
                // Update channel.backup file. Make sure to do it before
2671
                // stopping chanSubSwapper.
2672
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2673
                        ctx, s.chanStateDB, s.addrSource,
3✔
2674
                )
3✔
2675
                if err != nil {
3✔
2676
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2677
                                err)
×
2678
                } else {
3✔
2679
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2680
                        if err != nil {
6✔
2681
                                srvrLog.Warnf("Manual update of channel "+
3✔
2682
                                        "backup failed: %v", err)
3✔
2683
                        }
3✔
2684
                }
2685

2686
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2687
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2688
                }
×
2689
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2690
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2691
                }
×
2692
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2693
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2694
                                err)
×
2695
                }
×
2696
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2697
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2698
                                err)
×
2699
                }
×
2700
                s.missionController.StopStoreTickers()
3✔
2701

3✔
2702
                // Disconnect from each active peers to ensure that
3✔
2703
                // peerTerminationWatchers signal completion to each peer.
3✔
2704
                for _, peer := range s.Peers() {
6✔
2705
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2706
                        if err != nil {
3✔
2707
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2708
                                        "received error: %v", peer.IdentityKey(),
×
2709
                                        err,
×
2710
                                )
×
2711
                        }
×
2712
                }
2713

2714
                // Now that all connections have been torn down, stop the tower
2715
                // client which will reliably flush all queued states to the
2716
                // tower. If this is halted for any reason, the force quit timer
2717
                // will kick in and abort to allow this method to return.
2718
                if s.towerClientMgr != nil {
6✔
2719
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2720
                                srvrLog.Warnf("Unable to shut down tower "+
×
2721
                                        "client manager: %v", err)
×
2722
                        }
×
2723
                }
2724

2725
                if s.hostAnn != nil {
3✔
2726
                        if err := s.hostAnn.Stop(); err != nil {
×
2727
                                srvrLog.Warnf("unable to shut down host "+
×
2728
                                        "annoucner: %v", err)
×
2729
                        }
×
2730
                }
2731

2732
                if s.livenessMonitor != nil {
6✔
2733
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2734
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2735
                                        "monitor: %v", err)
×
2736
                        }
×
2737
                }
2738

2739
                // Wait for all lingering goroutines to quit.
2740
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2741
                s.wg.Wait()
3✔
2742

3✔
2743
                srvrLog.Debug("Stopping buffer pools...")
3✔
2744
                s.sigPool.Stop()
3✔
2745
                s.writePool.Stop()
3✔
2746
                s.readPool.Stop()
3✔
2747
        })
2748

2749
        return nil
3✔
2750
}
2751

2752
// Stopped returns true if the server has been instructed to shutdown.
2753
// NOTE: This function is safe for concurrent access.
2754
func (s *server) Stopped() bool {
3✔
2755
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2756
}
3✔
2757

2758
// configurePortForwarding attempts to set up port forwarding for the different
2759
// ports that the server will be listening on.
2760
//
2761
// NOTE: This should only be used when using some kind of NAT traversal to
2762
// automatically set up forwarding rules.
2763
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2764
        ip, err := s.natTraversal.ExternalIP()
×
2765
        if err != nil {
×
2766
                return nil, err
×
2767
        }
×
2768
        s.lastDetectedIP = ip
×
2769

×
2770
        externalIPs := make([]string, 0, len(ports))
×
2771
        for _, port := range ports {
×
2772
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2773
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2774
                        continue
×
2775
                }
2776

2777
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2778
                externalIPs = append(externalIPs, hostIP)
×
2779
        }
2780

2781
        return externalIPs, nil
×
2782
}
2783

2784
// removePortForwarding attempts to clear the forwarding rules for the different
2785
// ports the server is currently listening on.
2786
//
2787
// NOTE: This should only be used when using some kind of NAT traversal to
2788
// automatically set up forwarding rules.
2789
func (s *server) removePortForwarding() {
×
2790
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2791
        for _, port := range forwardedPorts {
×
2792
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2793
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2794
                                "port %d: %v", port, err)
×
2795
                }
×
2796
        }
2797
}
2798

2799
// watchExternalIP continuously checks for an updated external IP address every
2800
// 15 minutes. Once a new IP address has been detected, it will automatically
2801
// handle port forwarding rules and send updated node announcements to the
2802
// currently connected peers.
2803
//
2804
// NOTE: This MUST be run as a goroutine.
2805
func (s *server) watchExternalIP() {
×
2806
        defer s.wg.Done()
×
2807

×
2808
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2809
        // up by the server.
×
2810
        defer s.removePortForwarding()
×
2811

×
2812
        // Keep track of the external IPs set by the user to avoid replacing
×
2813
        // them when detecting a new IP.
×
2814
        ipsSetByUser := make(map[string]struct{})
×
2815
        for _, ip := range s.cfg.ExternalIPs {
×
2816
                ipsSetByUser[ip.String()] = struct{}{}
×
2817
        }
×
2818

2819
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2820

×
2821
        ticker := time.NewTicker(15 * time.Minute)
×
2822
        defer ticker.Stop()
×
2823
out:
×
2824
        for {
×
2825
                select {
×
2826
                case <-ticker.C:
×
2827
                        // We'll start off by making sure a new IP address has
×
2828
                        // been detected.
×
2829
                        ip, err := s.natTraversal.ExternalIP()
×
2830
                        if err != nil {
×
2831
                                srvrLog.Debugf("Unable to retrieve the "+
×
2832
                                        "external IP address: %v", err)
×
2833
                                continue
×
2834
                        }
2835

2836
                        // Periodically renew the NAT port forwarding.
2837
                        for _, port := range forwardedPorts {
×
2838
                                err := s.natTraversal.AddPortMapping(port)
×
2839
                                if err != nil {
×
2840
                                        srvrLog.Warnf("Unable to automatically "+
×
2841
                                                "re-create port forwarding using %s: %v",
×
2842
                                                s.natTraversal.Name(), err)
×
2843
                                } else {
×
2844
                                        srvrLog.Debugf("Automatically re-created "+
×
2845
                                                "forwarding for port %d using %s to "+
×
2846
                                                "advertise external IP",
×
2847
                                                port, s.natTraversal.Name())
×
2848
                                }
×
2849
                        }
2850

2851
                        if ip.Equal(s.lastDetectedIP) {
×
2852
                                continue
×
2853
                        }
2854

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

×
2857
                        // Next, we'll craft the new addresses that will be
×
2858
                        // included in the new node announcement and advertised
×
2859
                        // to the network. Each address will consist of the new
×
2860
                        // IP detected and one of the currently advertised
×
2861
                        // ports.
×
2862
                        var newAddrs []net.Addr
×
2863
                        for _, port := range forwardedPorts {
×
2864
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2865
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2866
                                if err != nil {
×
2867
                                        srvrLog.Debugf("Unable to resolve "+
×
2868
                                                "host %v: %v", addr, err)
×
2869
                                        continue
×
2870
                                }
2871

2872
                                newAddrs = append(newAddrs, addr)
×
2873
                        }
2874

2875
                        // Skip the update if we weren't able to resolve any of
2876
                        // the new addresses.
2877
                        if len(newAddrs) == 0 {
×
2878
                                srvrLog.Debug("Skipping node announcement " +
×
2879
                                        "update due to not being able to " +
×
2880
                                        "resolve any new addresses")
×
2881
                                continue
×
2882
                        }
2883

2884
                        // Now, we'll need to update the addresses in our node's
2885
                        // announcement in order to propagate the update
2886
                        // throughout the network. We'll only include addresses
2887
                        // that have a different IP from the previous one, as
2888
                        // the previous IP is no longer valid.
2889
                        currentNodeAnn := s.getNodeAnnouncement()
×
2890

×
2891
                        for _, addr := range currentNodeAnn.Addresses {
×
2892
                                host, _, err := net.SplitHostPort(addr.String())
×
2893
                                if err != nil {
×
2894
                                        srvrLog.Debugf("Unable to determine "+
×
2895
                                                "host from address %v: %v",
×
2896
                                                addr, err)
×
2897
                                        continue
×
2898
                                }
2899

2900
                                // We'll also make sure to include external IPs
2901
                                // set manually by the user.
2902
                                _, setByUser := ipsSetByUser[addr.String()]
×
2903
                                if setByUser || host != s.lastDetectedIP.String() {
×
2904
                                        newAddrs = append(newAddrs, addr)
×
2905
                                }
×
2906
                        }
2907

2908
                        // Then, we'll generate a new timestamped node
2909
                        // announcement with the updated addresses and broadcast
2910
                        // it to our peers.
2911
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2912
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2913
                        )
×
2914
                        if err != nil {
×
2915
                                srvrLog.Debugf("Unable to generate new node "+
×
2916
                                        "announcement: %v", err)
×
2917
                                continue
×
2918
                        }
2919

2920
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2921
                        if err != nil {
×
2922
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2923
                                        "announcement to peers: %v", err)
×
2924
                                continue
×
2925
                        }
2926

2927
                        // Finally, update the last IP seen to the current one.
2928
                        s.lastDetectedIP = ip
×
2929
                case <-s.quit:
×
2930
                        break out
×
2931
                }
2932
        }
2933
}
2934

2935
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2936
// based on the server, and currently active bootstrap mechanisms as defined
2937
// within the current configuration.
2938
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
2939
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
2940

3✔
2941
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
2942

3✔
2943
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
2944
        // this can be used by default if we've already partially seeded the
3✔
2945
        // network.
3✔
2946
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
2947
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
2948
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
2949
        )
3✔
2950
        if err != nil {
3✔
2951
                return nil, err
×
2952
        }
×
2953
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
2954

3✔
2955
        // If this isn't using simnet or regtest mode, then one of our
3✔
2956
        // additional bootstrapping sources will be the set of running DNS
3✔
2957
        // seeds.
3✔
2958
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
2959
                //nolint:ll
×
2960
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
2961

×
2962
                // If we have a set of DNS seeds for this chain, then we'll add
×
2963
                // it as an additional bootstrapping source.
×
2964
                if ok {
×
2965
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2966
                                "seeds: %v", dnsSeeds)
×
2967

×
2968
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2969
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2970
                        )
×
2971
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2972
                }
×
2973
        }
2974

2975
        return bootStrappers, nil
3✔
2976
}
2977

2978
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2979
// needs to ignore, which is made of three parts,
2980
//   - the node itself needs to be skipped as it doesn't make sense to connect
2981
//     to itself.
2982
//   - the peers that already have connections with, as in s.peersByPub.
2983
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2984
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
3✔
2985
        s.mu.RLock()
3✔
2986
        defer s.mu.RUnlock()
3✔
2987

3✔
2988
        ignore := make(map[autopilot.NodeID]struct{})
3✔
2989

3✔
2990
        // We should ignore ourselves from bootstrapping.
3✔
2991
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
2992
        ignore[selfKey] = struct{}{}
3✔
2993

3✔
2994
        // Ignore all connected peers.
3✔
2995
        for _, peer := range s.peersByPub {
3✔
2996
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2997
                ignore[nID] = struct{}{}
×
2998
        }
×
2999

3000
        // Ignore all persistent peers as they have a dedicated reconnecting
3001
        // process.
3002
        for pubKeyStr := range s.persistentPeers {
3✔
3003
                var nID autopilot.NodeID
×
3004
                copy(nID[:], []byte(pubKeyStr))
×
3005
                ignore[nID] = struct{}{}
×
3006
        }
×
3007

3008
        return ignore
3✔
3009
}
3010

3011
// peerBootstrapper is a goroutine which is tasked with attempting to establish
3012
// and maintain a target minimum number of outbound connections. With this
3013
// invariant, we ensure that our node is connected to a diverse set of peers
3014
// and that nodes newly joining the network receive an up to date network view
3015
// as soon as possible.
3016
func (s *server) peerBootstrapper(ctx context.Context, numTargetPeers uint32,
3017
        bootstrappers []discovery.NetworkPeerBootstrapper) {
3✔
3018

3✔
3019
        defer s.wg.Done()
3✔
3020

3✔
3021
        // Before we continue, init the ignore peers map.
3✔
3022
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3023

3✔
3024
        // We'll start off by aggressively attempting connections to peers in
3✔
3025
        // order to be a part of the network as soon as possible.
3✔
3026
        s.initialPeerBootstrap(ctx, ignoreList, numTargetPeers, bootstrappers)
3✔
3027

3✔
3028
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3029
        // peers.
3✔
3030
        //
3✔
3031
        // We'll use a 15 second backoff, and double the time every time an
3✔
3032
        // epoch fails up to a ceiling.
3✔
3033
        backOff := time.Second * 15
3✔
3034

3✔
3035
        // We'll create a new ticker to wake us up every 15 seconds so we can
3✔
3036
        // see if we've reached our minimum number of peers.
3✔
3037
        sampleTicker := time.NewTicker(backOff)
3✔
3038
        defer sampleTicker.Stop()
3✔
3039

3✔
3040
        // We'll use the number of attempts and errors to determine if we need
3✔
3041
        // to increase the time between discovery epochs.
3✔
3042
        var epochErrors uint32 // To be used atomically.
3✔
3043
        var epochAttempts uint32
3✔
3044

3✔
3045
        for {
6✔
3046
                select {
3✔
3047
                // The ticker has just woken us up, so we'll need to check if
3048
                // we need to attempt to connect our to any more peers.
3049
                case <-sampleTicker.C:
×
3050
                        // Obtain the current number of peers, so we can gauge
×
3051
                        // if we need to sample more peers or not.
×
3052
                        s.mu.RLock()
×
3053
                        numActivePeers := uint32(len(s.peersByPub))
×
3054
                        s.mu.RUnlock()
×
3055

×
3056
                        // If we have enough peers, then we can loop back
×
3057
                        // around to the next round as we're done here.
×
3058
                        if numActivePeers >= numTargetPeers {
×
3059
                                continue
×
3060
                        }
3061

3062
                        // If all of our attempts failed during this last back
3063
                        // off period, then will increase our backoff to 5
3064
                        // minute ceiling to avoid an excessive number of
3065
                        // queries
3066
                        //
3067
                        // TODO(roasbeef): add reverse policy too?
3068

3069
                        if epochAttempts > 0 &&
×
3070
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3071

×
3072
                                sampleTicker.Stop()
×
3073

×
3074
                                backOff *= 2
×
3075
                                if backOff > bootstrapBackOffCeiling {
×
3076
                                        backOff = bootstrapBackOffCeiling
×
3077
                                }
×
3078

3079
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3080
                                        "%v", backOff)
×
3081
                                sampleTicker = time.NewTicker(backOff)
×
3082
                                continue
×
3083
                        }
3084

3085
                        atomic.StoreUint32(&epochErrors, 0)
×
3086
                        epochAttempts = 0
×
3087

×
3088
                        // Since we know need more peers, we'll compute the
×
3089
                        // exact number we need to reach our threshold.
×
3090
                        numNeeded := numTargetPeers - numActivePeers
×
3091

×
3092
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3093
                                "peers", numNeeded)
×
3094

×
3095
                        // With the number of peers we need calculated, we'll
×
3096
                        // query the network bootstrappers to sample a set of
×
3097
                        // random addrs for us.
×
3098
                        //
×
3099
                        // Before we continue, get a copy of the ignore peers
×
3100
                        // map.
×
3101
                        ignoreList = s.createBootstrapIgnorePeers()
×
3102

×
3103
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3104
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3105
                        )
×
3106
                        if err != nil {
×
3107
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3108
                                        "peers: %v", err)
×
3109
                                continue
×
3110
                        }
3111

3112
                        // Finally, we'll launch a new goroutine for each
3113
                        // prospective peer candidates.
3114
                        for _, addr := range peerAddrs {
×
3115
                                epochAttempts++
×
3116

×
3117
                                go func(a *lnwire.NetAddress) {
×
3118
                                        // TODO(roasbeef): can do AS, subnet,
×
3119
                                        // country diversity, etc
×
3120
                                        errChan := make(chan error, 1)
×
3121
                                        s.connectToPeer(
×
3122
                                                a, errChan,
×
3123
                                                s.cfg.ConnectionTimeout,
×
3124
                                        )
×
3125
                                        select {
×
3126
                                        case err := <-errChan:
×
3127
                                                if err == nil {
×
3128
                                                        return
×
3129
                                                }
×
3130

3131
                                                srvrLog.Errorf("Unable to "+
×
3132
                                                        "connect to %v: %v",
×
3133
                                                        a, err)
×
3134
                                                atomic.AddUint32(&epochErrors, 1)
×
3135
                                        case <-s.quit:
×
3136
                                        }
3137
                                }(addr)
3138
                        }
3139
                case <-s.quit:
3✔
3140
                        return
3✔
3141
                }
3142
        }
3143
}
3144

3145
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3146
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3147
// query back off each time we encounter a failure.
3148
const bootstrapBackOffCeiling = time.Minute * 5
3149

3150
// initialPeerBootstrap attempts to continuously connect to peers on startup
3151
// until the target number of peers has been reached. This ensures that nodes
3152
// receive an up to date network view as soon as possible.
3153
func (s *server) initialPeerBootstrap(ctx context.Context,
3154
        ignore map[autopilot.NodeID]struct{}, numTargetPeers uint32,
3155
        bootstrappers []discovery.NetworkPeerBootstrapper) {
3✔
3156

3✔
3157
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3158
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3159

3✔
3160
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3161
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3162
        var delaySignal <-chan time.Time
3✔
3163
        delayTime := time.Second * 2
3✔
3164

3✔
3165
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3166
        // then the main peer bootstrap logic.
3✔
3167
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3168

3✔
3169
        for attempts := 0; ; attempts++ {
6✔
3170
                // Check if the server has been requested to shut down in order
3✔
3171
                // to prevent blocking.
3✔
3172
                if s.Stopped() {
3✔
3173
                        return
×
3174
                }
×
3175

3176
                // We can exit our aggressive initial peer bootstrapping stage
3177
                // if we've reached out target number of peers.
3178
                s.mu.RLock()
3✔
3179
                numActivePeers := uint32(len(s.peersByPub))
3✔
3180
                s.mu.RUnlock()
3✔
3181

3✔
3182
                if numActivePeers >= numTargetPeers {
6✔
3183
                        return
3✔
3184
                }
3✔
3185

3186
                if attempts > 0 {
3✔
UNCOV
3187
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
UNCOV
3188
                                "bootstrap peers (attempt #%v)", delayTime,
×
UNCOV
3189
                                attempts)
×
UNCOV
3190

×
UNCOV
3191
                        // We've completed at least one iterating and haven't
×
UNCOV
3192
                        // finished, so we'll start to insert a delay period
×
UNCOV
3193
                        // between each attempt.
×
UNCOV
3194
                        delaySignal = time.After(delayTime)
×
UNCOV
3195
                        select {
×
UNCOV
3196
                        case <-delaySignal:
×
UNCOV
3197
                        case <-s.quit:
×
UNCOV
3198
                                return
×
3199
                        }
3200

3201
                        // After our delay, we'll double the time we wait up to
3202
                        // the max back off period.
UNCOV
3203
                        delayTime *= 2
×
UNCOV
3204
                        if delayTime > backOffCeiling {
×
3205
                                delayTime = backOffCeiling
×
3206
                        }
×
3207
                }
3208

3209
                // Otherwise, we'll request for the remaining number of peers
3210
                // in order to reach our target.
3211
                peersNeeded := numTargetPeers - numActivePeers
3✔
3212
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3213
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3214
                )
3✔
3215
                if err != nil {
3✔
UNCOV
3216
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
UNCOV
3217
                                "peers: %v", err)
×
UNCOV
3218
                        continue
×
3219
                }
3220

3221
                // Then, we'll attempt to establish a connection to the
3222
                // different peer addresses retrieved by our bootstrappers.
3223
                var wg sync.WaitGroup
3✔
3224
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3225
                        wg.Add(1)
3✔
3226
                        go func(addr *lnwire.NetAddress) {
6✔
3227
                                defer wg.Done()
3✔
3228

3✔
3229
                                errChan := make(chan error, 1)
3✔
3230
                                go s.connectToPeer(
3✔
3231
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3232
                                )
3✔
3233

3✔
3234
                                // We'll only allow this connection attempt to
3✔
3235
                                // take up to 3 seconds. This allows us to move
3✔
3236
                                // quickly by discarding peers that are slowing
3✔
3237
                                // us down.
3✔
3238
                                select {
3✔
3239
                                case err := <-errChan:
3✔
3240
                                        if err == nil {
6✔
3241
                                                return
3✔
3242
                                        }
3✔
3243
                                        srvrLog.Errorf("Unable to connect to "+
×
3244
                                                "%v: %v", addr, err)
×
3245
                                // TODO: tune timeout? 3 seconds might be *too*
3246
                                // aggressive but works well.
3247
                                case <-time.After(3 * time.Second):
×
3248
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3249
                                                "to not establishing a "+
×
3250
                                                "connection within 3 seconds",
×
3251
                                                addr)
×
3252
                                case <-s.quit:
×
3253
                                }
3254
                        }(bootstrapAddr)
3255
                }
3256

3257
                wg.Wait()
3✔
3258
        }
3259
}
3260

3261
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3262
// order to listen for inbound connections over Tor.
3263
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3264
        // Determine the different ports the server is listening on. The onion
×
3265
        // service's virtual port will map to these ports and one will be picked
×
3266
        // at random when the onion service is being accessed.
×
3267
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3268
        for _, listenAddr := range s.listenAddrs {
×
3269
                port := listenAddr.(*net.TCPAddr).Port
×
3270
                listenPorts = append(listenPorts, port)
×
3271
        }
×
3272

3273
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3274
        if err != nil {
×
3275
                return err
×
3276
        }
×
3277

3278
        // Once the port mapping has been set, we can go ahead and automatically
3279
        // create our onion service. The service's private key will be saved to
3280
        // disk in order to regain access to this service when restarting `lnd`.
3281
        onionCfg := tor.AddOnionConfig{
×
3282
                VirtualPort: defaultPeerPort,
×
3283
                TargetPorts: listenPorts,
×
3284
                Store: tor.NewOnionFile(
×
3285
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3286
                        encrypter,
×
3287
                ),
×
3288
        }
×
3289

×
3290
        switch {
×
3291
        case s.cfg.Tor.V2:
×
3292
                onionCfg.Type = tor.V2
×
3293
        case s.cfg.Tor.V3:
×
3294
                onionCfg.Type = tor.V3
×
3295
        }
3296

3297
        addr, err := s.torController.AddOnion(onionCfg)
×
3298
        if err != nil {
×
3299
                return err
×
3300
        }
×
3301

3302
        // Now that the onion service has been created, we'll add the onion
3303
        // address it can be reached at to our list of advertised addresses.
3304
        newNodeAnn, err := s.genNodeAnnouncement(
×
3305
                nil, func(currentAnn *lnwire.NodeAnnouncement1) {
×
3306
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3307
                },
×
3308
        )
3309
        if err != nil {
×
3310
                return fmt.Errorf("unable to generate new node "+
×
3311
                        "announcement: %v", err)
×
3312
        }
×
3313

3314
        // Finally, we'll update the on-disk version of our announcement so it
3315
        // will eventually propagate to nodes in the network.
3316
        selfNode := models.NewV1Node(
×
3317
                route.NewVertex(s.identityECDH.PubKey()), &models.NodeV1Fields{
×
3318
                        Addresses:    newNodeAnn.Addresses,
×
3319
                        Features:     newNodeAnn.Features,
×
3320
                        AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3321
                        Color:        newNodeAnn.RGBColor,
×
3322
                        Alias:        newNodeAnn.Alias.String(),
×
3323
                        LastUpdate:   time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3324
                },
×
3325
        )
×
3326

×
3327
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3328
                return fmt.Errorf("can't set self node: %w", err)
×
3329
        }
×
3330

3331
        return nil
×
3332
}
3333

3334
// findChannel finds a channel given a public key and ChannelID. It is an
3335
// optimization that is quicker than seeking for a channel given only the
3336
// ChannelID.
3337
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3338
        *channeldb.OpenChannel, error) {
3✔
3339

3✔
3340
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3341
        if err != nil {
3✔
3342
                return nil, err
×
3343
        }
×
3344

3345
        for _, channel := range nodeChans {
6✔
3346
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3347
                        return channel, nil
3✔
3348
                }
3✔
3349
        }
3350

3351
        return nil, fmt.Errorf("unable to find channel")
3✔
3352
}
3353

3354
// getNodeAnnouncement fetches the current, fully signed node announcement.
3355
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement1 {
3✔
3356
        s.mu.Lock()
3✔
3357
        defer s.mu.Unlock()
3✔
3358

3✔
3359
        return *s.currentNodeAnn
3✔
3360
}
3✔
3361

3362
// genNodeAnnouncement generates and returns the current fully signed node
3363
// announcement. The time stamp of the announcement will be updated in order
3364
// to ensure it propagates through the network.
3365
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3366
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement1, error) {
3✔
3367

3✔
3368
        s.mu.Lock()
3✔
3369
        defer s.mu.Unlock()
3✔
3370

3✔
3371
        // Create a shallow copy of the current node announcement to work on.
3✔
3372
        // This ensures the original announcement remains unchanged
3✔
3373
        // until the new announcement is fully signed and valid.
3✔
3374
        newNodeAnn := *s.currentNodeAnn
3✔
3375

3✔
3376
        // First, try to update our feature manager with the updated set of
3✔
3377
        // features.
3✔
3378
        if features != nil {
6✔
3379
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3380
                        feature.SetNodeAnn: features,
3✔
3381
                }
3✔
3382
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3383
                if err != nil {
6✔
3384
                        return lnwire.NodeAnnouncement1{}, err
3✔
3385
                }
3✔
3386

3387
                // If we could successfully update our feature manager, add
3388
                // an update modifier to include these new features to our
3389
                // set.
3390
                modifiers = append(
3✔
3391
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3392
                )
3✔
3393
        }
3394

3395
        // Always update the timestamp when refreshing to ensure the update
3396
        // propagates.
3397
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3398

3✔
3399
        // Apply the requested changes to the node announcement.
3✔
3400
        for _, modifier := range modifiers {
6✔
3401
                modifier(&newNodeAnn)
3✔
3402
        }
3✔
3403

3404
        // The modifiers may have added duplicate addresses, so we need to
3405
        // de-duplicate them here.
3406
        uniqueAddrs := map[string]struct{}{}
3✔
3407
        dedupedAddrs := make([]net.Addr, 0)
3✔
3408
        for _, addr := range newNodeAnn.Addresses {
6✔
3409
                if _, ok := uniqueAddrs[addr.String()]; !ok {
6✔
3410
                        uniqueAddrs[addr.String()] = struct{}{}
3✔
3411
                        dedupedAddrs = append(dedupedAddrs, addr)
3✔
3412
                }
3✔
3413
        }
3414
        newNodeAnn.Addresses = dedupedAddrs
3✔
3415

3✔
3416
        // Sign a new update after applying all of the passed modifiers.
3✔
3417
        err := netann.SignNodeAnnouncement(
3✔
3418
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3419
        )
3✔
3420
        if err != nil {
3✔
3421
                return lnwire.NodeAnnouncement1{}, err
×
3422
        }
×
3423

3424
        // If signing succeeds, update the current announcement.
3425
        *s.currentNodeAnn = newNodeAnn
3✔
3426

3✔
3427
        return *s.currentNodeAnn, nil
3✔
3428
}
3429

3430
// updateAndBroadcastSelfNode generates a new node announcement
3431
// applying the giving modifiers and updating the time stamp
3432
// to ensure it propagates through the network. Then it broadcasts
3433
// it to the network.
3434
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3435
        features *lnwire.RawFeatureVector,
3436
        modifiers ...netann.NodeAnnModifier) error {
3✔
3437

3✔
3438
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3439
        if err != nil {
6✔
3440
                return fmt.Errorf("unable to generate new node "+
3✔
3441
                        "announcement: %v", err)
3✔
3442
        }
3✔
3443

3444
        // Update the on-disk version of our announcement.
3445
        // Load and modify self node istead of creating anew instance so we
3446
        // don't risk overwriting any existing values.
3447
        selfNode, err := s.v1Graph.SourceNode(ctx)
3✔
3448
        if err != nil {
3✔
3449
                return fmt.Errorf("unable to get current source node: %w", err)
×
3450
        }
×
3451

3452
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3453
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3454
        selfNode.Alias = fn.Some(newNodeAnn.Alias.String())
3✔
3455
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3456
        selfNode.Color = fn.Some(newNodeAnn.RGBColor)
3✔
3457
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3458

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

3✔
3461
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
3✔
3462
                return fmt.Errorf("can't set self node: %w", err)
×
3463
        }
×
3464

3465
        // Finally, propagate it to the nodes in the network.
3466
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3467
        if err != nil {
3✔
3468
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3469
                        "announcement to peers: %v", err)
×
3470
                return err
×
3471
        }
×
3472

3473
        return nil
3✔
3474
}
3475

3476
type nodeAddresses struct {
3477
        pubKey    *btcec.PublicKey
3478
        addresses []net.Addr
3479
}
3480

3481
// establishPersistentConnections attempts to establish persistent connections
3482
// to all our direct channel collaborators. In order to promote liveness of our
3483
// active channels, we instruct the connection manager to attempt to establish
3484
// and maintain persistent connections to all our direct channel counterparties.
3485
func (s *server) establishPersistentConnections(ctx context.Context) error {
3✔
3486
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3487
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3488
        // since other PubKey forms can't be compared.
3✔
3489
        nodeAddrsMap := make(map[string]*nodeAddresses)
3✔
3490

3✔
3491
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3492
        // attempt to connect to based on our set of previous connections. Set
3✔
3493
        // the reconnection port to the default peer port.
3✔
3494
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3495
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
3✔
3496
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3497
        }
×
3498

3499
        for _, node := range linkNodes {
6✔
3500
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3501
                nodeAddrs := &nodeAddresses{
3✔
3502
                        pubKey:    node.IdentityPub,
3✔
3503
                        addresses: node.Addresses,
3✔
3504
                }
3✔
3505
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3506
        }
3✔
3507

3508
        // After checking our previous connections for addresses to connect to,
3509
        // iterate through the nodes in our channel graph to find addresses
3510
        // that have been added via NodeAnnouncement1 messages.
3511
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3512
        // each of the nodes.
3513
        graphAddrs := make(map[string]*nodeAddresses)
3✔
3514
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
3✔
3515
                havePolicy bool, channelPeer *models.Node) error {
6✔
3516

3✔
3517
                // If the remote party has announced the channel to us, but we
3✔
3518
                // haven't yet, then we won't have a policy. However, we don't
3✔
3519
                // need this to connect to the peer, so we'll log it and move on.
3✔
3520
                if !havePolicy {
3✔
3521
                        srvrLog.Warnf("No channel policy found for "+
×
3522
                                "ChannelPoint(%v): ", chanPoint)
×
3523
                }
×
3524

3525
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3526

3✔
3527
                // Add all unique addresses from channel
3✔
3528
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3529
                // connect to for this peer.
3✔
3530
                addrSet := make(map[string]net.Addr)
3✔
3531
                for _, addr := range channelPeer.Addresses {
6✔
3532
                        switch addr.(type) {
3✔
3533
                        case *net.TCPAddr:
3✔
3534
                                addrSet[addr.String()] = addr
3✔
3535

3536
                        // We'll only attempt to connect to Tor addresses if Tor
3537
                        // outbound support is enabled.
3538
                        case *tor.OnionAddr:
×
3539
                                if s.cfg.Tor.Active {
×
3540
                                        addrSet[addr.String()] = addr
×
3541
                                }
×
3542
                        }
3543
                }
3544

3545
                // If this peer is also recorded as a link node, we'll add any
3546
                // additional addresses that have not already been selected.
3547
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3548
                if ok {
6✔
3549
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3550
                                switch lnAddress.(type) {
3✔
3551
                                case *net.TCPAddr:
3✔
3552
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3553

3554
                                // We'll only attempt to connect to Tor
3555
                                // addresses if Tor outbound support is enabled.
3556
                                case *tor.OnionAddr:
×
3557
                                        if s.cfg.Tor.Active {
×
3558
                                                //nolint:ll
×
3559
                                                addrSet[lnAddress.String()] = lnAddress
×
3560
                                        }
×
3561
                                }
3562
                        }
3563
                }
3564

3565
                // Construct a slice of the deduped addresses.
3566
                var addrs []net.Addr
3✔
3567
                for _, addr := range addrSet {
6✔
3568
                        addrs = append(addrs, addr)
3✔
3569
                }
3✔
3570

3571
                n := &nodeAddresses{
3✔
3572
                        addresses: addrs,
3✔
3573
                }
3✔
3574
                n.pubKey, err = channelPeer.PubKey()
3✔
3575
                if err != nil {
3✔
3576
                        return err
×
3577
                }
×
3578

3579
                graphAddrs[pubStr] = n
3✔
3580
                return nil
3✔
3581
        }
3582

3583
        // TODO(elle): for now, we only fetch our V1 channels. This should be
3584
        //  updated to fetch channels across all versions.
3585
        err = s.v1Graph.ForEachSourceNodeChannel(
3✔
3586
                ctx, forEachSrcNodeChan, func() {
6✔
3587
                        clear(graphAddrs)
3✔
3588
                },
3✔
3589
        )
3590
        if err != nil {
3✔
3591
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3592
                        "%v", err)
×
3593

×
3594
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3595
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3596

×
3597
                        return err
×
3598
                }
×
3599
        }
3600

3601
        // Combine the addresses from the link nodes and the channel graph.
3602
        for pubStr, nodeAddr := range graphAddrs {
6✔
3603
                nodeAddrsMap[pubStr] = nodeAddr
3✔
3604
        }
3✔
3605

3606
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3607
                len(nodeAddrsMap))
3✔
3608

3✔
3609
        // Acquire and hold server lock until all persistent connection requests
3✔
3610
        // have been recorded and sent to the connection manager.
3✔
3611
        s.mu.Lock()
3✔
3612
        defer s.mu.Unlock()
3✔
3613

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

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

3✔
3637
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3638
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3639
                }
3✔
3640

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

3✔
3651
                        go s.connectToPersistentPeer(pubStr)
3✔
3652
                } else {
3✔
3653
                        go s.delayInitialReconnect(pubStr)
×
3654
                }
×
3655

3656
                numOutboundConns++
3✔
3657
        }
3658

3659
        return nil
3✔
3660
}
3661

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

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

3✔
3681
        s.mu.Lock()
3✔
3682
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3683
                delete(s.persistentPeers, pubKeyStr)
3✔
3684
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3685
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3686
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3687
                s.mu.Unlock()
3✔
3688

3✔
3689
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3690
                        "peer has no open channels", compressedPubKey)
3✔
3691

3✔
3692
                return
3✔
3693
        }
3✔
3694
        s.mu.Unlock()
3✔
3695
}
3696

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

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

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

3737
                peers = append(peers, sPeer)
3✔
3738
        }
3739
        s.mu.RUnlock()
3✔
3740

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

3✔
3748
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3749
                wg.Add(1)
3✔
3750
                s.wg.Add(1)
3✔
3751
                go func(p lnpeer.Peer) {
6✔
3752
                        defer s.wg.Done()
3✔
3753
                        defer wg.Done()
3✔
3754

3✔
3755
                        p.SendMessageLazy(false, msgs...)
3✔
3756
                }(sPeer)
3✔
3757
        }
3758

3759
        // Wait for all messages to have been dispatched before returning to
3760
        // caller.
3761
        wg.Wait()
3✔
3762

3✔
3763
        return nil
3✔
3764
}
3765

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

3✔
3773
        s.mu.Lock()
3✔
3774

3✔
3775
        // Compute the target peer's identifier.
3✔
3776
        pubStr := string(peerKey[:])
3✔
3777

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

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

3800
                // Connected, can return early.
3801
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3802

3✔
3803
                select {
3✔
3804
                case peerChan <- peer:
3✔
3805
                case <-s.quit:
×
3806
                }
3807

3808
                return
3✔
3809
        }
3810

3811
        // Not connected, store this listener such that it can be notified when
3812
        // the peer comes online.
3813
        s.peerConnectedListeners[pubStr] = append(
3✔
3814
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3815
        )
3✔
3816
        s.mu.Unlock()
3✔
3817
}
3818

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

3✔
3826
        c := make(chan struct{})
3✔
3827

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

3837
        // Otherwise, the peer is online, so we'll keep track of the channel to
3838
        // trigger the notification once the server detects the peer
3839
        // disconnects.
3840
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3841
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3842
        )
3✔
3843

3✔
3844
        return c
3✔
3845
}
3846

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

3✔
3856
        pubStr := string(peerKey.SerializeCompressed())
3✔
3857

3✔
3858
        return s.findPeerByPubStr(pubStr)
3✔
3859
}
3✔
3860

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

3✔
3870
        return s.findPeerByPubStr(pubStr)
3✔
3871
}
3✔
3872

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

3881
        return peer, nil
3✔
3882
}
3883

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

3✔
3890
        // Now, determine the appropriate backoff to use for the retry.
3✔
3891
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3892
        if !ok {
6✔
3893
                // If an existing backoff was unknown, use the default.
3✔
3894
                return s.cfg.MinBackoff
3✔
3895
        }
3✔
3896

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

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

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

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

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

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

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

3956
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3957
        pubSer := nodePub.SerializeCompressed()
3✔
3958
        pubStr := string(pubSer)
3✔
3959

3✔
3960
        var pubBytes [33]byte
3✔
3961
        copy(pubBytes[:], pubSer)
3✔
3962

3✔
3963
        s.mu.Lock()
3✔
3964
        defer s.mu.Unlock()
3✔
3965

3✔
3966
        // If we already have an outbound connection to this peer, then ignore
3✔
3967
        // this new connection.
3✔
3968
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
3969
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3970
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3971
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3972

3✔
3973
                conn.Close()
3✔
3974
                return
3✔
3975
        }
3✔
3976

3977
        // If we already have a valid connection that is scheduled to take
3978
        // precedence once the prior peer has finished disconnecting, we'll
3979
        // ignore this connection.
3980
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
3981
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3982
                        "scheduled", conn.RemoteAddr(), p)
×
3983
                conn.Close()
×
3984
                return
×
3985
        }
×
3986

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

3✔
3989
        // Check to see if we already have a connection with this peer. If so,
3✔
3990
        // we may need to drop our existing connection. This prevents us from
3✔
3991
        // having duplicate connections to the same peer. We forgo adding a
3✔
3992
        // default case as we expect these to be the only error values returned
3✔
3993
        // from findPeerByPubStr.
3✔
3994
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
3995
        switch err {
3✔
3996
        case ErrPeerNotConnected:
3✔
3997
                // We were unable to locate an existing connection with the
3✔
3998
                // target peer, proceed to connect.
3✔
3999
                s.cancelConnReqs(pubStr, nil)
3✔
4000
                s.peerConnected(conn, nil, true)
3✔
4001

4002
        case nil:
3✔
4003
                ctx := btclog.WithCtx(
3✔
4004
                        context.TODO(),
3✔
4005
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4006
                )
3✔
4007

3✔
4008
                // We already have a connection with the incoming peer. If the
3✔
4009
                // connection we've already established should be kept and is
3✔
4010
                // not of the same type of the new connection (inbound), then
3✔
4011
                // we'll close out the new connection s.t there's only a single
3✔
4012
                // connection between us.
3✔
4013
                localPub := s.identityECDH.PubKey()
3✔
4014
                if !connectedPeer.Inbound() &&
3✔
4015
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
4016

×
4017
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4018
                                "peer, but already have outbound "+
×
4019
                                "connection, dropping conn",
×
4020
                                fmt.Errorf("already have outbound conn"))
×
4021
                        conn.Close()
×
4022
                        return
×
4023
                }
×
4024

4025
                // Otherwise, if we should drop the connection, then we'll
4026
                // disconnect our already connected peer.
4027
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4028

3✔
4029
                s.cancelConnReqs(pubStr, nil)
3✔
4030

3✔
4031
                // Remove the current peer from the server's internal state and
3✔
4032
                // signal that the peer termination watcher does not need to
3✔
4033
                // execute for this peer.
3✔
4034
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4035
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4036
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4037
                        s.peerConnected(conn, nil, true)
3✔
4038
                }
3✔
4039
        }
4040
}
4041

4042
// OutboundPeerConnected initializes a new peer in response to a new outbound
4043
// connection.
4044
// NOTE: This function is safe for concurrent access.
4045
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4046
        // Exit early if we have already been instructed to shutdown, this
3✔
4047
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4048
        if s.Stopped() {
3✔
4049
                return
×
4050
        }
×
4051

4052
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4053
        pubSer := nodePub.SerializeCompressed()
3✔
4054
        pubStr := string(pubSer)
3✔
4055

3✔
4056
        var pubBytes [33]byte
3✔
4057
        copy(pubBytes[:], pubSer)
3✔
4058

3✔
4059
        s.mu.Lock()
3✔
4060
        defer s.mu.Unlock()
3✔
4061

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

3✔
4069
                if connReq != nil {
6✔
4070
                        s.connMgr.Remove(connReq.ID())
3✔
4071
                }
3✔
4072
                conn.Close()
3✔
4073
                return
3✔
4074
        }
4075
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4076
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4077
                s.connMgr.Remove(connReq.ID())
×
4078
                conn.Close()
×
4079
                return
×
4080
        }
×
4081

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

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

4092
                conn.Close()
×
4093
                return
×
4094
        }
4095

4096
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4097
                conn.RemoteAddr())
3✔
4098

3✔
4099
        if connReq != nil {
6✔
4100
                // A successful connection was returned by the connmgr.
3✔
4101
                // Immediately cancel all pending requests, excluding the
3✔
4102
                // outbound connection we just established.
3✔
4103
                ignore := connReq.ID()
3✔
4104
                s.cancelConnReqs(pubStr, &ignore)
3✔
4105
        } else {
6✔
4106
                // This was a successful connection made by some other
3✔
4107
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4108
                s.cancelConnReqs(pubStr, nil)
3✔
4109
        }
3✔
4110

4111
        // If we already have a connection with this peer, decide whether or not
4112
        // we need to drop the stale connection. We forgo adding a default case
4113
        // as we expect these to be the only error values returned from
4114
        // findPeerByPubStr.
4115
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4116
        switch err {
3✔
4117
        case ErrPeerNotConnected:
3✔
4118
                // We were unable to locate an existing connection with the
3✔
4119
                // target peer, proceed to connect.
3✔
4120
                s.peerConnected(conn, connReq, false)
3✔
4121

4122
        case nil:
3✔
4123
                ctx := btclog.WithCtx(
3✔
4124
                        context.TODO(),
3✔
4125
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4126
                )
3✔
4127

3✔
4128
                // We already have a connection with the incoming peer. If the
3✔
4129
                // connection we've already established should be kept and is
3✔
4130
                // not of the same type of the new connection (outbound), then
3✔
4131
                // we'll close out the new connection s.t there's only a single
3✔
4132
                // connection between us.
3✔
4133
                localPub := s.identityECDH.PubKey()
3✔
4134
                if connectedPeer.Inbound() &&
3✔
4135
                        shouldDropLocalConnection(localPub, nodePub) {
3✔
4136

×
4137
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4138
                                "to peer, but already have inbound "+
×
4139
                                "connection, dropping conn",
×
4140
                                fmt.Errorf("already have inbound conn"))
×
4141
                        if connReq != nil {
×
4142
                                s.connMgr.Remove(connReq.ID())
×
4143
                        }
×
4144
                        conn.Close()
×
4145
                        return
×
4146
                }
4147

4148
                // Otherwise, _their_ connection should be dropped. So we'll
4149
                // disconnect the peer and send the now obsolete peer to the
4150
                // server for garbage collection.
4151
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4152

3✔
4153
                // Remove the current peer from the server's internal state and
3✔
4154
                // signal that the peer termination watcher does not need to
3✔
4155
                // execute for this peer.
3✔
4156
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4157
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4158
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4159
                        s.peerConnected(conn, connReq, false)
3✔
4160
                }
3✔
4161
        }
4162
}
4163

4164
// UnassignedConnID is the default connection ID that a request can have before
4165
// it actually is submitted to the connmgr.
4166
// TODO(conner): move into connmgr package, or better, add connmgr method for
4167
// generating atomic IDs
4168
const UnassignedConnID uint64 = 0
4169

4170
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4171
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4172
// Afterwards, each connection request removed from the connmgr. The caller can
4173
// optionally specify a connection ID to ignore, which prevents us from
4174
// canceling a successful request. All persistent connreqs for the provided
4175
// pubkey are discarded after the operationjw.
4176
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4177
        // First, cancel any lingering persistent retry attempts, which will
3✔
4178
        // prevent retries for any with backoffs that are still maturing.
3✔
4179
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4180
                close(cancelChan)
3✔
4181
                delete(s.persistentRetryCancels, pubStr)
3✔
4182
        }
3✔
4183

4184
        // Next, check to see if we have any outstanding persistent connection
4185
        // requests to this peer. If so, then we'll remove all of these
4186
        // connection requests, and also delete the entry from the map.
4187
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4188
        if !ok {
6✔
4189
                return
3✔
4190
        }
3✔
4191

4192
        for _, connReq := range connReqs {
6✔
4193
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4194

3✔
4195
                // Atomically capture the current request identifier.
3✔
4196
                connID := connReq.ID()
3✔
4197

3✔
4198
                // Skip any zero IDs, this indicates the request has not
3✔
4199
                // yet been schedule.
3✔
4200
                if connID == UnassignedConnID {
3✔
4201
                        continue
×
4202
                }
4203

4204
                // Skip a particular connection ID if instructed.
4205
                if skip != nil && connID == *skip {
6✔
4206
                        continue
3✔
4207
                }
4208

4209
                s.connMgr.Remove(connID)
3✔
4210
        }
4211

4212
        delete(s.persistentConnReqs, pubStr)
3✔
4213
}
4214

4215
// handleCustomMessage dispatches an incoming custom peers message to
4216
// subscribers.
4217
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4218
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4219
                peer, msg.Type)
3✔
4220

3✔
4221
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4222
                Peer: peer,
3✔
4223
                Msg:  msg,
3✔
4224
        })
3✔
4225
}
3✔
4226

4227
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4228
// messages.
4229
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4230
        return s.customMessageServer.Subscribe()
3✔
4231
}
3✔
4232

4233
// SubscribeOnionMessages subscribes to a stream of incoming onion messages.
4234
func (s *server) SubscribeOnionMessages() (*subscribe.Client, error) {
3✔
4235
        return s.onionMessageServer.Subscribe()
3✔
4236
}
3✔
4237

4238
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4239
// the channelNotifier's NotifyOpenChannelEvent.
4240
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4241
        remotePub *btcec.PublicKey) {
3✔
4242

3✔
4243
        // Call newOpenChan to update the access manager's maps for this peer.
3✔
4244
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
6✔
4245
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
3✔
4246
                        "channel[%v] open", remotePub.SerializeCompressed(), op)
3✔
4247
        }
3✔
4248

4249
        // Notify subscribers about this open channel event.
4250
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4251
}
4252

4253
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4254
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4255
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4256
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4257

3✔
4258
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4259
        // peer.
3✔
4260
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4261
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4262
                        "channel[%v] pending open",
×
4263
                        remotePub.SerializeCompressed(), op)
×
4264
        }
×
4265

4266
        // Notify subscribers about this event.
4267
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4268
}
4269

4270
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4271
// calls the channelNotifier's NotifyFundingTimeout.
4272
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4273
        remotePub *btcec.PublicKey) {
3✔
4274

3✔
4275
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4276
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4277
        if err != nil {
3✔
4278
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4279
                        "channel[%v] pending close",
×
4280
                        remotePub.SerializeCompressed(), op)
×
4281
        }
×
4282

4283
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4284
                // If we encounter an error while attempting to disconnect the
×
4285
                // peer, log the error.
×
4286
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4287
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4288
                }
×
4289
        }
4290

4291
        // Notify subscribers about this event.
4292
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4293
}
4294

4295
// peerConnected is a function that handles initialization a newly connected
4296
// peer by adding it to the server's global list of all active peers, and
4297
// starting all the goroutines the peer needs to function properly. The inbound
4298
// boolean should be true if the peer initiated the connection to us.
4299
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4300
        inbound bool) {
3✔
4301

3✔
4302
        brontideConn := conn.(*brontide.Conn)
3✔
4303
        addr := conn.RemoteAddr()
3✔
4304
        pubKey := brontideConn.RemotePub()
3✔
4305

3✔
4306
        // Only restrict access for inbound connections, which means if the
3✔
4307
        // remote node's public key is banned or the restricted slots are used
3✔
4308
        // up, we will drop the connection.
3✔
4309
        //
3✔
4310
        // TODO(yy): Consider perform this check in
3✔
4311
        // `peerAccessMan.addPeerAccess`.
3✔
4312
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4313
        if inbound && err != nil {
3✔
4314
                pubSer := pubKey.SerializeCompressed()
×
4315

×
4316
                // Clean up the persistent peer maps if we're dropping this
×
4317
                // connection.
×
4318
                s.bannedPersistentPeerConnection(string(pubSer))
×
4319

×
4320
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4321
                        "of restricted-access connection slots: %v.", pubSer,
×
4322
                        err)
×
4323

×
4324
                conn.Close()
×
4325

×
4326
                return
×
4327
        }
×
4328

4329
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4330
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4331

3✔
4332
        peerAddr := &lnwire.NetAddress{
3✔
4333
                IdentityKey: pubKey,
3✔
4334
                Address:     addr,
3✔
4335
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4336
        }
3✔
4337

3✔
4338
        // With the brontide connection established, we'll now craft the feature
3✔
4339
        // vectors to advertise to the remote node.
3✔
4340
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4341
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4342

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

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

4367
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4368
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4369

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

3✔
4414
                        return s.genNodeAnnouncement(nil)
3✔
4415
                },
3✔
4416

4417
                PongBuf: s.pongBuf,
4418

4419
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4420

4421
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4422

4423
                FundingManager: s.fundingMgr,
4424

4425
                Hodl:                    s.cfg.Hodl,
4426
                UnsafeReplay:            s.cfg.UnsafeReplay,
4427
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4428
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4429
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4430
                ChannelCloseConfs:       s.cfg.Dev.ChannelCloseConfs(),
4431
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4432
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4433
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4434
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4435
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4436
                HandleCustomMessage:    s.handleCustomMessage,
4437
                GetAliases:             s.aliasMgr.GetAliases,
4438
                RequestAlias:           s.aliasMgr.RequestAlias,
4439
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4440
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4441
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4442
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4443
                MaxFeeExposure:         thresholdMSats,
4444
                Quit:                   s.quit,
4445
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4446
                AuxSigner:              s.implCfg.AuxSigner,
4447
                MsgRouter:              s.implCfg.MsgRouter,
4448
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4449
                AuxResolver:            s.implCfg.AuxContractResolver,
4450
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4451
                AuxChannelNegotiator:   s.implCfg.AuxChannelNegotiator,
4452
                ShouldFwdExpAccountability: func() bool {
3✔
4453
                        return !s.cfg.ProtocolOptions.NoExpAccountability()
3✔
4454
                },
3✔
4455
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4456
        }
4457

4458
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4459
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4460

3✔
4461
        p := peer.NewBrontide(pCfg)
3✔
4462

3✔
4463
        // Update the access manager with the access permission for this peer.
3✔
4464
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4465

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

3✔
4469
        s.addPeer(p)
3✔
4470

3✔
4471
        // Once we have successfully added the peer to the server, we can
3✔
4472
        // delete the previous error buffer from the server's map of error
3✔
4473
        // buffers.
3✔
4474
        delete(s.peerErrors, pkStr)
3✔
4475

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

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

4490
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4491

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

×
4498
                return
×
4499
        }
×
4500

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

4506
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4507
        // be human-readable.
4508
        pubStr := string(pubBytes)
3✔
4509

3✔
4510
        s.peersByPub[pubStr] = p
3✔
4511

3✔
4512
        if p.Inbound() {
6✔
4513
                s.inboundPeers[pubStr] = p
3✔
4514
        } else {
6✔
4515
                s.outboundPeers[pubStr] = p
3✔
4516
        }
3✔
4517

4518
        // Inform the peer notifier of a peer online event so that it can be reported
4519
        // to clients listening for peer events.
4520
        var pubKey [33]byte
3✔
4521
        copy(pubKey[:], pubBytes)
3✔
4522
}
4523

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

3✔
4536
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4537

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

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

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

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

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

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

3✔
4572
        s.mu.Lock()
3✔
4573
        defer s.mu.Unlock()
3✔
4574

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

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

3✔
4590
        // Since the peer has been fully initialized, now it's time to notify
3✔
4591
        // the RPC about the peer online event.
3✔
4592
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
3✔
4593
}
4594

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

3✔
4609
        ctx := btclog.WithCtx(
3✔
4610
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4611
        )
3✔
4612

3✔
4613
        p.WaitForDisconnect(ready)
3✔
4614

3✔
4615
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4616

3✔
4617
        // If the server is exiting then we can bail out early ourselves as all
3✔
4618
        // the other sub-systems will already be shutting down.
3✔
4619
        if s.Stopped() {
6✔
4620
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4621
                return
3✔
4622
        }
3✔
4623

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

3✔
4630
        pubKey := p.IdentityKey()
3✔
4631

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

3✔
4636
        // Tell the switch to remove all links associated with this peer.
3✔
4637
        // Passing nil as the target link indicates that all links associated
3✔
4638
        // with this interface should be closed.
3✔
4639
        //
3✔
4640
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4641
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4642
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4643
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4644
        }
×
4645

4646
        for _, link := range links {
6✔
4647
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4648
        }
3✔
4649

4650
        s.mu.Lock()
3✔
4651
        defer s.mu.Unlock()
3✔
4652

3✔
4653
        // If there were any notification requests for when this peer
3✔
4654
        // disconnected, we can trigger them now.
3✔
4655
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
3✔
4656
        pubStr := string(pubKey.SerializeCompressed())
3✔
4657
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4658
                close(offlineChan)
3✔
4659
        }
3✔
4660
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4661

3✔
4662
        // If the server has already removed this peer, we can short circuit the
3✔
4663
        // peer termination watcher and skip cleanup.
3✔
4664
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4665
                delete(s.ignorePeerTermination, p)
3✔
4666

3✔
4667
                pubKey := p.PubKey()
3✔
4668
                pubStr := string(pubKey[:])
3✔
4669

3✔
4670
                // If a connection callback is present, we'll go ahead and
3✔
4671
                // execute it now that previous peer has fully disconnected. If
3✔
4672
                // the callback is not present, this likely implies the peer was
3✔
4673
                // purposefully disconnected via RPC, and that no reconnect
3✔
4674
                // should be attempted.
3✔
4675
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4676
                if ok {
6✔
4677
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4678
                        connCallback()
3✔
4679
                }
3✔
4680
                return
3✔
4681
        }
4682

4683
        // First, cleanup any remaining state the server has regarding the peer
4684
        // in question.
4685
        s.removePeerUnsafe(ctx, p)
3✔
4686

3✔
4687
        // Next, check to see if this is a persistent peer or not.
3✔
4688
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4689
                return
3✔
4690
        }
3✔
4691

4692
        // Get the last address that we used to connect to the peer.
4693
        addrs := []net.Addr{
3✔
4694
                p.NetAddress().Address,
3✔
4695
        }
3✔
4696

3✔
4697
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4698
        // reconnection purposes.
3✔
4699
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4700
        switch {
3✔
4701
        // We found advertised addresses, so use them.
4702
        case err == nil:
3✔
4703
                addrs = advertisedAddrs
3✔
4704

4705
        // The peer doesn't have an advertised address.
4706
        case err == errNoAdvertisedAddr:
3✔
4707
                // If it is an outbound peer then we fall back to the existing
3✔
4708
                // peer address.
3✔
4709
                if !p.Inbound() {
6✔
4710
                        break
3✔
4711
                }
4712

4713
                // Fall back to the existing peer address if
4714
                // we're not accepting connections over Tor.
4715
                if s.torController == nil {
6✔
4716
                        break
3✔
4717
                }
4718

4719
                // If we are, the peer's address won't be known
4720
                // to us (we'll see a private address, which is
4721
                // the address used by our onion service to dial
4722
                // to lnd), so we don't have enough information
4723
                // to attempt a reconnect.
4724
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4725
                        "to inbound peer without advertised address")
×
4726
                return
×
4727

4728
        // We came across an error retrieving an advertised
4729
        // address, log it, and fall back to the existing peer
4730
        // address.
4731
        default:
3✔
4732
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4733
                        "address for peer", err)
3✔
4734
        }
4735

4736
        // Make an easy lookup map so that we can check if an address
4737
        // is already in the address list that we have stored for this peer.
4738
        existingAddrs := make(map[string]bool)
3✔
4739
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4740
                existingAddrs[addr.String()] = true
3✔
4741
        }
3✔
4742

4743
        // Add any missing addresses for this peer to persistentPeerAddr.
4744
        for _, addr := range addrs {
6✔
4745
                if existingAddrs[addr.String()] {
3✔
4746
                        continue
×
4747
                }
4748

4749
                s.persistentPeerAddrs[pubStr] = append(
3✔
4750
                        s.persistentPeerAddrs[pubStr],
3✔
4751
                        &lnwire.NetAddress{
3✔
4752
                                IdentityKey: p.IdentityKey(),
3✔
4753
                                Address:     addr,
3✔
4754
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4755
                        },
3✔
4756
                )
3✔
4757
        }
4758

4759
        // Record the computed backoff in the backoff map.
4760
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4761
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4762

3✔
4763
        // Initialize a retry canceller for this peer if one does not
3✔
4764
        // exist.
3✔
4765
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4766
        if !ok {
6✔
4767
                cancelChan = make(chan struct{})
3✔
4768
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4769
        }
3✔
4770

4771
        // We choose not to wait group this go routine since the Connect
4772
        // call can stall for arbitrarily long if we shutdown while an
4773
        // outbound connection attempt is being made.
4774
        go func() {
6✔
4775
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4776
                        "re-establishment to persistent peer",
3✔
4777
                        "reconnecting_in", backoff)
3✔
4778

3✔
4779
                select {
3✔
4780
                case <-time.After(backoff):
3✔
4781
                case <-cancelChan:
3✔
4782
                        return
3✔
4783
                case <-s.quit:
3✔
4784
                        return
3✔
4785
                }
4786

4787
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4788
                        "connection")
3✔
4789

3✔
4790
                s.connectToPersistentPeer(pubStr)
3✔
4791
        }()
4792
}
4793

4794
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4795
// to connect to the peer. It creates connection requests if there are
4796
// currently none for a given address and it removes old connection requests
4797
// if the associated address is no longer in the latest address list for the
4798
// peer.
4799
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4800
        s.mu.Lock()
3✔
4801
        defer s.mu.Unlock()
3✔
4802

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

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

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

4832
                // If the existing connection request is using an address that
4833
                // is not one of the latest advertised addresses for the peer
4834
                // then we remove the connecting request from the connection
4835
                // manager.
4836
                case false:
3✔
4837
                        srvrLog.Info(
3✔
4838
                                "Removing conn req:", connReq.Addr.String(),
3✔
4839
                        )
3✔
4840
                        s.connMgr.Remove(connReq.ID())
3✔
4841
                }
4842
        }
4843

4844
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4845

3✔
4846
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4847
        if !ok {
6✔
4848
                cancelChan = make(chan struct{})
3✔
4849
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4850
        }
3✔
4851

4852
        // Any addresses left in addrMap are new ones that we have not made
4853
        // connection requests for. So create new connection requests for those.
4854
        // If there is more than one address in the address map, stagger the
4855
        // creation of the connection requests for those.
4856
        go func() {
6✔
4857
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4858
                defer ticker.Stop()
3✔
4859

3✔
4860
                for _, addr := range addrMap {
6✔
4861
                        // Send the persistent connection request to the
3✔
4862
                        // connection manager, saving the request itself so we
3✔
4863
                        // can cancel/restart the process as needed.
3✔
4864
                        connReq := &connmgr.ConnReq{
3✔
4865
                                Addr:      addr,
3✔
4866
                                Permanent: true,
3✔
4867
                        }
3✔
4868

3✔
4869
                        s.mu.Lock()
3✔
4870
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4871
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4872
                        )
3✔
4873
                        s.mu.Unlock()
3✔
4874

3✔
4875
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4876
                                "channel peer %v", addr)
3✔
4877

3✔
4878
                        go s.connMgr.Connect(connReq)
3✔
4879

3✔
4880
                        select {
3✔
4881
                        case <-s.quit:
3✔
4882
                                return
3✔
4883
                        case <-cancelChan:
3✔
4884
                                return
3✔
4885
                        case <-ticker.C:
3✔
4886
                        }
4887
                }
4888
        }()
4889
}
4890

4891
// removePeerUnsafe removes the passed peer from the server's state of all
4892
// active peers.
4893
//
4894
// NOTE: Server mutex must be held when calling this function.
4895
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
4896
        if p == nil {
3✔
4897
                return
×
4898
        }
×
4899

4900
        srvrLog.DebugS(ctx, "Removing peer")
3✔
4901

3✔
4902
        // Exit early if we have already been instructed to shutdown, the peers
3✔
4903
        // will be disconnected in the server shutdown process.
3✔
4904
        if s.Stopped() {
3✔
4905
                return
×
4906
        }
×
4907

4908
        // Capture the peer's public key and string representation.
4909
        pKey := p.PubKey()
3✔
4910
        pubSer := pKey[:]
3✔
4911
        pubStr := string(pubSer)
3✔
4912

3✔
4913
        delete(s.peersByPub, pubStr)
3✔
4914

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

4921
        // When removing the peer we make sure to disconnect it asynchronously
4922
        // to avoid blocking the main server goroutine because it is holding the
4923
        // server's mutex. Disconnecting the peer might block and wait until the
4924
        // peer has fully started up. This can happen if an inbound and outbound
4925
        // race condition occurs.
4926
        s.wg.Add(1)
3✔
4927
        go func() {
6✔
4928
                defer s.wg.Done()
3✔
4929

3✔
4930
                p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
3✔
4931

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

4938
                // Remove the peer's access permission from the access manager.
4939
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
4940
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
4941

3✔
4942
                // Copy the peer's error buffer across to the server if it has
3✔
4943
                // any items in it so that we can restore peer errors across
3✔
4944
                // connections. We need to look up the error after the peer has
3✔
4945
                // been disconnected because we write the error in the
3✔
4946
                // `Disconnect` method.
3✔
4947
                s.mu.Lock()
3✔
4948
                if p.ErrorBuffer().Total() > 0 {
6✔
4949
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4950
                }
3✔
4951
                s.mu.Unlock()
3✔
4952

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

3✔
4958
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4959
        }()
4960
}
4961

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

3✔
4970
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4971

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

3✔
4978
        // Ensure we're not already connected to this peer.
3✔
4979
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4980

3✔
4981
        // When there's no error it means we already have a connection with this
3✔
4982
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
4983
        // set, we will ignore the existing connection and continue.
3✔
4984
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
4985
                s.mu.Unlock()
3✔
4986
                return &errPeerAlreadyConnected{peer: peer}
3✔
4987
        }
3✔
4988

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

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

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

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

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

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

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

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

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

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

5061
        close(errChan)
3✔
5062

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

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

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

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

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

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

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

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

3✔
5098
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5099
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5100
        //
3✔
5101
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5102
        // goroutine because we might hold the server's mutex.
3✔
5103
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5104

3✔
5105
        return nil
3✔
5106
}
5107

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

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

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

×
5129
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5130
                return req.Updates, req.Err
×
5131
        }
×
5132
        req.Peer = peer
3✔
5133
        s.mu.RUnlock()
3✔
5134

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

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

×
5155
                return req.Updates, req.Err
×
5156
        }
×
5157

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

3✔
5164
        return req.Updates, req.Err
3✔
5165
}
5166

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

3✔
5174
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5175
        for _, peer := range s.peersByPub {
6✔
5176
                peers = append(peers, peer)
3✔
5177
        }
3✔
5178

5179
        return peers
3✔
5180
}
5181

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

5193
        // Using 1/10 of our duration as a margin, compute a random offset to
5194
        // avoid the nodes entering connection cycles.
5195
        margin := nextBackoff / 10
3✔
5196

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

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

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

5214
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5215
func (s *server) fetchNodeAdvertisedAddrs(ctx context.Context,
5216
        pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
5217

3✔
5218
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5219
        if err != nil {
3✔
5220
                return nil, err
×
5221
        }
×
5222

5223
        node, err := s.v1Graph.FetchNode(ctx, vertex)
3✔
5224
        if err != nil {
6✔
5225
                return nil, err
3✔
5226
        }
3✔
5227

5228
        if len(node.Addresses) == 0 {
6✔
5229
                return nil, errNoAdvertisedAddr
3✔
5230
        }
3✔
5231

5232
        return node.Addresses, nil
3✔
5233
}
5234

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

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

5247
                return netann.ExtractChannelUpdate(
3✔
5248
                        ourPubKey[:], info, edge1, edge2,
3✔
5249
                )
3✔
5250
        }
5251
}
5252

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

3✔
5259
        var (
3✔
5260
                peerAlias    *lnwire.ShortChannelID
3✔
5261
                defaultAlias lnwire.ShortChannelID
3✔
5262
        )
3✔
5263

3✔
5264
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5265

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

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

5286
// SendCustomMessage sends a custom message to the peer with the specified
5287
// pubkey.
5288
func (s *server) SendCustomMessage(ctx context.Context, peerPub [33]byte,
5289
        msgType lnwire.MessageType, data []byte) error {
3✔
5290

3✔
5291
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5292
        if err != nil {
6✔
5293
                return err
3✔
5294
        }
3✔
5295

5296
        // We'll wait until the peer is active, but also listen for
5297
        // cancellation.
5298
        select {
3✔
5299
        case <-peer.ActiveSignal():
3✔
5300
        case <-peer.QuitSignal():
×
5301
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5302
        case <-s.quit:
×
5303
                return ErrServerShuttingDown
×
5304
        case <-ctx.Done():
×
5305
                return ctx.Err()
×
5306
        }
5307

5308
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5309
        if err != nil {
6✔
5310
                return err
3✔
5311
        }
3✔
5312

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

5318
// SendOnionMessage sends a custom message to the peer with the specified
5319
// pubkey.
5320
// TODO(gijs): change this message to include path finding.
5321
func (s *server) SendOnionMessage(ctx context.Context, peerPub [33]byte,
5322
        pathKey *btcec.PublicKey, onion []byte) error {
3✔
5323

3✔
5324
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5325
        if err != nil {
3✔
5326
                return err
×
5327
        }
×
5328

5329
        // We'll wait until the peer is active, but also listen for
5330
        // cancellation.
5331
        select {
3✔
5332
        case <-peer.ActiveSignal():
3✔
5333
        case <-peer.QuitSignal():
×
5334
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5335
        case <-s.quit:
×
5336
                return ErrServerShuttingDown
×
5337
        case <-ctx.Done():
×
5338
                return ctx.Err()
×
5339
        }
5340

5341
        msg := lnwire.NewOnionMessage(pathKey, onion)
3✔
5342

3✔
5343
        // Send the message as low-priority. For now we assume that all
3✔
5344
        // application-defined message are low priority.
3✔
5345
        return peer.SendMessageLazy(true, msg)
3✔
5346
}
5347

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

3✔
5356
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5357
                sweepAddr, err := wallet.NewAddress(
3✔
5358
                        lnwallet.TaprootPubkey, false,
3✔
5359
                        lnwallet.DefaultAccountName,
3✔
5360
                )
3✔
5361
                if err != nil {
3✔
5362
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5363
                }
×
5364

5365
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5366
                if err != nil {
3✔
5367
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5368
                }
×
5369

5370
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5371
                        wallet, netParams, addr,
3✔
5372
                )
3✔
5373
                if err != nil {
3✔
5374
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5375
                }
×
5376

5377
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5378
                        DeliveryAddress: addr,
3✔
5379
                        InternalKey:     internalKeyDesc,
3✔
5380
                })
3✔
5381
        }
5382
}
5383

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

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

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

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

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

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

5430
        return closedSCIDs
3✔
5431
}
5432

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

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

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

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

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

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

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

5471
        return beat, nil
3✔
5472
}
5473

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

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

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

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

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

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

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

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

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

5527
        return closeUpdates, nil
3✔
5528
}
5529

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

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

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

5556
        return updates, nil
3✔
5557
}
5558

5559
// calculateNodeAnnouncementTimestamp returns the timestamp to use for a node
5560
// announcement, ensuring it's at least one second after the previously
5561
// persisted timestamp. This ensures BOLT-07 compliance, which requires node
5562
// announcements to have strictly increasing timestamps.
5563
func calculateNodeAnnouncementTimestamp(persistedTime,
5564
        currentTime time.Time) time.Time {
12✔
5565

12✔
5566
        if persistedTime.Unix() >= currentTime.Unix() {
21✔
5567
                return persistedTime.Add(time.Second)
9✔
5568
        }
9✔
5569

5570
        return currentTime
6✔
5571
}
5572

5573
// setSelfNode configures and sets the server's self node. It sets the node
5574
// announcement, signs it, and updates the source node in the graph. When
5575
// determining values such as color and alias, the method prioritizes values
5576
// set in the config, then values previously persisted on disk, and finally
5577
// falls back to the defaults.
5578
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
5579
        listenAddrs []net.Addr) error {
3✔
5580

3✔
5581
        // If we were requested to automatically configure port forwarding,
3✔
5582
        // we'll use the ports that the server will be listening on.
3✔
5583
        externalIPStrings := make([]string, 0, len(s.cfg.ExternalIPs))
3✔
5584
        for _, ip := range s.cfg.ExternalIPs {
6✔
5585
                externalIPStrings = append(externalIPStrings, ip.String())
3✔
5586
        }
3✔
5587
        if s.natTraversal != nil {
3✔
5588
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
5589
                for _, listenAddr := range listenAddrs {
×
5590
                        // At this point, the listen addresses should have
×
5591
                        // already been normalized, so it's safe to ignore the
×
5592
                        // errors.
×
5593
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
5594
                        port, _ := strconv.Atoi(portStr)
×
5595

×
5596
                        listenPorts = append(listenPorts, uint16(port))
×
5597
                }
×
5598

5599
                ips, err := s.configurePortForwarding(listenPorts...)
×
5600
                if err != nil {
×
5601
                        srvrLog.Errorf("Unable to automatically set up port "+
×
5602
                                "forwarding using %s: %v",
×
5603
                                s.natTraversal.Name(), err)
×
5604
                } else {
×
5605
                        srvrLog.Infof("Automatically set up port forwarding "+
×
5606
                                "using %s to advertise external IP",
×
5607
                                s.natTraversal.Name())
×
5608
                        externalIPStrings = append(externalIPStrings, ips...)
×
5609
                }
×
5610
        }
5611

5612
        // Normalize the external IP strings to net.Addr.
5613
        addrs, err := lncfg.NormalizeAddresses(
3✔
5614
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
5615
                s.cfg.net.ResolveTCPAddr,
3✔
5616
        )
3✔
5617
        if err != nil {
3✔
5618
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
5619
        }
×
5620

5621
        // Parse the color from config. We will update this later if the config
5622
        // color is not changed from default (#3399FF) and we have a value in
5623
        // the source node.
5624
        nodeColor, err := lncfg.ParseHexColor(s.cfg.Color)
3✔
5625
        if err != nil {
3✔
5626
                return fmt.Errorf("unable to parse color: %w", err)
×
5627
        }
×
5628

5629
        var (
3✔
5630
                alias          = s.cfg.Alias
3✔
5631
                nodeLastUpdate = time.Now()
3✔
5632
        )
3✔
5633

3✔
5634
        srcNode, err := s.v1Graph.SourceNode(ctx)
3✔
5635
        switch {
3✔
5636
        case err == nil:
3✔
5637
                // If we have a source node persisted in the DB already, then we
3✔
5638
                // just need to make sure that the new LastUpdate time is at
3✔
5639
                // least one second after the last update time.
3✔
5640
                nodeLastUpdate = calculateNodeAnnouncementTimestamp(
3✔
5641
                        srcNode.LastUpdate, nodeLastUpdate,
3✔
5642
                )
3✔
5643

3✔
5644
                // If the color is not changed from default, it means that we
3✔
5645
                // didn't specify a different color in the config. We'll use the
3✔
5646
                // source node's color.
3✔
5647
                if s.cfg.Color == defaultColor {
6✔
5648
                        srcNode.Color.WhenSome(func(rgba color.RGBA) {
6✔
5649
                                nodeColor = rgba
3✔
5650
                        })
3✔
5651
                }
5652

5653
                // If an alias is not specified in the config, we'll use the
5654
                // source node's alias.
5655
                if alias == "" {
6✔
5656
                        srcNode.Alias.WhenSome(func(s string) {
6✔
5657
                                alias = s
3✔
5658
                        })
3✔
5659
                }
5660

5661
                // If the `externalip` is not specified in the config, it means
5662
                // `addrs` will be empty, we'll use the source node's addresses.
5663
                if len(s.cfg.ExternalIPs) == 0 {
6✔
5664
                        addrs = srcNode.Addresses
3✔
5665
                }
3✔
5666

5667
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
3✔
5668
                // If an alias is not specified in the config, we'll use the
3✔
5669
                // default, which is the first 10 bytes of the serialized
3✔
5670
                // pubkey.
3✔
5671
                if alias == "" {
6✔
5672
                        alias = hex.EncodeToString(nodePub[:10])
3✔
5673
                }
3✔
5674

5675
        // If the above cases are not matched, then we have an unhandled non
5676
        // nil error.
5677
        default:
×
5678
                return fmt.Errorf("unable to fetch source node: %w", err)
×
5679
        }
5680

5681
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
5682
        if err != nil {
3✔
5683
                return err
×
5684
        }
×
5685

5686
        // TODO(abdulkbk): potentially find a way to use the source node's
5687
        // features in the self node.
5688
        selfNode := models.NewV1Node(
3✔
5689
                nodePub, &models.NodeV1Fields{
3✔
5690
                        Alias:      nodeAlias.String(),
3✔
5691
                        Color:      nodeColor,
3✔
5692
                        LastUpdate: nodeLastUpdate,
3✔
5693
                        Addresses:  addrs,
3✔
5694
                        Features:   s.featureMgr.GetRaw(feature.SetNodeAnn),
3✔
5695
                },
3✔
5696
        )
3✔
5697

3✔
5698
        // Based on the disk representation of the node announcement generated
3✔
5699
        // above, we'll generate a node announcement that can go out on the
3✔
5700
        // network so we can properly sign it.
3✔
5701
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
5702
        if err != nil {
3✔
5703
                return fmt.Errorf("unable to gen self node ann: %w", err)
×
5704
        }
×
5705

5706
        // With the announcement generated, we'll sign it to properly
5707
        // authenticate the message on the network.
5708
        authSig, err := netann.SignAnnouncement(
3✔
5709
                s.nodeSigner, s.identityKeyLoc, nodeAnn,
3✔
5710
        )
3✔
5711
        if err != nil {
3✔
5712
                return fmt.Errorf("unable to generate signature for self node "+
×
5713
                        "announcement: %v", err)
×
5714
        }
×
5715

5716
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
5717
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
5718
                selfNode.AuthSigBytes,
3✔
5719
        )
3✔
5720
        if err != nil {
3✔
5721
                return err
×
5722
        }
×
5723

5724
        // Finally, we'll update the representation on disk, and update our
5725
        // cached in-memory version as well.
5726
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
3✔
5727
                return fmt.Errorf("can't set self node: %w", err)
×
5728
        }
×
5729

5730
        s.currentNodeAnn = nodeAnn
3✔
5731

3✔
5732
        return nil
3✔
5733
}
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

© 2026 Coveralls, Inc