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

lightningnetwork / lnd / 16170852573

09 Jul 2025 01:36PM UTC coverage: 68.199% (+10.6%) from 57.62%
16170852573

Pull #9868

github

web-flow
Merge e5726a7be into ea32aac77
Pull Request #9868: PoC Onion messaging using `msgmux`

169 of 228 new or added lines in 10 files covered. (74.12%)

17 existing lines in 3 files now uncovered.

137361 of 201411 relevant lines covered (68.2%)

21720.74 hits per line

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

69.67
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

204
        case peerStatusTemporary:
3✔
205
                return "temporary"
3✔
206

207
        case peerStatusProtected:
3✔
208
                return "protected"
3✔
209

210
        default:
×
211
                return "unknown"
×
212
        }
213
}
214

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

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

230
        start sync.Once
231
        stop  sync.Once
232

233
        cfg *Config
234

235
        implCfg *ImplementationCfg
236

237
        // identityECDH is an ECDH capable wrapper for the private key used
238
        // to authenticate any incoming connections.
239
        identityECDH keychain.SingleKeyECDH
240

241
        // identityKeyLoc is the key locator for the above wrapped identity key.
242
        identityKeyLoc keychain.KeyLocator
243

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

248
        chanStatusMgr *netann.ChanStatusManager
249

250
        // listenAddrs is the list of addresses the server is currently
251
        // listening on.
252
        listenAddrs []net.Addr
253

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

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

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

270
        mu sync.RWMutex
271

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

281
        inboundPeers  map[string]*peer.Brontide
282
        outboundPeers map[string]*peer.Brontide
283

284
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
285
        peerDisconnectedListeners map[string][]chan<- struct{}
286

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

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

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

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

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

322
        cc *chainreg.ChainControl
323

324
        fundingMgr *funding.Manager
325

326
        graphDB *graphdb.ChannelGraph
327

328
        chanStateDB *channeldb.ChannelStateDB
329

330
        addrSource channeldb.AddrSource
331

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

336
        invoicesDB invoices.InvoiceDB
337

338
        aliasMgr *aliasmgr.Manager
339

340
        htlcSwitch *htlcswitch.Switch
341

342
        interceptableSwitch *htlcswitch.InterceptableSwitch
343

344
        invoices *invoices.InvoiceRegistry
345

346
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
347

348
        channelNotifier *channelnotifier.ChannelNotifier
349

350
        peerNotifier *peernotifier.PeerNotifier
351

352
        htlcNotifier *htlcswitch.HtlcNotifier
353

354
        witnessBeacon contractcourt.WitnessBeacon
355

356
        breachArbitrator *contractcourt.BreachArbitrator
357

358
        missionController *routing.MissionController
359
        defaultMC         *routing.MissionControl
360

361
        graphBuilder *graph.Builder
362

363
        chanRouter *routing.ChannelRouter
364

365
        controlTower routing.ControlTower
366

367
        authGossiper *discovery.AuthenticatedGossiper
368

369
        localChanMgr *localchans.Manager
370

371
        utxoNursery *contractcourt.UtxoNursery
372

373
        sweeper *sweep.UtxoSweeper
374

375
        chainArb *contractcourt.ChainArbitrator
376

377
        sphinx *hop.OnionProcessor
378

379
        towerClientMgr *wtclient.Manager
380

381
        connMgr *connmgr.ConnManager
382

383
        sigPool *lnwallet.SigPool
384

385
        writePool *pool.Write
386

387
        readPool *pool.Read
388

389
        tlsManager *TLSManager
390

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

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

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

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

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

413
        hostAnn *netann.HostAnnouncer
414

415
        // livenessMonitor monitors that lnd has access to critical resources.
416
        livenessMonitor *healthcheck.Monitor
417

418
        customMessageServer *subscribe.Server
419

420
        onionMessageServer *subscribe.Server
421

422
        // txPublisher is a publisher with fee-bumping capability.
423
        txPublisher *sweep.TxPublisher
424

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

429
        // peerAccessMan implements peer access controls.
430
        peerAccessMan *accessMan
431

432
        quit chan struct{}
433

434
        wg sync.WaitGroup
435
}
436

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

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

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

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

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

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

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

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

492
                                        s.mu.Lock()
3✔
493

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

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

508
                                        s.mu.Unlock()
3✔
509

3✔
510
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
511
                                }
512
                        }
513
                }
514
        }()
515

516
        return nil
3✔
517
}
518

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

524
        // Msg is the custom wire message.
525
        Msg *lnwire.Custom
526
}
527

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

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

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

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

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

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

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

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

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

3✔
599
        var serializedPubKey [33]byte
3✔
600
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
601

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

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

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

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

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

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

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

×
633
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
634
                        "aux controllers")
×
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
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
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
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
674

3✔
675
        s := &server{
3✔
676
                cfg:            cfg,
3✔
677
                implCfg:        implCfg,
3✔
678
                graphDB:        dbs.GraphDB,
3✔
679
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
680
                addrSource:     addrSource,
3✔
681
                miscDB:         dbs.ChanStateDB,
3✔
682
                invoicesDB:     dbs.InvoiceDB,
3✔
683
                cc:             cc,
3✔
684
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
685
                writePool:      writePool,
3✔
686
                readPool:       readPool,
3✔
687
                chansToRestore: chansToRestore,
3✔
688

3✔
689
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
690
                        cc.ChainNotifier,
3✔
691
                ),
3✔
692
                channelNotifier: channelnotifier.New(
3✔
693
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
694
                ),
3✔
695

3✔
696
                identityECDH:   nodeKeyECDH,
3✔
697
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
698
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
699

3✔
700
                listenAddrs: listenAddrs,
3✔
701

3✔
702
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
703
                // schedule
3✔
704
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
705

3✔
706
                torController: torController,
3✔
707

3✔
708
                persistentPeers:         make(map[string]bool),
3✔
709
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
710
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
711
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
712
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
713
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
714
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
715
                scheduledPeerConnection: make(map[string]func()),
3✔
716
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
717

3✔
718
                peersByPub:                make(map[string]*peer.Brontide),
3✔
719
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
720
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
721
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
722
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
723

3✔
724
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
725

3✔
726
                customMessageServer: subscribe.NewServer(),
3✔
727

3✔
728
                onionMessageServer: subscribe.NewServer(),
3✔
729

3✔
730
                tlsManager: tlsManager,
3✔
731

3✔
732
                featureMgr: featureMgr,
3✔
733
                quit:       make(chan struct{}),
3✔
734
        }
3✔
735

3✔
736
        // Start the low-level services once they are initialized.
3✔
737
        //
3✔
738
        // TODO(yy): break the server startup into four steps,
3✔
739
        // 1. init the low-level services.
3✔
740
        // 2. start the low-level services.
3✔
741
        // 3. init the high-level services.
3✔
742
        // 4. start the high-level services.
3✔
743
        if err := s.startLowLevelServices(); err != nil {
3✔
744
                return nil, err
×
745
        }
×
746

747
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
748
        if err != nil {
3✔
749
                return nil, err
×
750
        }
×
751

752
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
753
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
754
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
755
        )
3✔
756
        s.invoices = invoices.NewRegistry(
3✔
757
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
758
        )
3✔
759

3✔
760
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
761

3✔
762
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
763
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
764

3✔
765
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
766
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
767
                if err != nil {
3✔
768
                        return err
×
769
                }
×
770

771
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
772

3✔
773
                return nil
3✔
774
        }
775

776
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
777
        if err != nil {
3✔
778
                return nil, err
×
779
        }
×
780

781
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
782
                DB:                   dbs.ChanStateDB,
3✔
783
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
784
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
785
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
786
                LocalChannelClose: func(pubKey []byte,
3✔
787
                        request *htlcswitch.ChanClose) {
6✔
788

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

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

833
        s.witnessBeacon = newPreimageBeacon(
3✔
834
                dbs.ChanStateDB.NewWitnessCache(),
3✔
835
                s.interceptableSwitch.ForwardPacket,
3✔
836
        )
3✔
837

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

3✔
851
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
852
        if err != nil {
3✔
853
                return nil, err
×
854
        }
×
855
        s.chanStatusMgr = chanStatusMgr
3✔
856

3✔
857
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
858
        // port forwarding for users behind a NAT.
3✔
859
        if cfg.NAT {
3✔
860
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
861

×
862
                discoveryTimeout := time.Duration(10 * time.Second)
×
863

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

×
878
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
879
                                "enabled device")
×
880

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

890
                        s.natTraversal = pmp
×
891
                }
892
        }
893

894
        // If we were requested to automatically configure port forwarding,
895
        // we'll use the ports that the server will be listening on.
896
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
3✔
897
        for idx, ip := range cfg.ExternalIPs {
6✔
898
                externalIPStrings[idx] = ip.String()
3✔
899
        }
3✔
900
        if s.natTraversal != nil {
3✔
901
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
902
                for _, listenAddr := range listenAddrs {
×
903
                        // At this point, the listen addresses should have
×
904
                        // already been normalized, so it's safe to ignore the
×
905
                        // errors.
×
906
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
907
                        port, _ := strconv.Atoi(portStr)
×
908

×
909
                        listenPorts = append(listenPorts, uint16(port))
×
910
                }
×
911

912
                ips, err := s.configurePortForwarding(listenPorts...)
×
913
                if err != nil {
×
914
                        srvrLog.Errorf("Unable to automatically set up port "+
×
915
                                "forwarding using %s: %v",
×
916
                                s.natTraversal.Name(), err)
×
917
                } else {
×
918
                        srvrLog.Infof("Automatically set up port forwarding "+
×
919
                                "using %s to advertise external IP",
×
920
                                s.natTraversal.Name())
×
921
                        externalIPStrings = append(externalIPStrings, ips...)
×
922
                }
×
923
        }
924

925
        // If external IP addresses have been specified, add those to the list
926
        // of this server's addresses.
927
        externalIPs, err := lncfg.NormalizeAddresses(
3✔
928
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
929
                cfg.net.ResolveTCPAddr,
3✔
930
        )
3✔
931
        if err != nil {
3✔
932
                return nil, err
×
933
        }
×
934

935
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
3✔
936
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
937

3✔
938
        // We'll now reconstruct a node announcement based on our current
3✔
939
        // configuration so we can send it out as a sort of heart beat within
3✔
940
        // the network.
3✔
941
        //
3✔
942
        // We'll start by parsing the node color from configuration.
3✔
943
        color, err := lncfg.ParseHexColor(cfg.Color)
3✔
944
        if err != nil {
3✔
945
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
946
                return nil, err
×
947
        }
×
948

949
        // If no alias is provided, default to first 10 characters of public
950
        // key.
951
        alias := cfg.Alias
3✔
952
        if alias == "" {
6✔
953
                alias = hex.EncodeToString(serializedPubKey[:10])
3✔
954
        }
3✔
955
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
956
        if err != nil {
3✔
957
                return nil, err
×
958
        }
×
959

960
        // TODO(elle): All previously persisted node announcement fields (ie,
961
        //  not just LastUpdate) should be consulted here to ensure that we
962
        //  aren't overwriting any fields that may have been set during the
963
        //  last run of lnd.
964
        nodeLastUpdate := time.Now()
3✔
965
        srcNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
966
        switch {
3✔
967
        // If we have a source node persisted in the DB already, then we just
968
        // need to make sure that the new LastUpdate time is at least one
969
        // second after the last update time.
970
        case err == nil:
3✔
971
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
6✔
972
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
3✔
973
                }
3✔
974

975
        // If we don't have a source node persisted in the DB, then we'll
976
        // create a new one with the current time as the LastUpdate.
977
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
3✔
978

979
        // If the above cases are not matched, then we have an unhandled non
980
        // nil error.
981
        default:
×
982
                return nil, fmt.Errorf("unable to fetch source node: %w", err)
×
983
        }
984

985
        selfNode := &models.LightningNode{
3✔
986
                HaveNodeAnnouncement: true,
3✔
987
                LastUpdate:           nodeLastUpdate,
3✔
988
                Addresses:            selfAddrs,
3✔
989
                Alias:                nodeAlias.String(),
3✔
990
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
991
                Color:                color,
3✔
992
        }
3✔
993
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
994

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

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

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

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

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

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

3✔
1055
                        estimator, err = routing.NewAprioriEstimator(
3✔
1056
                                aprioriConfig,
3✔
1057
                        )
3✔
1058
                        if err != nil {
3✔
1059
                                return nil, err
×
1060
                        }
×
1061

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

×
1072
                        estimator, err = routing.NewBimodalEstimator(
×
1073
                                bimodalConfig,
×
1074
                        )
×
1075
                        if err != nil {
×
1076
                                return nil, err
×
1077
                        }
×
1078

1079
                default:
×
1080
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1081
                                routingConfig.ProbabilityEstimatorType)
×
1082
                }
1083
        }
1084

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

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

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

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

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

3✔
1134
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1135

3✔
1136
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1137

3✔
1138
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1139
                cfg.Routing.StrictZombiePruning
3✔
1140

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

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

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

1188
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1189

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

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

1234
        accessCfg := &accessManConfig{
3✔
1235
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1236
                        error) {
6✔
1237

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

1247
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1248
        if err != nil {
3✔
1249
                return nil, err
×
1250
        }
×
1251

1252
        s.peerAccessMan = peerAccessMan
3✔
1253

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

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

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

×
1279
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1280
                },
×
1281
        }
1282

1283
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1284
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1285
        )
3✔
1286
        if err != nil {
3✔
1287
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1288
                return nil, err
×
1289
        }
×
1290

1291
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1292
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1293
        )
3✔
1294
        if err != nil {
3✔
1295
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1296
                return nil, err
×
1297
        }
×
1298

1299
        aggregator := sweep.NewBudgetAggregator(
3✔
1300
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1301
                s.implCfg.AuxSweeper,
3✔
1302
        )
3✔
1303

3✔
1304
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1305
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1306
                Wallet:     cc.Wallet,
3✔
1307
                Estimator:  cc.FeeEstimator,
3✔
1308
                Notifier:   cc.ChainNotifier,
3✔
1309
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1310
        })
3✔
1311

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

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

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

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

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

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

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

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

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

3✔
1429
                        // processACK will handle the BreachArbitrator ACKing
3✔
1430
                        // the event.
3✔
1431
                        finalErr := make(chan error, 1)
3✔
1432
                        processACK := func(brarErr error) {
6✔
1433
                                if brarErr != nil {
3✔
1434
                                        finalErr <- brarErr
×
1435
                                        return
×
1436
                                }
×
1437

1438
                                // If the BreachArbitrator successfully handled
1439
                                // the event, we can signal that the handoff
1440
                                // was successful.
1441
                                finalErr <- nil
3✔
1442
                        }
1443

1444
                        event := &contractcourt.ContractBreachEvent{
3✔
1445
                                ChanPoint:         chanPoint,
3✔
1446
                                ProcessACK:        processACK,
3✔
1447
                                BreachRetribution: breachRet,
3✔
1448
                        }
3✔
1449

3✔
1450
                        // Send the contract breach event to the
3✔
1451
                        // BreachArbitrator.
3✔
1452
                        select {
3✔
1453
                        case contractBreaches <- event:
3✔
1454
                        case <-s.quit:
×
1455
                                return ErrServerShuttingDown
×
1456
                        }
1457

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

1483
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1484
                QueryIncomingCircuit: func(
1485
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1486

3✔
1487
                        // Get the circuit map.
3✔
1488
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1489

3✔
1490
                        // Lookup the outgoing circuit.
3✔
1491
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1492
                        if pc == nil {
5✔
1493
                                return nil
2✔
1494
                        }
2✔
1495

1496
                        return &pc.Incoming
3✔
1497
                },
1498
                AuxLeafStore: implCfg.AuxLeafStore,
1499
                AuxSigner:    implCfg.AuxSigner,
1500
                AuxResolver:  implCfg.AuxContractResolver,
1501
        }, dbs.ChanStateDB)
1502

1503
        // Select the configuration and funding parameters for Bitcoin.
1504
        chainCfg := cfg.Bitcoin
3✔
1505
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1506
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1507

3✔
1508
        var chanIDSeed [32]byte
3✔
1509
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1510
                return nil, err
×
1511
        }
×
1512

1513
        // Wrap the DeleteChannelEdges method so that the funding manager can
1514
        // use it without depending on several layers of indirection.
1515
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1516
                *models.ChannelEdgePolicy, error) {
6✔
1517

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

1531
                // Grab our key to find our policy.
1532
                var ourKey [33]byte
3✔
1533
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1534

3✔
1535
                var ourPolicy *models.ChannelEdgePolicy
3✔
1536
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1537
                        ourPolicy = e1
3✔
1538
                } else {
6✔
1539
                        ourPolicy = e2
3✔
1540
                }
3✔
1541

1542
                if ourPolicy == nil {
3✔
1543
                        // Something is wrong, so return an error.
×
1544
                        return nil, fmt.Errorf("we don't have an edge")
×
1545
                }
×
1546

1547
                err = s.graphDB.DeleteChannelEdges(
3✔
1548
                        false, false, scid.ToUint64(),
3✔
1549
                )
3✔
1550
                return ourPolicy, err
3✔
1551
        }
1552

1553
        // For the reservationTimeout and the zombieSweeperInterval different
1554
        // values are set in case we are in a dev environment so enhance test
1555
        // capacilities.
1556
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1557
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1558

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

3✔
1569
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1570
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1571

3✔
1572
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1573
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1574
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1575
        }
3✔
1576

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

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

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

1623
                        minConf := uint64(3)
×
1624
                        maxConf := uint64(6)
×
1625

×
1626
                        // If this is a wumbo channel, then we'll require the
×
1627
                        // max amount of confirmations.
×
1628
                        if chanAmt > MaxFundingAmount {
×
1629
                                return uint16(maxConf)
×
1630
                        }
×
1631

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

3✔
1654
                        // In case the user has explicitly specified
3✔
1655
                        // a default value for the remote delay, we
3✔
1656
                        // use it.
3✔
1657
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1658
                        if defaultDelay > 0 {
6✔
1659
                                return defaultDelay
3✔
1660
                        }
3✔
1661

1662
                        // If this is a wumbo channel, then we'll require the
1663
                        // max value.
1664
                        if chanAmt > MaxFundingAmount {
×
1665
                                return maxRemoteDelay
×
1666
                        }
×
1667

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

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

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

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

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

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

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

1781
        // Assemble a peer notifier which will provide clients with subscriptions
1782
        // to peer online and offline events.
1783
        s.peerNotifier = peernotifier.New()
3✔
1784

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

1800
        if cfg.WtClient.Active {
6✔
1801
                policy := wtpolicy.DefaultPolicy()
3✔
1802
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1803

3✔
1804
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1805
                // protocol operations on sat/kw.
3✔
1806
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1807
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1808
                )
3✔
1809

3✔
1810
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1811

3✔
1812
                if err := policy.Validate(); err != nil {
3✔
1813
                        return nil, err
×
1814
                }
×
1815

1816
                // authDial is the wrapper around the btrontide.Dial for the
1817
                // watchtower.
1818
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1819
                        netAddr *lnwire.NetAddress,
3✔
1820
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1821

3✔
1822
                        return brontide.Dial(
3✔
1823
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1824
                        )
3✔
1825
                }
3✔
1826

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

3✔
1834
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1835
                                nil, chanID,
3✔
1836
                        )
3✔
1837
                        if err != nil {
3✔
1838
                                return nil, 0, err
×
1839
                        }
×
1840

1841
                        br, err := lnwallet.NewBreachRetribution(
3✔
1842
                                channel, commitHeight, 0, nil,
3✔
1843
                                implCfg.AuxLeafStore,
3✔
1844
                                implCfg.AuxContractResolver,
3✔
1845
                        )
3✔
1846
                        if err != nil {
3✔
1847
                                return nil, 0, err
×
1848
                        }
×
1849

1850
                        return br, channel.ChanType, nil
3✔
1851
                }
1852

1853
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1854

3✔
1855
                // Copy the policy for legacy channels and set the blob flag
3✔
1856
                // signalling support for anchor channels.
3✔
1857
                anchorPolicy := policy
3✔
1858
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1859

3✔
1860
                // Copy the policy for legacy channels and set the blob flag
3✔
1861
                // signalling support for taproot channels.
3✔
1862
                taprootPolicy := policy
3✔
1863
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1864
                        blob.FlagTaprootChannel,
3✔
1865
                )
3✔
1866

3✔
1867
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1868
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1869
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1870
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1871
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1872
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1873
                                error) {
6✔
1874

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

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

1903
        if len(cfg.ExternalHosts) != 0 {
3✔
1904
                advertisedIPs := make(map[string]struct{})
×
1905
                for _, addr := range s.currentNodeAnn.Addresses {
×
1906
                        advertisedIPs[addr.String()] = struct{}{}
×
1907
                }
×
1908

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

×
1923
                                        return s.genNodeAnnouncement(
×
1924
                                                nil, modifier...,
×
1925
                                        )
×
1926
                                }),
×
1927
                })
1928
        }
1929

1930
        // Create liveness monitor.
1931
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1932

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

3✔
1939
                // RESOLVE: We are actually partially accepting inbound
3✔
1940
                // connection requests when we call NewListener.
3✔
1941
                listeners[i], err = brontide.NewListener(
3✔
1942
                        nodeKeyECDH, listenAddr.String(),
3✔
1943
                        // TODO(yy): remove this check and unify the inbound
3✔
1944
                        // connection check inside `InboundPeerConnected`.
3✔
1945
                        s.peerAccessMan.checkAcceptIncomingConn,
3✔
1946
                )
3✔
1947
                if err != nil {
3✔
1948
                        return nil, err
×
1949
                }
×
1950
        }
1951

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

3✔
1970
        // Finally, register the subsystems in blockbeat.
3✔
1971
        s.registerBlockConsumers()
3✔
1972

3✔
1973
        return s, nil
3✔
1974
}
1975

1976
// UpdateRoutingConfig is a callback function to update the routing config
1977
// values in the main cfg.
1978
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1979
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1980

3✔
1981
        switch c := cfg.Estimator.Config().(type) {
3✔
1982
        case routing.AprioriConfig:
3✔
1983
                routerCfg.ProbabilityEstimatorType =
3✔
1984
                        routing.AprioriEstimatorName
3✔
1985

3✔
1986
                targetCfg := routerCfg.AprioriConfig
3✔
1987
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1988
                targetCfg.Weight = c.AprioriWeight
3✔
1989
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1990
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1991

1992
        case routing.BimodalConfig:
3✔
1993
                routerCfg.ProbabilityEstimatorType =
3✔
1994
                        routing.BimodalEstimatorName
3✔
1995

3✔
1996
                targetCfg := routerCfg.BimodalConfig
3✔
1997
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1998
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1999
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
2000
        }
2001

2002
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
2003
}
2004

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

2024
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
2025
// used for option_scid_alias channels where the ChannelUpdate to be sent back
2026
// may differ from what is on disk.
2027
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
2028
        error) {
3✔
2029

3✔
2030
        data, err := u.DataToSign()
3✔
2031
        if err != nil {
3✔
2032
                return nil, err
×
2033
        }
×
2034

2035
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
2036
}
2037

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

3✔
2051
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
2052
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
2053
                srvrLog.Info("Disabling chain backend checks for " +
×
2054
                        "nochainbackend mode")
×
2055

×
2056
                chainBackendAttempts = 0
×
2057
        }
×
2058

2059
        chainHealthCheck := healthcheck.NewObservation(
3✔
2060
                "chain backend",
3✔
2061
                cc.HealthCheck,
3✔
2062
                cfg.HealthChecks.ChainCheck.Interval,
3✔
2063
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
2064
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
2065
                chainBackendAttempts,
3✔
2066
        )
3✔
2067

3✔
2068
        diskCheck := healthcheck.NewObservation(
3✔
2069
                "disk space",
3✔
2070
                func() error {
3✔
2071
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2072
                                cfg.LndDir,
×
2073
                        )
×
2074
                        if err != nil {
×
2075
                                return err
×
2076
                        }
×
2077

2078
                        // If we have more free space than we require,
2079
                        // we return a nil error.
2080
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2081
                                return nil
×
2082
                        }
×
2083

2084
                        return fmt.Errorf("require: %v free space, got: %v",
×
2085
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2086
                                free)
×
2087
                },
2088
                cfg.HealthChecks.DiskCheck.Interval,
2089
                cfg.HealthChecks.DiskCheck.Timeout,
2090
                cfg.HealthChecks.DiskCheck.Backoff,
2091
                cfg.HealthChecks.DiskCheck.Attempts,
2092
        )
2093

2094
        tlsHealthCheck := healthcheck.NewObservation(
3✔
2095
                "tls",
3✔
2096
                func() error {
3✔
2097
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2098
                                s.cc.KeyRing,
×
2099
                        )
×
2100
                        if err != nil {
×
2101
                                return err
×
2102
                        }
×
2103
                        if expired {
×
2104
                                return fmt.Errorf("TLS certificate is "+
×
2105
                                        "expired as of %v", expTime)
×
2106
                        }
×
2107

2108
                        // If the certificate is not outdated, no error needs
2109
                        // to be returned
2110
                        return nil
×
2111
                },
2112
                cfg.HealthChecks.TLSCheck.Interval,
2113
                cfg.HealthChecks.TLSCheck.Timeout,
2114
                cfg.HealthChecks.TLSCheck.Backoff,
2115
                cfg.HealthChecks.TLSCheck.Attempts,
2116
        )
2117

2118
        checks := []*healthcheck.Observation{
3✔
2119
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2120
        }
3✔
2121

3✔
2122
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2123
        if s.torController != nil {
3✔
2124
                torConnectionCheck := healthcheck.NewObservation(
×
2125
                        "tor connection",
×
2126
                        func() error {
×
2127
                                return healthcheck.CheckTorServiceStatus(
×
2128
                                        s.torController,
×
2129
                                        func() error {
×
2130
                                                return s.createNewHiddenService(
×
2131
                                                        context.TODO(),
×
2132
                                                )
×
2133
                                        },
×
2134
                                )
2135
                        },
2136
                        cfg.HealthChecks.TorConnection.Interval,
2137
                        cfg.HealthChecks.TorConnection.Timeout,
2138
                        cfg.HealthChecks.TorConnection.Backoff,
2139
                        cfg.HealthChecks.TorConnection.Attempts,
2140
                )
2141
                checks = append(checks, torConnectionCheck)
×
2142
        }
2143

2144
        // If remote signing is enabled, add the healthcheck for the remote
2145
        // signing RPC interface.
2146
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2147
                // Because we have two cascading timeouts here, we need to add
3✔
2148
                // some slack to the "outer" one of them in case the "inner"
3✔
2149
                // returns exactly on time.
3✔
2150
                overhead := time.Millisecond * 10
3✔
2151

3✔
2152
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2153
                        "remote signer connection",
3✔
2154
                        rpcwallet.HealthCheck(
3✔
2155
                                s.cfg.RemoteSigner,
3✔
2156

3✔
2157
                                // For the health check we might to be even
3✔
2158
                                // stricter than the initial/normal connect, so
3✔
2159
                                // we use the health check timeout here.
3✔
2160
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2161
                        ),
3✔
2162
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2163
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2164
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2165
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2166
                )
3✔
2167
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2168
        }
3✔
2169

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

×
2188
                                leader, err := leaderElector.IsLeader(
×
2189
                                        timeoutCtx,
×
2190
                                )
×
2191
                                if err != nil {
×
2192
                                        return fmt.Errorf("unable to check if "+
×
2193
                                                "still leader: %v", err)
×
2194
                                }
×
2195

2196
                                if !leader {
×
2197
                                        srvrLog.Debug("Not the current leader")
×
2198
                                        return fmt.Errorf("not the current " +
×
2199
                                                "leader")
×
2200
                                }
×
2201

2202
                                return nil
×
2203
                        },
2204
                        cfg.HealthChecks.LeaderCheck.Interval,
2205
                        cfg.HealthChecks.LeaderCheck.Timeout,
2206
                        cfg.HealthChecks.LeaderCheck.Backoff,
2207
                        cfg.HealthChecks.LeaderCheck.Attempts,
2208
                )
2209

2210
                checks = append(checks, leaderCheck)
×
2211
        }
2212

2213
        // If we have not disabled all of our health checks, we create a
2214
        // liveness monitor with our configured checks.
2215
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2216
                &healthcheck.Config{
3✔
2217
                        Checks:   checks,
3✔
2218
                        Shutdown: srvrLog.Criticalf,
3✔
2219
                },
3✔
2220
        )
3✔
2221
}
2222

2223
// Started returns true if the server has been started, and false otherwise.
2224
// NOTE: This function is safe for concurrent access.
2225
func (s *server) Started() bool {
3✔
2226
        return atomic.LoadInt32(&s.active) != 0
3✔
2227
}
3✔
2228

2229
// cleaner is used to aggregate "cleanup" functions during an operation that
2230
// starts several subsystems. In case one of the subsystem fails to start
2231
// and a proper resource cleanup is required, the "run" method achieves this
2232
// by running all these added "cleanup" functions.
2233
type cleaner []func() error
2234

2235
// add is used to add a cleanup function to be called when
2236
// the run function is executed.
2237
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2238
        return append(c, cleanup)
3✔
2239
}
3✔
2240

2241
// run is used to run all the previousely added cleanup functions.
2242
func (c cleaner) run() {
×
2243
        for i := len(c) - 1; i >= 0; i-- {
×
2244
                if err := c[i](); err != nil {
×
2245
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2246
                }
×
2247
        }
2248
}
2249

2250
// startLowLevelServices starts the low-level services of the server. These
2251
// services must be started successfully before running the main server. The
2252
// services are,
2253
// 1. the chain notifier.
2254
//
2255
// TODO(yy): identify and add more low-level services here.
2256
func (s *server) startLowLevelServices() error {
3✔
2257
        var startErr error
3✔
2258

3✔
2259
        cleanup := cleaner{}
3✔
2260

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

2266
        if startErr != nil {
3✔
2267
                cleanup.run()
×
2268
        }
×
2269

2270
        return startErr
3✔
2271
}
2272

2273
// Start starts the main daemon server, all requested listeners, and any helper
2274
// goroutines.
2275
// NOTE: This function is safe for concurrent access.
2276
//
2277
//nolint:funlen
2278
func (s *server) Start(ctx context.Context) error {
3✔
2279
        // Get the current blockbeat.
3✔
2280
        beat, err := s.getStartingBeat()
3✔
2281
        if err != nil {
3✔
2282
                return err
×
2283
        }
×
2284

2285
        var startErr error
3✔
2286

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

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

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

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

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

2321
                // Start the notification server. This is used so channel
2322
                // management goroutines can be notified when a funding
2323
                // transaction reaches a sufficient number of confirmations, or
2324
                // when the input for the funding transaction is spent in an
2325
                // attempt at an uncooperative close by the counterparty.
2326
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2327
                if err := s.sigPool.Start(); err != nil {
3✔
2328
                        startErr = err
×
2329
                        return
×
2330
                }
×
2331

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

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

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

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

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

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

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

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

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

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

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

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

2408
                // htlcSwitch must be started before chainArb since the latter
2409
                // relies on htlcSwitch to deliver resolution message upon
2410
                // start.
2411
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2412
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2413
                        startErr = err
×
2414
                        return
×
2415
                }
×
2416

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

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

2429
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
2430
                if err := s.chainArb.Start(beat); err != nil {
3✔
2431
                        startErr = err
×
2432
                        return
×
2433
                }
×
2434

2435
                cleanup = cleanup.add(s.graphDB.Stop)
3✔
2436
                if err := s.graphDB.Start(); err != nil {
3✔
2437
                        startErr = err
×
2438
                        return
×
2439
                }
×
2440

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

2447
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2448
                if err := s.chanRouter.Start(); err != nil {
3✔
2449
                        startErr = err
×
2450
                        return
×
2451
                }
×
2452
                // The authGossiper depends on the chanRouter and therefore
2453
                // should be started after it.
2454
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2455
                if err := s.authGossiper.Start(); err != nil {
3✔
2456
                        startErr = err
×
2457
                        return
×
2458
                }
×
2459

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

2466
                cleanup = cleanup.add(s.sphinx.Stop)
3✔
2467
                if err := s.sphinx.Start(); err != nil {
3✔
2468
                        startErr = err
×
2469
                        return
×
2470
                }
×
2471

2472
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
2473
                if err := s.chanStatusMgr.Start(); err != nil {
3✔
2474
                        startErr = err
×
2475
                        return
×
2476
                }
×
2477

2478
                cleanup = cleanup.add(s.chanEventStore.Stop)
3✔
2479
                if err := s.chanEventStore.Start(); err != nil {
3✔
2480
                        startErr = err
×
2481
                        return
×
2482
                }
×
2483

2484
                cleanup.add(func() error {
3✔
2485
                        s.missionController.StopStoreTickers()
×
2486
                        return nil
×
2487
                })
×
2488
                s.missionController.RunStoreTickers()
3✔
2489

3✔
2490
                // Before we start the connMgr, we'll check to see if we have
3✔
2491
                // any backups to recover. We do this now as we want to ensure
3✔
2492
                // that have all the information we need to handle channel
3✔
2493
                // recovery _before_ we even accept connections from any peers.
3✔
2494
                chanRestorer := &chanDBRestorer{
3✔
2495
                        db:         s.chanStateDB,
3✔
2496
                        secretKeys: s.cc.KeyRing,
3✔
2497
                        chainArb:   s.chainArb,
3✔
2498
                }
3✔
2499
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2500
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2501
                                s.chansToRestore.PackedSingleChanBackups,
×
2502
                                s.cc.KeyRing, chanRestorer, s,
×
2503
                        )
×
2504
                        if err != nil {
×
2505
                                startErr = fmt.Errorf("unable to unpack single "+
×
2506
                                        "backups: %v", err)
×
2507
                                return
×
2508
                        }
×
2509
                }
2510
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2511
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2512
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2513
                                s.cc.KeyRing, chanRestorer, s,
3✔
2514
                        )
3✔
2515
                        if err != nil {
3✔
2516
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2517
                                        "backup: %v", err)
×
2518
                                return
×
2519
                        }
×
2520
                }
2521

2522
                // chanSubSwapper must be started after the `channelNotifier`
2523
                // because it depends on channel events as a synchronization
2524
                // point.
2525
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2526
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2527
                        startErr = err
×
2528
                        return
×
2529
                }
×
2530

2531
                if s.torController != nil {
3✔
2532
                        cleanup = cleanup.add(s.torController.Stop)
×
2533
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2534
                                startErr = err
×
2535
                                return
×
2536
                        }
×
2537
                }
2538

2539
                if s.natTraversal != nil {
3✔
2540
                        s.wg.Add(1)
×
2541
                        go s.watchExternalIP()
×
2542
                }
×
2543

2544
                // Start connmgr last to prevent connections before init.
2545
                cleanup = cleanup.add(func() error {
3✔
2546
                        s.connMgr.Stop()
×
2547
                        return nil
×
2548
                })
×
2549

2550
                // RESOLVE: s.connMgr.Start() is called here, but
2551
                // brontide.NewListener() is called in newServer. This means
2552
                // that we are actually listening and partially accepting
2553
                // inbound connections even before the connMgr starts.
2554
                //
2555
                // TODO(yy): move the log into the connMgr's `Start` method.
2556
                srvrLog.Info("connMgr starting...")
3✔
2557
                s.connMgr.Start()
3✔
2558
                srvrLog.Debug("connMgr started")
3✔
2559

3✔
2560
                // If peers are specified as a config option, we'll add those
3✔
2561
                // peers first.
3✔
2562
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2563
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2564
                                peerAddrCfg,
3✔
2565
                        )
3✔
2566
                        if err != nil {
3✔
2567
                                startErr = fmt.Errorf("unable to parse peer "+
×
2568
                                        "pubkey from config: %v", err)
×
2569
                                return
×
2570
                        }
×
2571
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2572
                        if err != nil {
3✔
2573
                                startErr = fmt.Errorf("unable to parse peer "+
×
2574
                                        "address provided as a config option: "+
×
2575
                                        "%v", err)
×
2576
                                return
×
2577
                        }
×
2578

2579
                        peerAddr := &lnwire.NetAddress{
3✔
2580
                                IdentityKey: parsedPubkey,
3✔
2581
                                Address:     addr,
3✔
2582
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2583
                        }
3✔
2584

3✔
2585
                        err = s.ConnectToPeer(
3✔
2586
                                peerAddr, true,
3✔
2587
                                s.cfg.ConnectionTimeout,
3✔
2588
                        )
3✔
2589
                        if err != nil {
3✔
2590
                                startErr = fmt.Errorf("unable to connect to "+
×
2591
                                        "peer address provided as a config "+
×
2592
                                        "option: %v", err)
×
2593
                                return
×
2594
                        }
×
2595
                }
2596

2597
                // Subscribe to NodeAnnouncements that advertise new addresses
2598
                // our persistent peers.
2599
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2600
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2601
                                "addr: %v", err)
×
2602

×
2603
                        startErr = err
×
2604
                        return
×
2605
                }
×
2606

2607
                // With all the relevant sub-systems started, we'll now attempt
2608
                // to establish persistent connections to our direct channel
2609
                // collaborators within the network. Before doing so however,
2610
                // we'll prune our set of link nodes found within the database
2611
                // to ensure we don't reconnect to any nodes we no longer have
2612
                // open channels with.
2613
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2614
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2615

×
2616
                        startErr = err
×
2617
                        return
×
2618
                }
×
2619

2620
                if err := s.establishPersistentConnections(); err != nil {
3✔
2621
                        srvrLog.Errorf("Failed to establish persistent "+
×
2622
                                "connections: %v", err)
×
2623
                }
×
2624

2625
                // setSeedList is a helper function that turns multiple DNS seed
2626
                // server tuples from the command line or config file into the
2627
                // data structure we need and does a basic formal sanity check
2628
                // in the process.
2629
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2630
                        if len(tuples) == 0 {
×
2631
                                return
×
2632
                        }
×
2633

2634
                        result := make([][2]string, len(tuples))
×
2635
                        for idx, tuple := range tuples {
×
2636
                                tuple = strings.TrimSpace(tuple)
×
2637
                                if len(tuple) == 0 {
×
2638
                                        return
×
2639
                                }
×
2640

2641
                                servers := strings.Split(tuple, ",")
×
2642
                                if len(servers) > 2 || len(servers) == 0 {
×
2643
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2644
                                                "seed tuple: %v", servers)
×
2645
                                        return
×
2646
                                }
×
2647

2648
                                copy(result[idx][:], servers)
×
2649
                        }
2650

2651
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2652
                }
2653

2654
                // Let users overwrite the DNS seed nodes. We only allow them
2655
                // for bitcoin mainnet/testnet/signet.
2656
                if s.cfg.Bitcoin.MainNet {
3✔
2657
                        setSeedList(
×
2658
                                s.cfg.Bitcoin.DNSSeeds,
×
2659
                                chainreg.BitcoinMainnetGenesis,
×
2660
                        )
×
2661
                }
×
2662
                if s.cfg.Bitcoin.TestNet3 {
3✔
2663
                        setSeedList(
×
2664
                                s.cfg.Bitcoin.DNSSeeds,
×
2665
                                chainreg.BitcoinTestnetGenesis,
×
2666
                        )
×
2667
                }
×
2668
                if s.cfg.Bitcoin.TestNet4 {
3✔
2669
                        setSeedList(
×
2670
                                s.cfg.Bitcoin.DNSSeeds,
×
2671
                                chainreg.BitcoinTestnet4Genesis,
×
2672
                        )
×
2673
                }
×
2674
                if s.cfg.Bitcoin.SigNet {
3✔
2675
                        setSeedList(
×
2676
                                s.cfg.Bitcoin.DNSSeeds,
×
2677
                                chainreg.BitcoinSignetGenesis,
×
2678
                        )
×
2679
                }
×
2680

2681
                // If network bootstrapping hasn't been disabled, then we'll
2682
                // configure the set of active bootstrappers, and launch a
2683
                // dedicated goroutine to maintain a set of persistent
2684
                // connections.
2685
                if !s.cfg.NoNetBootstrap {
6✔
2686
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2687
                        if err != nil {
3✔
2688
                                startErr = err
×
2689
                                return
×
2690
                        }
×
2691

2692
                        s.wg.Add(1)
3✔
2693
                        go s.peerBootstrapper(
3✔
2694
                                ctx, defaultMinPeers, bootstrappers,
3✔
2695
                        )
3✔
2696
                } else {
3✔
2697
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2698
                }
3✔
2699

2700
                // Start the blockbeat after all other subsystems have been
2701
                // started so they are ready to receive new blocks.
2702
                cleanup = cleanup.add(func() error {
3✔
2703
                        s.blockbeatDispatcher.Stop()
×
2704
                        return nil
×
2705
                })
×
2706
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2707
                        startErr = err
×
2708
                        return
×
2709
                }
×
2710

2711
                // Set the active flag now that we've completed the full
2712
                // startup.
2713
                atomic.StoreInt32(&s.active, 1)
3✔
2714
        })
2715

2716
        if startErr != nil {
3✔
2717
                cleanup.run()
×
2718
        }
×
2719
        return startErr
3✔
2720
}
2721

2722
// Stop gracefully shutsdown the main daemon server. This function will signal
2723
// any active goroutines, or helper objects to exit, then blocks until they've
2724
// all successfully exited. Additionally, any/all listeners are closed.
2725
// NOTE: This function is safe for concurrent access.
2726
func (s *server) Stop() error {
3✔
2727
        s.stop.Do(func() {
6✔
2728
                atomic.StoreInt32(&s.stopping, 1)
3✔
2729

3✔
2730
                ctx := context.Background()
3✔
2731

3✔
2732
                close(s.quit)
3✔
2733

3✔
2734
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2735
                s.connMgr.Stop()
3✔
2736

3✔
2737
                // Stop dispatching blocks to other systems immediately.
3✔
2738
                s.blockbeatDispatcher.Stop()
3✔
2739

3✔
2740
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2741
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2742
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2743
                }
×
2744
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2745
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2746
                }
×
2747
                if err := s.sphinx.Stop(); err != nil {
3✔
2748
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2749
                }
×
2750
                if err := s.invoices.Stop(); err != nil {
3✔
2751
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2752
                }
×
2753
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2754
                        srvrLog.Warnf("failed to stop interceptable "+
×
2755
                                "switch: %v", err)
×
2756
                }
×
2757
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2758
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2759
                                "modifier: %v", err)
×
2760
                }
×
2761
                if err := s.chanRouter.Stop(); err != nil {
3✔
2762
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2763
                }
×
2764
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2765
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2766
                }
×
2767
                if err := s.graphDB.Stop(); err != nil {
3✔
2768
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2769
                }
×
2770
                if err := s.chainArb.Stop(); err != nil {
3✔
2771
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2772
                }
×
2773
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2774
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2775
                }
×
2776
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2777
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2778
                                err)
×
2779
                }
×
2780
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2781
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2782
                }
×
2783
                if err := s.authGossiper.Stop(); err != nil {
3✔
2784
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2785
                }
×
2786
                if err := s.sweeper.Stop(); err != nil {
3✔
2787
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2788
                }
×
2789
                if err := s.txPublisher.Stop(); err != nil {
3✔
2790
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2791
                }
×
2792
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2793
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2794
                }
×
2795
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2796
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2797
                }
×
2798
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2799
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2800
                }
×
2801

2802
                // Update channel.backup file. Make sure to do it before
2803
                // stopping chanSubSwapper.
2804
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2805
                        ctx, s.chanStateDB, s.addrSource,
3✔
2806
                )
3✔
2807
                if err != nil {
3✔
2808
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2809
                                err)
×
2810
                } else {
3✔
2811
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2812
                        if err != nil {
6✔
2813
                                srvrLog.Warnf("Manual update of channel "+
3✔
2814
                                        "backup failed: %v", err)
3✔
2815
                        }
3✔
2816
                }
2817

2818
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2819
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2820
                }
×
2821
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2822
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2823
                }
×
2824
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2825
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2826
                                err)
×
2827
                }
×
2828
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2829
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2830
                                err)
×
2831
                }
×
2832
                s.missionController.StopStoreTickers()
3✔
2833

3✔
2834
                // Disconnect from each active peers to ensure that
3✔
2835
                // peerTerminationWatchers signal completion to each peer.
3✔
2836
                for _, peer := range s.Peers() {
6✔
2837
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2838
                        if err != nil {
3✔
2839
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2840
                                        "received error: %v", peer.IdentityKey(),
×
2841
                                        err,
×
2842
                                )
×
2843
                        }
×
2844
                }
2845

2846
                // Now that all connections have been torn down, stop the tower
2847
                // client which will reliably flush all queued states to the
2848
                // tower. If this is halted for any reason, the force quit timer
2849
                // will kick in and abort to allow this method to return.
2850
                if s.towerClientMgr != nil {
6✔
2851
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2852
                                srvrLog.Warnf("Unable to shut down tower "+
×
2853
                                        "client manager: %v", err)
×
2854
                        }
×
2855
                }
2856

2857
                if s.hostAnn != nil {
3✔
2858
                        if err := s.hostAnn.Stop(); err != nil {
×
2859
                                srvrLog.Warnf("unable to shut down host "+
×
2860
                                        "annoucner: %v", err)
×
2861
                        }
×
2862
                }
2863

2864
                if s.livenessMonitor != nil {
6✔
2865
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2866
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2867
                                        "monitor: %v", err)
×
2868
                        }
×
2869
                }
2870

2871
                // Wait for all lingering goroutines to quit.
2872
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2873
                s.wg.Wait()
3✔
2874

3✔
2875
                srvrLog.Debug("Stopping buffer pools...")
3✔
2876
                s.sigPool.Stop()
3✔
2877
                s.writePool.Stop()
3✔
2878
                s.readPool.Stop()
3✔
2879
        })
2880

2881
        return nil
3✔
2882
}
2883

2884
// Stopped returns true if the server has been instructed to shutdown.
2885
// NOTE: This function is safe for concurrent access.
2886
func (s *server) Stopped() bool {
3✔
2887
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2888
}
3✔
2889

2890
// configurePortForwarding attempts to set up port forwarding for the different
2891
// ports that the server will be listening on.
2892
//
2893
// NOTE: This should only be used when using some kind of NAT traversal to
2894
// automatically set up forwarding rules.
2895
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2896
        ip, err := s.natTraversal.ExternalIP()
×
2897
        if err != nil {
×
2898
                return nil, err
×
2899
        }
×
2900
        s.lastDetectedIP = ip
×
2901

×
2902
        externalIPs := make([]string, 0, len(ports))
×
2903
        for _, port := range ports {
×
2904
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2905
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2906
                        continue
×
2907
                }
2908

2909
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2910
                externalIPs = append(externalIPs, hostIP)
×
2911
        }
2912

2913
        return externalIPs, nil
×
2914
}
2915

2916
// removePortForwarding attempts to clear the forwarding rules for the different
2917
// ports the server is currently listening on.
2918
//
2919
// NOTE: This should only be used when using some kind of NAT traversal to
2920
// automatically set up forwarding rules.
2921
func (s *server) removePortForwarding() {
×
2922
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2923
        for _, port := range forwardedPorts {
×
2924
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2925
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2926
                                "port %d: %v", port, err)
×
2927
                }
×
2928
        }
2929
}
2930

2931
// watchExternalIP continuously checks for an updated external IP address every
2932
// 15 minutes. Once a new IP address has been detected, it will automatically
2933
// handle port forwarding rules and send updated node announcements to the
2934
// currently connected peers.
2935
//
2936
// NOTE: This MUST be run as a goroutine.
2937
func (s *server) watchExternalIP() {
×
2938
        defer s.wg.Done()
×
2939

×
2940
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2941
        // up by the server.
×
2942
        defer s.removePortForwarding()
×
2943

×
2944
        // Keep track of the external IPs set by the user to avoid replacing
×
2945
        // them when detecting a new IP.
×
2946
        ipsSetByUser := make(map[string]struct{})
×
2947
        for _, ip := range s.cfg.ExternalIPs {
×
2948
                ipsSetByUser[ip.String()] = struct{}{}
×
2949
        }
×
2950

2951
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2952

×
2953
        ticker := time.NewTicker(15 * time.Minute)
×
2954
        defer ticker.Stop()
×
2955
out:
×
2956
        for {
×
2957
                select {
×
2958
                case <-ticker.C:
×
2959
                        // We'll start off by making sure a new IP address has
×
2960
                        // been detected.
×
2961
                        ip, err := s.natTraversal.ExternalIP()
×
2962
                        if err != nil {
×
2963
                                srvrLog.Debugf("Unable to retrieve the "+
×
2964
                                        "external IP address: %v", err)
×
2965
                                continue
×
2966
                        }
2967

2968
                        // Periodically renew the NAT port forwarding.
2969
                        for _, port := range forwardedPorts {
×
2970
                                err := s.natTraversal.AddPortMapping(port)
×
2971
                                if err != nil {
×
2972
                                        srvrLog.Warnf("Unable to automatically "+
×
2973
                                                "re-create port forwarding using %s: %v",
×
2974
                                                s.natTraversal.Name(), err)
×
2975
                                } else {
×
2976
                                        srvrLog.Debugf("Automatically re-created "+
×
2977
                                                "forwarding for port %d using %s to "+
×
2978
                                                "advertise external IP",
×
2979
                                                port, s.natTraversal.Name())
×
2980
                                }
×
2981
                        }
2982

2983
                        if ip.Equal(s.lastDetectedIP) {
×
2984
                                continue
×
2985
                        }
2986

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

×
2989
                        // Next, we'll craft the new addresses that will be
×
2990
                        // included in the new node announcement and advertised
×
2991
                        // to the network. Each address will consist of the new
×
2992
                        // IP detected and one of the currently advertised
×
2993
                        // ports.
×
2994
                        var newAddrs []net.Addr
×
2995
                        for _, port := range forwardedPorts {
×
2996
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2997
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2998
                                if err != nil {
×
2999
                                        srvrLog.Debugf("Unable to resolve "+
×
3000
                                                "host %v: %v", addr, err)
×
3001
                                        continue
×
3002
                                }
3003

3004
                                newAddrs = append(newAddrs, addr)
×
3005
                        }
3006

3007
                        // Skip the update if we weren't able to resolve any of
3008
                        // the new addresses.
3009
                        if len(newAddrs) == 0 {
×
3010
                                srvrLog.Debug("Skipping node announcement " +
×
3011
                                        "update due to not being able to " +
×
3012
                                        "resolve any new addresses")
×
3013
                                continue
×
3014
                        }
3015

3016
                        // Now, we'll need to update the addresses in our node's
3017
                        // announcement in order to propagate the update
3018
                        // throughout the network. We'll only include addresses
3019
                        // that have a different IP from the previous one, as
3020
                        // the previous IP is no longer valid.
3021
                        currentNodeAnn := s.getNodeAnnouncement()
×
3022

×
3023
                        for _, addr := range currentNodeAnn.Addresses {
×
3024
                                host, _, err := net.SplitHostPort(addr.String())
×
3025
                                if err != nil {
×
3026
                                        srvrLog.Debugf("Unable to determine "+
×
3027
                                                "host from address %v: %v",
×
3028
                                                addr, err)
×
3029
                                        continue
×
3030
                                }
3031

3032
                                // We'll also make sure to include external IPs
3033
                                // set manually by the user.
3034
                                _, setByUser := ipsSetByUser[addr.String()]
×
3035
                                if setByUser || host != s.lastDetectedIP.String() {
×
3036
                                        newAddrs = append(newAddrs, addr)
×
3037
                                }
×
3038
                        }
3039

3040
                        // Then, we'll generate a new timestamped node
3041
                        // announcement with the updated addresses and broadcast
3042
                        // it to our peers.
3043
                        newNodeAnn, err := s.genNodeAnnouncement(
×
3044
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
3045
                        )
×
3046
                        if err != nil {
×
3047
                                srvrLog.Debugf("Unable to generate new node "+
×
3048
                                        "announcement: %v", err)
×
3049
                                continue
×
3050
                        }
3051

3052
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3053
                        if err != nil {
×
3054
                                srvrLog.Debugf("Unable to broadcast new node "+
×
3055
                                        "announcement to peers: %v", err)
×
3056
                                continue
×
3057
                        }
3058

3059
                        // Finally, update the last IP seen to the current one.
3060
                        s.lastDetectedIP = ip
×
3061
                case <-s.quit:
×
3062
                        break out
×
3063
                }
3064
        }
3065
}
3066

3067
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3068
// based on the server, and currently active bootstrap mechanisms as defined
3069
// within the current configuration.
3070
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
3071
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
3072

3✔
3073
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
3074

3✔
3075
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
3076
        // this can be used by default if we've already partially seeded the
3✔
3077
        // network.
3✔
3078
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
3079
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
3080
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
3081
        )
3✔
3082
        if err != nil {
3✔
3083
                return nil, err
×
3084
        }
×
3085
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
3086

3✔
3087
        // If this isn't using simnet or regtest mode, then one of our
3✔
3088
        // additional bootstrapping sources will be the set of running DNS
3✔
3089
        // seeds.
3✔
3090
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
3091
                //nolint:ll
×
3092
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
3093

×
3094
                // If we have a set of DNS seeds for this chain, then we'll add
×
3095
                // it as an additional bootstrapping source.
×
3096
                if ok {
×
3097
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3098
                                "seeds: %v", dnsSeeds)
×
3099

×
3100
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3101
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3102
                        )
×
3103
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3104
                }
×
3105
        }
3106

3107
        return bootStrappers, nil
3✔
3108
}
3109

3110
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3111
// needs to ignore, which is made of three parts,
3112
//   - the node itself needs to be skipped as it doesn't make sense to connect
3113
//     to itself.
3114
//   - the peers that already have connections with, as in s.peersByPub.
3115
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3116
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
3✔
3117
        s.mu.RLock()
3✔
3118
        defer s.mu.RUnlock()
3✔
3119

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

3✔
3122
        // We should ignore ourselves from bootstrapping.
3✔
3123
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
3124
        ignore[selfKey] = struct{}{}
3✔
3125

3✔
3126
        // Ignore all connected peers.
3✔
3127
        for _, peer := range s.peersByPub {
3✔
3128
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3129
                ignore[nID] = struct{}{}
×
3130
        }
×
3131

3132
        // Ignore all persistent peers as they have a dedicated reconnecting
3133
        // process.
3134
        for pubKeyStr := range s.persistentPeers {
3✔
3135
                var nID autopilot.NodeID
×
3136
                copy(nID[:], []byte(pubKeyStr))
×
3137
                ignore[nID] = struct{}{}
×
3138
        }
×
3139

3140
        return ignore
3✔
3141
}
3142

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

3✔
3151
        defer s.wg.Done()
3✔
3152

3✔
3153
        // Before we continue, init the ignore peers map.
3✔
3154
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3155

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

3✔
3160
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3161
        // peers.
3✔
3162
        //
3✔
3163
        // We'll use a 15 second backoff, and double the time every time an
3✔
3164
        // epoch fails up to a ceiling.
3✔
3165
        backOff := time.Second * 15
3✔
3166

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

3✔
3172
        // We'll use the number of attempts and errors to determine if we need
3✔
3173
        // to increase the time between discovery epochs.
3✔
3174
        var epochErrors uint32 // To be used atomically.
3✔
3175
        var epochAttempts uint32
3✔
3176

3✔
3177
        for {
6✔
3178
                select {
3✔
3179
                // The ticker has just woken us up, so we'll need to check if
3180
                // we need to attempt to connect our to any more peers.
3181
                case <-sampleTicker.C:
×
3182
                        // Obtain the current number of peers, so we can gauge
×
3183
                        // if we need to sample more peers or not.
×
3184
                        s.mu.RLock()
×
3185
                        numActivePeers := uint32(len(s.peersByPub))
×
3186
                        s.mu.RUnlock()
×
3187

×
3188
                        // If we have enough peers, then we can loop back
×
3189
                        // around to the next round as we're done here.
×
3190
                        if numActivePeers >= numTargetPeers {
×
3191
                                continue
×
3192
                        }
3193

3194
                        // If all of our attempts failed during this last back
3195
                        // off period, then will increase our backoff to 5
3196
                        // minute ceiling to avoid an excessive number of
3197
                        // queries
3198
                        //
3199
                        // TODO(roasbeef): add reverse policy too?
3200

3201
                        if epochAttempts > 0 &&
×
3202
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3203

×
3204
                                sampleTicker.Stop()
×
3205

×
3206
                                backOff *= 2
×
3207
                                if backOff > bootstrapBackOffCeiling {
×
3208
                                        backOff = bootstrapBackOffCeiling
×
3209
                                }
×
3210

3211
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3212
                                        "%v", backOff)
×
3213
                                sampleTicker = time.NewTicker(backOff)
×
3214
                                continue
×
3215
                        }
3216

3217
                        atomic.StoreUint32(&epochErrors, 0)
×
3218
                        epochAttempts = 0
×
3219

×
3220
                        // Since we know need more peers, we'll compute the
×
3221
                        // exact number we need to reach our threshold.
×
3222
                        numNeeded := numTargetPeers - numActivePeers
×
3223

×
3224
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3225
                                "peers", numNeeded)
×
3226

×
3227
                        // With the number of peers we need calculated, we'll
×
3228
                        // query the network bootstrappers to sample a set of
×
3229
                        // random addrs for us.
×
3230
                        //
×
3231
                        // Before we continue, get a copy of the ignore peers
×
3232
                        // map.
×
3233
                        ignoreList = s.createBootstrapIgnorePeers()
×
3234

×
3235
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3236
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3237
                        )
×
3238
                        if err != nil {
×
3239
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3240
                                        "peers: %v", err)
×
3241
                                continue
×
3242
                        }
3243

3244
                        // Finally, we'll launch a new goroutine for each
3245
                        // prospective peer candidates.
3246
                        for _, addr := range peerAddrs {
×
3247
                                epochAttempts++
×
3248

×
3249
                                go func(a *lnwire.NetAddress) {
×
3250
                                        // TODO(roasbeef): can do AS, subnet,
×
3251
                                        // country diversity, etc
×
3252
                                        errChan := make(chan error, 1)
×
3253
                                        s.connectToPeer(
×
3254
                                                a, errChan,
×
3255
                                                s.cfg.ConnectionTimeout,
×
3256
                                        )
×
3257
                                        select {
×
3258
                                        case err := <-errChan:
×
3259
                                                if err == nil {
×
3260
                                                        return
×
3261
                                                }
×
3262

3263
                                                srvrLog.Errorf("Unable to "+
×
3264
                                                        "connect to %v: %v",
×
3265
                                                        a, err)
×
3266
                                                atomic.AddUint32(&epochErrors, 1)
×
3267
                                        case <-s.quit:
×
3268
                                        }
3269
                                }(addr)
3270
                        }
3271
                case <-s.quit:
3✔
3272
                        return
3✔
3273
                }
3274
        }
3275
}
3276

3277
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3278
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3279
// query back off each time we encounter a failure.
3280
const bootstrapBackOffCeiling = time.Minute * 5
3281

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

3✔
3289
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3290
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3291

3✔
3292
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3293
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3294
        var delaySignal <-chan time.Time
3✔
3295
        delayTime := time.Second * 2
3✔
3296

3✔
3297
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3298
        // then the main peer bootstrap logic.
3✔
3299
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3300

3✔
3301
        for attempts := 0; ; attempts++ {
6✔
3302
                // Check if the server has been requested to shut down in order
3✔
3303
                // to prevent blocking.
3✔
3304
                if s.Stopped() {
3✔
3305
                        return
×
3306
                }
×
3307

3308
                // We can exit our aggressive initial peer bootstrapping stage
3309
                // if we've reached out target number of peers.
3310
                s.mu.RLock()
3✔
3311
                numActivePeers := uint32(len(s.peersByPub))
3✔
3312
                s.mu.RUnlock()
3✔
3313

3✔
3314
                if numActivePeers >= numTargetPeers {
5✔
3315
                        return
2✔
3316
                }
2✔
3317

3318
                if attempts > 0 {
4✔
3319
                        srvrLog.Debugf("Waiting %v before trying to locate "+
1✔
3320
                                "bootstrap peers (attempt #%v)", delayTime,
1✔
3321
                                attempts)
1✔
3322

1✔
3323
                        // We've completed at least one iterating and haven't
1✔
3324
                        // finished, so we'll start to insert a delay period
1✔
3325
                        // between each attempt.
1✔
3326
                        delaySignal = time.After(delayTime)
1✔
3327
                        select {
1✔
3328
                        case <-delaySignal:
1✔
3329
                        case <-s.quit:
1✔
3330
                                return
1✔
3331
                        }
3332

3333
                        // After our delay, we'll double the time we wait up to
3334
                        // the max back off period.
3335
                        delayTime *= 2
1✔
3336
                        if delayTime > backOffCeiling {
1✔
3337
                                delayTime = backOffCeiling
×
3338
                        }
×
3339
                }
3340

3341
                // Otherwise, we'll request for the remaining number of peers
3342
                // in order to reach our target.
3343
                peersNeeded := numTargetPeers - numActivePeers
3✔
3344
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3345
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3346
                )
3✔
3347
                if err != nil {
4✔
3348
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
1✔
3349
                                "peers: %v", err)
1✔
3350
                        continue
1✔
3351
                }
3352

3353
                // Then, we'll attempt to establish a connection to the
3354
                // different peer addresses retrieved by our bootstrappers.
3355
                var wg sync.WaitGroup
3✔
3356
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3357
                        wg.Add(1)
3✔
3358
                        go func(addr *lnwire.NetAddress) {
6✔
3359
                                defer wg.Done()
3✔
3360

3✔
3361
                                errChan := make(chan error, 1)
3✔
3362
                                go s.connectToPeer(
3✔
3363
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3364
                                )
3✔
3365

3✔
3366
                                // We'll only allow this connection attempt to
3✔
3367
                                // take up to 3 seconds. This allows us to move
3✔
3368
                                // quickly by discarding peers that are slowing
3✔
3369
                                // us down.
3✔
3370
                                select {
3✔
3371
                                case err := <-errChan:
3✔
3372
                                        if err == nil {
6✔
3373
                                                return
3✔
3374
                                        }
3✔
3375
                                        srvrLog.Errorf("Unable to connect to "+
×
3376
                                                "%v: %v", addr, err)
×
3377
                                // TODO: tune timeout? 3 seconds might be *too*
3378
                                // aggressive but works well.
3379
                                case <-time.After(3 * time.Second):
×
3380
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3381
                                                "to not establishing a "+
×
3382
                                                "connection within 3 seconds",
×
3383
                                                addr)
×
3384
                                case <-s.quit:
×
3385
                                }
3386
                        }(bootstrapAddr)
3387
                }
3388

3389
                wg.Wait()
3✔
3390
        }
3391
}
3392

3393
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3394
// order to listen for inbound connections over Tor.
3395
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3396
        // Determine the different ports the server is listening on. The onion
×
3397
        // service's virtual port will map to these ports and one will be picked
×
3398
        // at random when the onion service is being accessed.
×
3399
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3400
        for _, listenAddr := range s.listenAddrs {
×
3401
                port := listenAddr.(*net.TCPAddr).Port
×
3402
                listenPorts = append(listenPorts, port)
×
3403
        }
×
3404

3405
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3406
        if err != nil {
×
3407
                return err
×
3408
        }
×
3409

3410
        // Once the port mapping has been set, we can go ahead and automatically
3411
        // create our onion service. The service's private key will be saved to
3412
        // disk in order to regain access to this service when restarting `lnd`.
3413
        onionCfg := tor.AddOnionConfig{
×
3414
                VirtualPort: defaultPeerPort,
×
3415
                TargetPorts: listenPorts,
×
3416
                Store: tor.NewOnionFile(
×
3417
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3418
                        encrypter,
×
3419
                ),
×
3420
        }
×
3421

×
3422
        switch {
×
3423
        case s.cfg.Tor.V2:
×
3424
                onionCfg.Type = tor.V2
×
3425
        case s.cfg.Tor.V3:
×
3426
                onionCfg.Type = tor.V3
×
3427
        }
3428

3429
        addr, err := s.torController.AddOnion(onionCfg)
×
3430
        if err != nil {
×
3431
                return err
×
3432
        }
×
3433

3434
        // Now that the onion service has been created, we'll add the onion
3435
        // address it can be reached at to our list of advertised addresses.
3436
        newNodeAnn, err := s.genNodeAnnouncement(
×
3437
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3438
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3439
                },
×
3440
        )
3441
        if err != nil {
×
3442
                return fmt.Errorf("unable to generate new node "+
×
3443
                        "announcement: %v", err)
×
3444
        }
×
3445

3446
        // Finally, we'll update the on-disk version of our announcement so it
3447
        // will eventually propagate to nodes in the network.
3448
        selfNode := &models.LightningNode{
×
3449
                HaveNodeAnnouncement: true,
×
3450
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3451
                Addresses:            newNodeAnn.Addresses,
×
3452
                Alias:                newNodeAnn.Alias.String(),
×
3453
                Features: lnwire.NewFeatureVector(
×
3454
                        newNodeAnn.Features, lnwire.Features,
×
3455
                ),
×
3456
                Color:        newNodeAnn.RGBColor,
×
3457
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3458
        }
×
3459
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3460
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3461
                return fmt.Errorf("can't set self node: %w", err)
×
3462
        }
×
3463

3464
        return nil
×
3465
}
3466

3467
// findChannel finds a channel given a public key and ChannelID. It is an
3468
// optimization that is quicker than seeking for a channel given only the
3469
// ChannelID.
3470
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3471
        *channeldb.OpenChannel, error) {
3✔
3472

3✔
3473
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3474
        if err != nil {
3✔
3475
                return nil, err
×
3476
        }
×
3477

3478
        for _, channel := range nodeChans {
6✔
3479
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3480
                        return channel, nil
3✔
3481
                }
3✔
3482
        }
3483

3484
        return nil, fmt.Errorf("unable to find channel")
3✔
3485
}
3486

3487
// getNodeAnnouncement fetches the current, fully signed node announcement.
3488
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3489
        s.mu.Lock()
3✔
3490
        defer s.mu.Unlock()
3✔
3491

3✔
3492
        return *s.currentNodeAnn
3✔
3493
}
3✔
3494

3495
// genNodeAnnouncement generates and returns the current fully signed node
3496
// announcement. The time stamp of the announcement will be updated in order
3497
// to ensure it propagates through the network.
3498
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3499
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3500

3✔
3501
        s.mu.Lock()
3✔
3502
        defer s.mu.Unlock()
3✔
3503

3✔
3504
        // Create a shallow copy of the current node announcement to work on.
3✔
3505
        // This ensures the original announcement remains unchanged
3✔
3506
        // until the new announcement is fully signed and valid.
3✔
3507
        newNodeAnn := *s.currentNodeAnn
3✔
3508

3✔
3509
        // First, try to update our feature manager with the updated set of
3✔
3510
        // features.
3✔
3511
        if features != nil {
6✔
3512
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3513
                        feature.SetNodeAnn: features,
3✔
3514
                }
3✔
3515
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3516
                if err != nil {
6✔
3517
                        return lnwire.NodeAnnouncement{}, err
3✔
3518
                }
3✔
3519

3520
                // If we could successfully update our feature manager, add
3521
                // an update modifier to include these new features to our
3522
                // set.
3523
                modifiers = append(
3✔
3524
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3525
                )
3✔
3526
        }
3527

3528
        // Always update the timestamp when refreshing to ensure the update
3529
        // propagates.
3530
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3531

3✔
3532
        // Apply the requested changes to the node announcement.
3✔
3533
        for _, modifier := range modifiers {
6✔
3534
                modifier(&newNodeAnn)
3✔
3535
        }
3✔
3536

3537
        // Sign a new update after applying all of the passed modifiers.
3538
        err := netann.SignNodeAnnouncement(
3✔
3539
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3540
        )
3✔
3541
        if err != nil {
3✔
3542
                return lnwire.NodeAnnouncement{}, err
×
3543
        }
×
3544

3545
        // If signing succeeds, update the current announcement.
3546
        *s.currentNodeAnn = newNodeAnn
3✔
3547

3✔
3548
        return *s.currentNodeAnn, nil
3✔
3549
}
3550

3551
// updateAndBroadcastSelfNode generates a new node announcement
3552
// applying the giving modifiers and updating the time stamp
3553
// to ensure it propagates through the network. Then it broadcasts
3554
// it to the network.
3555
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3556
        features *lnwire.RawFeatureVector,
3557
        modifiers ...netann.NodeAnnModifier) error {
3✔
3558

3✔
3559
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3560
        if err != nil {
6✔
3561
                return fmt.Errorf("unable to generate new node "+
3✔
3562
                        "announcement: %v", err)
3✔
3563
        }
3✔
3564

3565
        // Update the on-disk version of our announcement.
3566
        // Load and modify self node istead of creating anew instance so we
3567
        // don't risk overwriting any existing values.
3568
        selfNode, err := s.graphDB.SourceNode(ctx)
3✔
3569
        if err != nil {
3✔
3570
                return fmt.Errorf("unable to get current source node: %w", err)
×
3571
        }
×
3572

3573
        selfNode.HaveNodeAnnouncement = true
3✔
3574
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3575
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3576
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3577
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3578
        selfNode.Color = newNodeAnn.RGBColor
3✔
3579
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3580

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

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

3587
        // Finally, propagate it to the nodes in the network.
3588
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3589
        if err != nil {
3✔
3590
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3591
                        "announcement to peers: %v", err)
×
3592
                return err
×
3593
        }
×
3594

3595
        return nil
3✔
3596
}
3597

3598
type nodeAddresses struct {
3599
        pubKey    *btcec.PublicKey
3600
        addresses []net.Addr
3601
}
3602

3603
// establishPersistentConnections attempts to establish persistent connections
3604
// to all our direct channel collaborators. In order to promote liveness of our
3605
// active channels, we instruct the connection manager to attempt to establish
3606
// and maintain persistent connections to all our direct channel counterparties.
3607
func (s *server) establishPersistentConnections() error {
3✔
3608
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3609
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3610
        // since other PubKey forms can't be compared.
3✔
3611
        nodeAddrsMap := map[string]*nodeAddresses{}
3✔
3612

3✔
3613
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3614
        // attempt to connect to based on our set of previous connections. Set
3✔
3615
        // the reconnection port to the default peer port.
3✔
3616
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3617
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3618
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3619
        }
×
3620

3621
        for _, node := range linkNodes {
6✔
3622
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3623
                nodeAddrs := &nodeAddresses{
3✔
3624
                        pubKey:    node.IdentityPub,
3✔
3625
                        addresses: node.Addresses,
3✔
3626
                }
3✔
3627
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3628
        }
3✔
3629

3630
        // After checking our previous connections for addresses to connect to,
3631
        // iterate through the nodes in our channel graph to find addresses
3632
        // that have been added via NodeAnnouncement messages.
3633
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3634
        // each of the nodes.
3635
        err = s.graphDB.ForEachSourceNodeChannel(func(chanPoint wire.OutPoint,
3✔
3636
                havePolicy bool, channelPeer *models.LightningNode) error {
6✔
3637

3✔
3638
                // If the remote party has announced the channel to us, but we
3✔
3639
                // haven't yet, then we won't have a policy. However, we don't
3✔
3640
                // need this to connect to the peer, so we'll log it and move on.
3✔
3641
                if !havePolicy {
3✔
3642
                        srvrLog.Warnf("No channel policy found for "+
×
3643
                                "ChannelPoint(%v): ", chanPoint)
×
3644
                }
×
3645

3646
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3647

3✔
3648
                // Add all unique addresses from channel
3✔
3649
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3650
                // connect to for this peer.
3✔
3651
                addrSet := make(map[string]net.Addr)
3✔
3652
                for _, addr := range channelPeer.Addresses {
6✔
3653
                        switch addr.(type) {
3✔
3654
                        case *net.TCPAddr:
3✔
3655
                                addrSet[addr.String()] = addr
3✔
3656

3657
                        // We'll only attempt to connect to Tor addresses if Tor
3658
                        // outbound support is enabled.
3659
                        case *tor.OnionAddr:
×
3660
                                if s.cfg.Tor.Active {
×
3661
                                        addrSet[addr.String()] = addr
×
3662
                                }
×
3663
                        }
3664
                }
3665

3666
                // If this peer is also recorded as a link node, we'll add any
3667
                // additional addresses that have not already been selected.
3668
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3669
                if ok {
6✔
3670
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3671
                                switch lnAddress.(type) {
3✔
3672
                                case *net.TCPAddr:
3✔
3673
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3674

3675
                                // We'll only attempt to connect to Tor
3676
                                // addresses if Tor outbound support is enabled.
3677
                                case *tor.OnionAddr:
×
3678
                                        if s.cfg.Tor.Active {
×
3679
                                                addrSet[lnAddress.String()] = lnAddress
×
3680
                                        }
×
3681
                                }
3682
                        }
3683
                }
3684

3685
                // Construct a slice of the deduped addresses.
3686
                var addrs []net.Addr
3✔
3687
                for _, addr := range addrSet {
6✔
3688
                        addrs = append(addrs, addr)
3✔
3689
                }
3✔
3690

3691
                n := &nodeAddresses{
3✔
3692
                        addresses: addrs,
3✔
3693
                }
3✔
3694
                n.pubKey, err = channelPeer.PubKey()
3✔
3695
                if err != nil {
3✔
3696
                        return err
×
3697
                }
×
3698

3699
                nodeAddrsMap[pubStr] = n
3✔
3700
                return nil
3✔
3701
        })
3702
        if err != nil {
3✔
3703
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3704
                        "%v", err)
×
3705

×
3706
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3707
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3708

×
3709
                        return err
×
3710
                }
×
3711
        }
3712

3713
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3714
                len(nodeAddrsMap))
3✔
3715

3✔
3716
        // Acquire and hold server lock until all persistent connection requests
3✔
3717
        // have been recorded and sent to the connection manager.
3✔
3718
        s.mu.Lock()
3✔
3719
        defer s.mu.Unlock()
3✔
3720

3✔
3721
        // Iterate through the combined list of addresses from prior links and
3✔
3722
        // node announcements and attempt to reconnect to each node.
3✔
3723
        var numOutboundConns int
3✔
3724
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3725
                // Add this peer to the set of peers we should maintain a
3✔
3726
                // persistent connection with. We set the value to false to
3✔
3727
                // indicate that we should not continue to reconnect if the
3✔
3728
                // number of channels returns to zero, since this peer has not
3✔
3729
                // been requested as perm by the user.
3✔
3730
                s.persistentPeers[pubStr] = false
3✔
3731
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3732
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3733
                }
3✔
3734

3735
                for _, address := range nodeAddr.addresses {
6✔
3736
                        // Create a wrapper address which couples the IP and
3✔
3737
                        // the pubkey so the brontide authenticated connection
3✔
3738
                        // can be established.
3✔
3739
                        lnAddr := &lnwire.NetAddress{
3✔
3740
                                IdentityKey: nodeAddr.pubKey,
3✔
3741
                                Address:     address,
3✔
3742
                        }
3✔
3743

3✔
3744
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3745
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3746
                }
3✔
3747

3748
                // We'll connect to the first 10 peers immediately, then
3749
                // randomly stagger any remaining connections if the
3750
                // stagger initial reconnect flag is set. This ensures
3751
                // that mobile nodes or nodes with a small number of
3752
                // channels obtain connectivity quickly, but larger
3753
                // nodes are able to disperse the costs of connecting to
3754
                // all peers at once.
3755
                if numOutboundConns < numInstantInitReconnect ||
3✔
3756
                        !s.cfg.StaggerInitialReconnect {
6✔
3757

3✔
3758
                        go s.connectToPersistentPeer(pubStr)
3✔
3759
                } else {
3✔
3760
                        go s.delayInitialReconnect(pubStr)
×
3761
                }
×
3762

3763
                numOutboundConns++
3✔
3764
        }
3765

3766
        return nil
3✔
3767
}
3768

3769
// delayInitialReconnect will attempt a reconnection to the given peer after
3770
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3771
//
3772
// NOTE: This method MUST be run as a goroutine.
3773
func (s *server) delayInitialReconnect(pubStr string) {
×
3774
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3775
        select {
×
3776
        case <-time.After(delay):
×
3777
                s.connectToPersistentPeer(pubStr)
×
3778
        case <-s.quit:
×
3779
        }
3780
}
3781

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

3✔
3788
        s.mu.Lock()
3✔
3789
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3790
                delete(s.persistentPeers, pubKeyStr)
3✔
3791
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3792
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3793
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3794
                s.mu.Unlock()
3✔
3795

3✔
3796
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3797
                        "peer has no open channels", compressedPubKey)
3✔
3798

3✔
3799
                return
3✔
3800
        }
3✔
3801
        s.mu.Unlock()
3✔
3802
}
3803

3804
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3805
// is instead used to remove persistent peer state for a peer that has been
3806
// disconnected for good cause by the server. Currently, a gossip ban from
3807
// sending garbage and the server running out of restricted-access
3808
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3809
// future, this function may expand when more ban criteria is added.
3810
//
3811
// NOTE: The server's write lock MUST be held when this is called.
3812
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3813
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3814
                delete(s.persistentPeers, remotePub)
×
3815
                delete(s.persistentPeersBackoff, remotePub)
×
3816
                delete(s.persistentPeerAddrs, remotePub)
×
3817
                s.cancelConnReqs(remotePub, nil)
×
3818
        }
×
3819
}
3820

3821
// BroadcastMessage sends a request to the server to broadcast a set of
3822
// messages to all peers other than the one specified by the `skips` parameter.
3823
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3824
// the target peers.
3825
//
3826
// NOTE: This function is safe for concurrent access.
3827
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3828
        msgs ...lnwire.Message) error {
3✔
3829

3✔
3830
        // Filter out peers found in the skips map. We synchronize access to
3✔
3831
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3832
        // exact set of peers present at the time of invocation.
3✔
3833
        s.mu.RLock()
3✔
3834
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3835
        for pubStr, sPeer := range s.peersByPub {
6✔
3836
                if skips != nil {
6✔
3837
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3838
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3839
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3840
                                continue
3✔
3841
                        }
3842
                }
3843

3844
                peers = append(peers, sPeer)
3✔
3845
        }
3846
        s.mu.RUnlock()
3✔
3847

3✔
3848
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3849
        // all messages to each of peers.
3✔
3850
        var wg sync.WaitGroup
3✔
3851
        for _, sPeer := range peers {
6✔
3852
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3853
                        sPeer.PubKey())
3✔
3854

3✔
3855
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3856
                wg.Add(1)
3✔
3857
                s.wg.Add(1)
3✔
3858
                go func(p lnpeer.Peer) {
6✔
3859
                        defer s.wg.Done()
3✔
3860
                        defer wg.Done()
3✔
3861

3✔
3862
                        p.SendMessageLazy(false, msgs...)
3✔
3863
                }(sPeer)
3✔
3864
        }
3865

3866
        // Wait for all messages to have been dispatched before returning to
3867
        // caller.
3868
        wg.Wait()
3✔
3869

3✔
3870
        return nil
3✔
3871
}
3872

3873
// NotifyWhenOnline can be called by other subsystems to get notified when a
3874
// particular peer comes online. The peer itself is sent across the peerChan.
3875
//
3876
// NOTE: This function is safe for concurrent access.
3877
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3878
        peerChan chan<- lnpeer.Peer) {
3✔
3879

3✔
3880
        s.mu.Lock()
3✔
3881

3✔
3882
        // Compute the target peer's identifier.
3✔
3883
        pubStr := string(peerKey[:])
3✔
3884

3✔
3885
        // Check if peer is connected.
3✔
3886
        peer, ok := s.peersByPub[pubStr]
3✔
3887
        if ok {
6✔
3888
                // Unlock here so that the mutex isn't held while we are
3✔
3889
                // waiting for the peer to become active.
3✔
3890
                s.mu.Unlock()
3✔
3891

3✔
3892
                // Wait until the peer signals that it is actually active
3✔
3893
                // rather than only in the server's maps.
3✔
3894
                select {
3✔
3895
                case <-peer.ActiveSignal():
3✔
3896
                case <-peer.QuitSignal():
×
3897
                        // The peer quit, so we'll add the channel to the slice
×
3898
                        // and return.
×
3899
                        s.mu.Lock()
×
3900
                        s.peerConnectedListeners[pubStr] = append(
×
3901
                                s.peerConnectedListeners[pubStr], peerChan,
×
3902
                        )
×
3903
                        s.mu.Unlock()
×
3904
                        return
×
3905
                }
3906

3907
                // Connected, can return early.
3908
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3909

3✔
3910
                select {
3✔
3911
                case peerChan <- peer:
3✔
3912
                case <-s.quit:
×
3913
                }
3914

3915
                return
3✔
3916
        }
3917

3918
        // Not connected, store this listener such that it can be notified when
3919
        // the peer comes online.
3920
        s.peerConnectedListeners[pubStr] = append(
3✔
3921
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3922
        )
3✔
3923
        s.mu.Unlock()
3✔
3924
}
3925

3926
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3927
// the given public key has been disconnected. The notification is signaled by
3928
// closing the channel returned.
3929
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3930
        s.mu.Lock()
3✔
3931
        defer s.mu.Unlock()
3✔
3932

3✔
3933
        c := make(chan struct{})
3✔
3934

3✔
3935
        // If the peer is already offline, we can immediately trigger the
3✔
3936
        // notification.
3✔
3937
        peerPubKeyStr := string(peerPubKey[:])
3✔
3938
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3939
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3940
                close(c)
×
3941
                return c
×
3942
        }
×
3943

3944
        // Otherwise, the peer is online, so we'll keep track of the channel to
3945
        // trigger the notification once the server detects the peer
3946
        // disconnects.
3947
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3948
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3949
        )
3✔
3950

3✔
3951
        return c
3✔
3952
}
3953

3954
// FindPeer will return the peer that corresponds to the passed in public key.
3955
// This function is used by the funding manager, allowing it to update the
3956
// daemon's local representation of the remote peer.
3957
//
3958
// NOTE: This function is safe for concurrent access.
3959
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3960
        s.mu.RLock()
3✔
3961
        defer s.mu.RUnlock()
3✔
3962

3✔
3963
        pubStr := string(peerKey.SerializeCompressed())
3✔
3964

3✔
3965
        return s.findPeerByPubStr(pubStr)
3✔
3966
}
3✔
3967

3968
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3969
// which should be a string representation of the peer's serialized, compressed
3970
// public key.
3971
//
3972
// NOTE: This function is safe for concurrent access.
3973
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3974
        s.mu.RLock()
3✔
3975
        defer s.mu.RUnlock()
3✔
3976

3✔
3977
        return s.findPeerByPubStr(pubStr)
3✔
3978
}
3✔
3979

3980
// findPeerByPubStr is an internal method that retrieves the specified peer from
3981
// the server's internal state using.
3982
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3983
        peer, ok := s.peersByPub[pubStr]
3✔
3984
        if !ok {
6✔
3985
                return nil, ErrPeerNotConnected
3✔
3986
        }
3✔
3987

3988
        return peer, nil
3✔
3989
}
3990

3991
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3992
// exponential backoff. If no previous backoff was known, the default is
3993
// returned.
3994
func (s *server) nextPeerBackoff(pubStr string,
3995
        startTime time.Time) time.Duration {
3✔
3996

3✔
3997
        // Now, determine the appropriate backoff to use for the retry.
3✔
3998
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3999
        if !ok {
6✔
4000
                // If an existing backoff was unknown, use the default.
3✔
4001
                return s.cfg.MinBackoff
3✔
4002
        }
3✔
4003

4004
        // If the peer failed to start properly, we'll just use the previous
4005
        // backoff to compute the subsequent randomized exponential backoff
4006
        // duration. This will roughly double on average.
4007
        if startTime.IsZero() {
3✔
4008
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
4009
        }
×
4010

4011
        // The peer succeeded in starting. If the connection didn't last long
4012
        // enough to be considered stable, we'll continue to back off retries
4013
        // with this peer.
4014
        connDuration := time.Since(startTime)
3✔
4015
        if connDuration < defaultStableConnDuration {
6✔
4016
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
4017
        }
3✔
4018

4019
        // The peer succeed in starting and this was stable peer, so we'll
4020
        // reduce the timeout duration by the length of the connection after
4021
        // applying randomized exponential backoff. We'll only apply this in the
4022
        // case that:
4023
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
4024
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
4025
        if relaxedBackoff > s.cfg.MinBackoff {
×
4026
                return relaxedBackoff
×
4027
        }
×
4028

4029
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
4030
        // the stable connection lasted much longer than our previous backoff.
4031
        // To reward such good behavior, we'll reconnect after the default
4032
        // timeout.
4033
        return s.cfg.MinBackoff
×
4034
}
4035

4036
// shouldDropLocalConnection determines if our local connection to a remote peer
4037
// should be dropped in the case of concurrent connection establishment. In
4038
// order to deterministically decide which connection should be dropped, we'll
4039
// utilize the ordering of the local and remote public key. If we didn't use
4040
// such a tie breaker, then we risk _both_ connections erroneously being
4041
// dropped.
4042
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
4043
        localPubBytes := local.SerializeCompressed()
×
4044
        remotePubPbytes := remote.SerializeCompressed()
×
4045

×
4046
        // The connection that comes from the node with a "smaller" pubkey
×
4047
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
4048
        // should drop our established connection.
×
4049
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
4050
}
×
4051

4052
// InboundPeerConnected initializes a new peer in response to a new inbound
4053
// connection.
4054
//
4055
// NOTE: This function is safe for concurrent access.
4056
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
4057
        // Exit early if we have already been instructed to shutdown, this
3✔
4058
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4059
        if s.Stopped() {
3✔
4060
                return
×
4061
        }
×
4062

4063
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4064
        pubSer := nodePub.SerializeCompressed()
3✔
4065
        pubStr := string(pubSer)
3✔
4066

3✔
4067
        var pubBytes [33]byte
3✔
4068
        copy(pubBytes[:], pubSer)
3✔
4069

3✔
4070
        s.mu.Lock()
3✔
4071
        defer s.mu.Unlock()
3✔
4072

3✔
4073
        // If we already have an outbound connection to this peer, then ignore
3✔
4074
        // this new connection.
3✔
4075
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
4076
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
4077
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
4078
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4079

3✔
4080
                conn.Close()
3✔
4081
                return
3✔
4082
        }
3✔
4083

4084
        // If we already have a valid connection that is scheduled to take
4085
        // precedence once the prior peer has finished disconnecting, we'll
4086
        // ignore this connection.
4087
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
4088
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4089
                        "scheduled", conn.RemoteAddr(), p)
×
4090
                conn.Close()
×
4091
                return
×
4092
        }
×
4093

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

3✔
4096
        // Check to see if we already have a connection with this peer. If so,
3✔
4097
        // we may need to drop our existing connection. This prevents us from
3✔
4098
        // having duplicate connections to the same peer. We forgo adding a
3✔
4099
        // default case as we expect these to be the only error values returned
3✔
4100
        // from findPeerByPubStr.
3✔
4101
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4102
        switch err {
3✔
4103
        case ErrPeerNotConnected:
3✔
4104
                // We were unable to locate an existing connection with the
3✔
4105
                // target peer, proceed to connect.
3✔
4106
                s.cancelConnReqs(pubStr, nil)
3✔
4107
                s.peerConnected(conn, nil, true)
3✔
4108

4109
        case nil:
3✔
4110
                ctx := btclog.WithCtx(
3✔
4111
                        context.TODO(),
3✔
4112
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4113
                )
3✔
4114

3✔
4115
                // We already have a connection with the incoming peer. If the
3✔
4116
                // connection we've already established should be kept and is
3✔
4117
                // not of the same type of the new connection (inbound), then
3✔
4118
                // we'll close out the new connection s.t there's only a single
3✔
4119
                // connection between us.
3✔
4120
                localPub := s.identityECDH.PubKey()
3✔
4121
                if !connectedPeer.Inbound() &&
3✔
4122
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
4123

×
4124
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4125
                                "peer, but already have outbound "+
×
4126
                                "connection, dropping conn",
×
4127
                                fmt.Errorf("already have outbound conn"))
×
4128
                        conn.Close()
×
4129
                        return
×
4130
                }
×
4131

4132
                // Otherwise, if we should drop the connection, then we'll
4133
                // disconnect our already connected peer.
4134
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4135

3✔
4136
                s.cancelConnReqs(pubStr, nil)
3✔
4137

3✔
4138
                // Remove the current peer from the server's internal state and
3✔
4139
                // signal that the peer termination watcher does not need to
3✔
4140
                // execute for this peer.
3✔
4141
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4142
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4143
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4144
                        s.peerConnected(conn, nil, true)
3✔
4145
                }
3✔
4146
        }
4147
}
4148

4149
// OutboundPeerConnected initializes a new peer in response to a new outbound
4150
// connection.
4151
// NOTE: This function is safe for concurrent access.
4152
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4153
        // Exit early if we have already been instructed to shutdown, this
3✔
4154
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4155
        if s.Stopped() {
3✔
4156
                return
×
4157
        }
×
4158

4159
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4160
        pubSer := nodePub.SerializeCompressed()
3✔
4161
        pubStr := string(pubSer)
3✔
4162

3✔
4163
        var pubBytes [33]byte
3✔
4164
        copy(pubBytes[:], pubSer)
3✔
4165

3✔
4166
        s.mu.Lock()
3✔
4167
        defer s.mu.Unlock()
3✔
4168

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

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

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

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

4199
                conn.Close()
×
4200
                return
×
4201
        }
4202

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

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

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

4229
        case nil:
3✔
4230
                ctx := btclog.WithCtx(
3✔
4231
                        context.TODO(),
3✔
4232
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4233
                )
3✔
4234

3✔
4235
                // We already have a connection with the incoming peer. If the
3✔
4236
                // connection we've already established should be kept and is
3✔
4237
                // not of the same type of the new connection (outbound), then
3✔
4238
                // we'll close out the new connection s.t there's only a single
3✔
4239
                // connection between us.
3✔
4240
                localPub := s.identityECDH.PubKey()
3✔
4241
                if connectedPeer.Inbound() &&
3✔
4242
                        shouldDropLocalConnection(localPub, nodePub) {
3✔
4243

×
4244
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4245
                                "to peer, but already have inbound "+
×
4246
                                "connection, dropping conn",
×
4247
                                fmt.Errorf("already have inbound conn"))
×
4248
                        if connReq != nil {
×
4249
                                s.connMgr.Remove(connReq.ID())
×
4250
                        }
×
4251
                        conn.Close()
×
4252
                        return
×
4253
                }
4254

4255
                // Otherwise, _their_ connection should be dropped. So we'll
4256
                // disconnect the peer and send the now obsolete peer to the
4257
                // server for garbage collection.
4258
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4259

3✔
4260
                // Remove the current peer from the server's internal state and
3✔
4261
                // signal that the peer termination watcher does not need to
3✔
4262
                // execute for this peer.
3✔
4263
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4264
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4265
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4266
                        s.peerConnected(conn, connReq, false)
3✔
4267
                }
3✔
4268
        }
4269
}
4270

4271
// UnassignedConnID is the default connection ID that a request can have before
4272
// it actually is submitted to the connmgr.
4273
// TODO(conner): move into connmgr package, or better, add connmgr method for
4274
// generating atomic IDs
4275
const UnassignedConnID uint64 = 0
4276

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

4291
        // Next, check to see if we have any outstanding persistent connection
4292
        // requests to this peer. If so, then we'll remove all of these
4293
        // connection requests, and also delete the entry from the map.
4294
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4295
        if !ok {
6✔
4296
                return
3✔
4297
        }
3✔
4298

4299
        for _, connReq := range connReqs {
6✔
4300
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4301

3✔
4302
                // Atomically capture the current request identifier.
3✔
4303
                connID := connReq.ID()
3✔
4304

3✔
4305
                // Skip any zero IDs, this indicates the request has not
3✔
4306
                // yet been schedule.
3✔
4307
                if connID == UnassignedConnID {
3✔
4308
                        continue
×
4309
                }
4310

4311
                // Skip a particular connection ID if instructed.
4312
                if skip != nil && connID == *skip {
6✔
4313
                        continue
3✔
4314
                }
4315

4316
                s.connMgr.Remove(connID)
3✔
4317
        }
4318

4319
        delete(s.persistentConnReqs, pubStr)
3✔
4320
}
4321

4322
// handleCustomMessage dispatches an incoming custom peers message to
4323
// subscribers.
4324
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4325
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4326
                peer, msg.Type)
3✔
4327

3✔
4328
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4329
                Peer: peer,
3✔
4330
                Msg:  msg,
3✔
4331
        })
3✔
4332
}
3✔
4333

4334
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4335
// messages.
4336
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4337
        return s.customMessageServer.Subscribe()
3✔
4338
}
3✔
4339

4340
// SubscribeOnionMessages subscribes to a stream of incoming onion messages.
4341
func (s *server) SubscribeOnionMessages() (*subscribe.Client, error) {
3✔
4342
        return s.onionMessageServer.Subscribe()
3✔
4343
}
3✔
4344

4345
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4346
// the channelNotifier's NotifyOpenChannelEvent.
4347
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4348
        remotePub *btcec.PublicKey) {
3✔
4349

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

4356
        // Notify subscribers about this open channel event.
4357
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4358
}
4359

4360
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4361
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4362
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4363
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4364

3✔
4365
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4366
        // peer.
3✔
4367
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4368
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4369
                        "channel[%v] pending open",
×
4370
                        remotePub.SerializeCompressed(), op)
×
4371
        }
×
4372

4373
        // Notify subscribers about this event.
4374
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4375
}
4376

4377
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4378
// calls the channelNotifier's NotifyFundingTimeout.
4379
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4380
        remotePub *btcec.PublicKey) {
3✔
4381

3✔
4382
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4383
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4384
        if err != nil {
3✔
4385
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4386
                        "channel[%v] pending close",
×
4387
                        remotePub.SerializeCompressed(), op)
×
4388
        }
×
4389

4390
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4391
                // If we encounter an error while attempting to disconnect the
×
4392
                // peer, log the error.
×
4393
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4394
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4395
                }
×
4396
        }
4397

4398
        // Notify subscribers about this event.
4399
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4400
}
4401

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

3✔
4409
        brontideConn := conn.(*brontide.Conn)
3✔
4410
        addr := conn.RemoteAddr()
3✔
4411
        pubKey := brontideConn.RemotePub()
3✔
4412

3✔
4413
        // Only restrict access for inbound connections, which means if the
3✔
4414
        // remote node's public key is banned or the restricted slots are used
3✔
4415
        // up, we will drop the connection.
3✔
4416
        //
3✔
4417
        // TODO(yy): Consider perform this check in
3✔
4418
        // `peerAccessMan.addPeerAccess`.
3✔
4419
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4420
        if inbound && err != nil {
3✔
4421
                pubSer := pubKey.SerializeCompressed()
×
4422

×
4423
                // Clean up the persistent peer maps if we're dropping this
×
4424
                // connection.
×
4425
                s.bannedPersistentPeerConnection(string(pubSer))
×
4426

×
4427
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4428
                        "of restricted-access connection slots: %v.", pubSer,
×
4429
                        err)
×
4430

×
4431
                conn.Close()
×
4432

×
4433
                return
×
4434
        }
×
4435

4436
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4437
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4438

3✔
4439
        peerAddr := &lnwire.NetAddress{
3✔
4440
                IdentityKey: pubKey,
3✔
4441
                Address:     addr,
3✔
4442
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4443
        }
3✔
4444

3✔
4445
        // With the brontide connection established, we'll now craft the feature
3✔
4446
        // vectors to advertise to the remote node.
3✔
4447
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4448
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4449

3✔
4450
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4451
        // found, create a fresh buffer.
3✔
4452
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4453
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4454
        if !ok {
6✔
4455
                var err error
3✔
4456
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4457
                if err != nil {
3✔
4458
                        srvrLog.Errorf("unable to create peer %v", err)
×
4459
                        return
×
4460
                }
×
4461
        }
4462

4463
        // If we directly set the peer.Config TowerClient member to the
4464
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4465
        // the peer.Config's TowerClient member will not evaluate to nil even
4466
        // though the underlying value is nil. To avoid this gotcha which can
4467
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4468
        // TowerClient if needed.
4469
        var towerClient wtclient.ClientManager
3✔
4470
        if s.towerClientMgr != nil {
6✔
4471
                towerClient = s.towerClientMgr
3✔
4472
        }
3✔
4473

4474
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4475
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4476

3✔
4477
        // Now that we've established a connection, create a peer, and it to the
3✔
4478
        // set of currently active peers. Configure the peer with the incoming
3✔
4479
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
3✔
4480
        // offered that would trigger channel closure. In case of outgoing
3✔
4481
        // htlcs, an extra block is added to prevent the channel from being
3✔
4482
        // closed when the htlc is outstanding and a new block comes in.
3✔
4483
        pCfg := peer.Config{
3✔
4484
                Conn:                    brontideConn,
3✔
4485
                ConnReq:                 connReq,
3✔
4486
                Addr:                    peerAddr,
3✔
4487
                Inbound:                 inbound,
3✔
4488
                Features:                initFeatures,
3✔
4489
                LegacyFeatures:          legacyFeatures,
3✔
4490
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
3✔
4491
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
3✔
4492
                ErrorBuffer:             errBuffer,
3✔
4493
                WritePool:               s.writePool,
3✔
4494
                ReadPool:                s.readPool,
3✔
4495
                Switch:                  s.htlcSwitch,
3✔
4496
                InterceptSwitch:         s.interceptableSwitch,
3✔
4497
                ChannelDB:               s.chanStateDB,
3✔
4498
                ChannelGraph:            s.graphDB,
3✔
4499
                ChainArb:                s.chainArb,
3✔
4500
                AuthGossiper:            s.authGossiper,
3✔
4501
                ChanStatusMgr:           s.chanStatusMgr,
3✔
4502
                ChainIO:                 s.cc.ChainIO,
3✔
4503
                FeeEstimator:            s.cc.FeeEstimator,
3✔
4504
                Signer:                  s.cc.Wallet.Cfg.Signer,
3✔
4505
                SigPool:                 s.sigPool,
3✔
4506
                Wallet:                  s.cc.Wallet,
3✔
4507
                ChainNotifier:           s.cc.ChainNotifier,
3✔
4508
                BestBlockView:           s.cc.BestBlockTracker,
3✔
4509
                RoutingPolicy:           s.cc.RoutingPolicy,
3✔
4510
                Sphinx:                  s.sphinx,
3✔
4511
                WitnessBeacon:           s.witnessBeacon,
3✔
4512
                Invoices:                s.invoices,
3✔
4513
                ChannelNotifier:         s.channelNotifier,
3✔
4514
                HtlcNotifier:            s.htlcNotifier,
3✔
4515
                TowerClient:             towerClient,
3✔
4516
                DisconnectPeer:          s.DisconnectPeer,
3✔
4517
                OnionMessageServer:      s.onionMessageServer,
3✔
4518
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
3✔
4519
                        lnwire.NodeAnnouncement, error) {
6✔
4520

3✔
4521
                        return s.genNodeAnnouncement(nil)
3✔
4522
                },
3✔
4523

4524
                PongBuf: s.pongBuf,
4525

4526
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4527

4528
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4529

4530
                FundingManager: s.fundingMgr,
4531

4532
                Hodl:                    s.cfg.Hodl,
4533
                UnsafeReplay:            s.cfg.UnsafeReplay,
4534
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4535
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4536
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4537
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4538
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4539
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4540
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4541
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4542
                HandleCustomMessage:    s.handleCustomMessage,
4543
                GetAliases:             s.aliasMgr.GetAliases,
4544
                RequestAlias:           s.aliasMgr.RequestAlias,
4545
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4546
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4547
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4548
                MaxFeeExposure:         thresholdMSats,
4549
                Quit:                   s.quit,
4550
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4551
                AuxSigner:              s.implCfg.AuxSigner,
4552
                MsgRouter:              s.implCfg.MsgRouter,
4553
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4554
                AuxResolver:            s.implCfg.AuxContractResolver,
4555
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4556
                ShouldFwdExpEndorsement: func() bool {
3✔
4557
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4558
                                return false
3✔
4559
                        }
3✔
4560

4561
                        return clock.NewDefaultClock().Now().Before(
3✔
4562
                                EndorsementExperimentEnd,
3✔
4563
                        )
3✔
4564
                },
4565
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4566
        }
4567

4568
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4569
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4570

3✔
4571
        p := peer.NewBrontide(pCfg)
3✔
4572

3✔
4573
        // Update the access manager with the access permission for this peer.
3✔
4574
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4575

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

3✔
4579
        s.addPeer(p)
3✔
4580

3✔
4581
        // Once we have successfully added the peer to the server, we can
3✔
4582
        // delete the previous error buffer from the server's map of error
3✔
4583
        // buffers.
3✔
4584
        delete(s.peerErrors, pkStr)
3✔
4585

3✔
4586
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4587
        // includes sending and receiving Init messages, which would be a DOS
3✔
4588
        // vector if we held the server's mutex throughout the procedure.
3✔
4589
        s.wg.Add(1)
3✔
4590
        go s.peerInitializer(p)
3✔
4591
}
4592

4593
// addPeer adds the passed peer to the server's global state of all active
4594
// peers.
4595
func (s *server) addPeer(p *peer.Brontide) {
3✔
4596
        if p == nil {
3✔
4597
                return
×
4598
        }
×
4599

4600
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4601

3✔
4602
        // Ignore new peers if we're shutting down.
3✔
4603
        if s.Stopped() {
3✔
4604
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4605
                        pubBytes)
×
4606
                p.Disconnect(ErrServerShuttingDown)
×
4607

×
4608
                return
×
4609
        }
×
4610

4611
        // Track the new peer in our indexes so we can quickly look it up either
4612
        // according to its public key, or its peer ID.
4613
        // TODO(roasbeef): pipe all requests through to the
4614
        // queryHandler/peerManager
4615

4616
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4617
        // be human-readable.
4618
        pubStr := string(pubBytes)
3✔
4619

3✔
4620
        s.peersByPub[pubStr] = p
3✔
4621

3✔
4622
        if p.Inbound() {
6✔
4623
                s.inboundPeers[pubStr] = p
3✔
4624
        } else {
6✔
4625
                s.outboundPeers[pubStr] = p
3✔
4626
        }
3✔
4627

4628
        // Inform the peer notifier of a peer online event so that it can be reported
4629
        // to clients listening for peer events.
4630
        var pubKey [33]byte
3✔
4631
        copy(pubKey[:], pubBytes)
3✔
4632

3✔
4633
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4634
}
4635

4636
// peerInitializer asynchronously starts a newly connected peer after it has
4637
// been added to the server's peer map. This method sets up a
4638
// peerTerminationWatcher for the given peer, and ensures that it executes even
4639
// if the peer failed to start. In the event of a successful connection, this
4640
// method reads the negotiated, local feature-bits and spawns the appropriate
4641
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4642
// be signaled of the new peer once the method returns.
4643
//
4644
// NOTE: This MUST be launched as a goroutine.
4645
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4646
        defer s.wg.Done()
3✔
4647

3✔
4648
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4649

3✔
4650
        // Avoid initializing peers while the server is exiting.
3✔
4651
        if s.Stopped() {
3✔
4652
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4653
                        pubBytes)
×
4654
                return
×
4655
        }
×
4656

4657
        // Create a channel that will be used to signal a successful start of
4658
        // the link. This prevents the peer termination watcher from beginning
4659
        // its duty too early.
4660
        ready := make(chan struct{})
3✔
4661

3✔
4662
        // Before starting the peer, launch a goroutine to watch for the
3✔
4663
        // unexpected termination of this peer, which will ensure all resources
3✔
4664
        // are properly cleaned up, and re-establish persistent connections when
3✔
4665
        // necessary. The peer termination watcher will be short circuited if
3✔
4666
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4667
        // that the server has already handled the removal of this peer.
3✔
4668
        s.wg.Add(1)
3✔
4669
        go s.peerTerminationWatcher(p, ready)
3✔
4670

3✔
4671
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4672
        // will unblock the peerTerminationWatcher.
3✔
4673
        if err := p.Start(); err != nil {
6✔
4674
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4675

3✔
4676
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4677
                return
3✔
4678
        }
3✔
4679

4680
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4681
        // was successful, and to begin watching the peer's wait group.
4682
        close(ready)
3✔
4683

3✔
4684
        s.mu.Lock()
3✔
4685
        defer s.mu.Unlock()
3✔
4686

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

3✔
4690
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4691
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4692
        pubStr := string(pubBytes)
3✔
4693
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4694
                select {
3✔
4695
                case peerChan <- p:
3✔
4696
                case <-s.quit:
×
4697
                        return
×
4698
                }
4699
        }
4700
        delete(s.peerConnectedListeners, pubStr)
3✔
4701
}
4702

4703
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4704
// and then cleans up all resources allocated to the peer, notifies relevant
4705
// sub-systems of its demise, and finally handles re-connecting to the peer if
4706
// it's persistent. If the server intentionally disconnects a peer, it should
4707
// have a corresponding entry in the ignorePeerTermination map which will cause
4708
// the cleanup routine to exit early. The passed `ready` chan is used to
4709
// synchronize when WaitForDisconnect should begin watching on the peer's
4710
// waitgroup. The ready chan should only be signaled if the peer starts
4711
// successfully, otherwise the peer should be disconnected instead.
4712
//
4713
// NOTE: This MUST be launched as a goroutine.
4714
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4715
        defer s.wg.Done()
3✔
4716

3✔
4717
        ctx := btclog.WithCtx(
3✔
4718
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4719
        )
3✔
4720

3✔
4721
        p.WaitForDisconnect(ready)
3✔
4722

3✔
4723
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4724

3✔
4725
        // If the server is exiting then we can bail out early ourselves as all
3✔
4726
        // the other sub-systems will already be shutting down.
3✔
4727
        if s.Stopped() {
6✔
4728
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4729
                return
3✔
4730
        }
3✔
4731

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

3✔
4738
        pubKey := p.IdentityKey()
3✔
4739

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

3✔
4744
        // Tell the switch to remove all links associated with this peer.
3✔
4745
        // Passing nil as the target link indicates that all links associated
3✔
4746
        // with this interface should be closed.
3✔
4747
        //
3✔
4748
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4749
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4750
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4751
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4752
        }
×
4753

4754
        for _, link := range links {
6✔
4755
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4756
        }
3✔
4757

4758
        s.mu.Lock()
3✔
4759
        defer s.mu.Unlock()
3✔
4760

3✔
4761
        // If there were any notification requests for when this peer
3✔
4762
        // disconnected, we can trigger them now.
3✔
4763
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
3✔
4764
        pubStr := string(pubKey.SerializeCompressed())
3✔
4765
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4766
                close(offlineChan)
3✔
4767
        }
3✔
4768
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4769

3✔
4770
        // If the server has already removed this peer, we can short circuit the
3✔
4771
        // peer termination watcher and skip cleanup.
3✔
4772
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4773
                delete(s.ignorePeerTermination, p)
3✔
4774

3✔
4775
                pubKey := p.PubKey()
3✔
4776
                pubStr := string(pubKey[:])
3✔
4777

3✔
4778
                // If a connection callback is present, we'll go ahead and
3✔
4779
                // execute it now that previous peer has fully disconnected. If
3✔
4780
                // the callback is not present, this likely implies the peer was
3✔
4781
                // purposefully disconnected via RPC, and that no reconnect
3✔
4782
                // should be attempted.
3✔
4783
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4784
                if ok {
6✔
4785
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4786
                        connCallback()
3✔
4787
                }
3✔
4788
                return
3✔
4789
        }
4790

4791
        // First, cleanup any remaining state the server has regarding the peer
4792
        // in question.
4793
        s.removePeerUnsafe(ctx, p)
3✔
4794

3✔
4795
        // Next, check to see if this is a persistent peer or not.
3✔
4796
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4797
                return
3✔
4798
        }
3✔
4799

4800
        // Get the last address that we used to connect to the peer.
4801
        addrs := []net.Addr{
3✔
4802
                p.NetAddress().Address,
3✔
4803
        }
3✔
4804

3✔
4805
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4806
        // reconnection purposes.
3✔
4807
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4808
        switch {
3✔
4809
        // We found advertised addresses, so use them.
4810
        case err == nil:
3✔
4811
                addrs = advertisedAddrs
3✔
4812

4813
        // The peer doesn't have an advertised address.
4814
        case err == errNoAdvertisedAddr:
3✔
4815
                // If it is an outbound peer then we fall back to the existing
3✔
4816
                // peer address.
3✔
4817
                if !p.Inbound() {
6✔
4818
                        break
3✔
4819
                }
4820

4821
                // Fall back to the existing peer address if
4822
                // we're not accepting connections over Tor.
4823
                if s.torController == nil {
6✔
4824
                        break
3✔
4825
                }
4826

4827
                // If we are, the peer's address won't be known
4828
                // to us (we'll see a private address, which is
4829
                // the address used by our onion service to dial
4830
                // to lnd), so we don't have enough information
4831
                // to attempt a reconnect.
4832
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4833
                        "to inbound peer without advertised address")
×
4834
                return
×
4835

4836
        // We came across an error retrieving an advertised
4837
        // address, log it, and fall back to the existing peer
4838
        // address.
4839
        default:
3✔
4840
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4841
                        "address for peer", err)
3✔
4842
        }
4843

4844
        // Make an easy lookup map so that we can check if an address
4845
        // is already in the address list that we have stored for this peer.
4846
        existingAddrs := make(map[string]bool)
3✔
4847
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4848
                existingAddrs[addr.String()] = true
3✔
4849
        }
3✔
4850

4851
        // Add any missing addresses for this peer to persistentPeerAddr.
4852
        for _, addr := range addrs {
6✔
4853
                if existingAddrs[addr.String()] {
3✔
4854
                        continue
×
4855
                }
4856

4857
                s.persistentPeerAddrs[pubStr] = append(
3✔
4858
                        s.persistentPeerAddrs[pubStr],
3✔
4859
                        &lnwire.NetAddress{
3✔
4860
                                IdentityKey: p.IdentityKey(),
3✔
4861
                                Address:     addr,
3✔
4862
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4863
                        },
3✔
4864
                )
3✔
4865
        }
4866

4867
        // Record the computed backoff in the backoff map.
4868
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4869
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4870

3✔
4871
        // Initialize a retry canceller for this peer if one does not
3✔
4872
        // exist.
3✔
4873
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4874
        if !ok {
6✔
4875
                cancelChan = make(chan struct{})
3✔
4876
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4877
        }
3✔
4878

4879
        // We choose not to wait group this go routine since the Connect
4880
        // call can stall for arbitrarily long if we shutdown while an
4881
        // outbound connection attempt is being made.
4882
        go func() {
6✔
4883
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4884
                        "re-establishment to persistent peer",
3✔
4885
                        "reconnecting_in", backoff)
3✔
4886

3✔
4887
                select {
3✔
4888
                case <-time.After(backoff):
3✔
4889
                case <-cancelChan:
3✔
4890
                        return
3✔
4891
                case <-s.quit:
3✔
4892
                        return
3✔
4893
                }
4894

4895
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4896
                        "connection")
3✔
4897

3✔
4898
                s.connectToPersistentPeer(pubStr)
3✔
4899
        }()
4900
}
4901

4902
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4903
// to connect to the peer. It creates connection requests if there are
4904
// currently none for a given address and it removes old connection requests
4905
// if the associated address is no longer in the latest address list for the
4906
// peer.
4907
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4908
        s.mu.Lock()
3✔
4909
        defer s.mu.Unlock()
3✔
4910

3✔
4911
        // Create an easy lookup map of the addresses we have stored for the
3✔
4912
        // peer. We will remove entries from this map if we have existing
3✔
4913
        // connection requests for the associated address and then any leftover
3✔
4914
        // entries will indicate which addresses we should create new
3✔
4915
        // connection requests for.
3✔
4916
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4917
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4918
                addrMap[addr.String()] = addr
3✔
4919
        }
3✔
4920

4921
        // Go through each of the existing connection requests and
4922
        // check if they correspond to the latest set of addresses. If
4923
        // there is a connection requests that does not use one of the latest
4924
        // advertised addresses then remove that connection request.
4925
        var updatedConnReqs []*connmgr.ConnReq
3✔
4926
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4927
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4928

3✔
4929
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4930
                // If the existing connection request is using one of the
4931
                // latest advertised addresses for the peer then we add it to
4932
                // updatedConnReqs and remove the associated address from
4933
                // addrMap so that we don't recreate this connReq later on.
4934
                case true:
×
4935
                        updatedConnReqs = append(
×
4936
                                updatedConnReqs, connReq,
×
4937
                        )
×
4938
                        delete(addrMap, lnAddr)
×
4939

4940
                // If the existing connection request is using an address that
4941
                // is not one of the latest advertised addresses for the peer
4942
                // then we remove the connecting request from the connection
4943
                // manager.
4944
                case false:
3✔
4945
                        srvrLog.Info(
3✔
4946
                                "Removing conn req:", connReq.Addr.String(),
3✔
4947
                        )
3✔
4948
                        s.connMgr.Remove(connReq.ID())
3✔
4949
                }
4950
        }
4951

4952
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4953

3✔
4954
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4955
        if !ok {
6✔
4956
                cancelChan = make(chan struct{})
3✔
4957
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4958
        }
3✔
4959

4960
        // Any addresses left in addrMap are new ones that we have not made
4961
        // connection requests for. So create new connection requests for those.
4962
        // If there is more than one address in the address map, stagger the
4963
        // creation of the connection requests for those.
4964
        go func() {
6✔
4965
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4966
                defer ticker.Stop()
3✔
4967

3✔
4968
                for _, addr := range addrMap {
6✔
4969
                        // Send the persistent connection request to the
3✔
4970
                        // connection manager, saving the request itself so we
3✔
4971
                        // can cancel/restart the process as needed.
3✔
4972
                        connReq := &connmgr.ConnReq{
3✔
4973
                                Addr:      addr,
3✔
4974
                                Permanent: true,
3✔
4975
                        }
3✔
4976

3✔
4977
                        s.mu.Lock()
3✔
4978
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4979
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4980
                        )
3✔
4981
                        s.mu.Unlock()
3✔
4982

3✔
4983
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4984
                                "channel peer %v", addr)
3✔
4985

3✔
4986
                        go s.connMgr.Connect(connReq)
3✔
4987

3✔
4988
                        select {
3✔
4989
                        case <-s.quit:
3✔
4990
                                return
3✔
4991
                        case <-cancelChan:
3✔
4992
                                return
3✔
4993
                        case <-ticker.C:
3✔
4994
                        }
4995
                }
4996
        }()
4997
}
4998

4999
// removePeerUnsafe removes the passed peer from the server's state of all
5000
// active peers.
5001
//
5002
// NOTE: Server mutex must be held when calling this function.
5003
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
5004
        if p == nil {
3✔
5005
                return
×
5006
        }
×
5007

5008
        srvrLog.DebugS(ctx, "Removing peer")
3✔
5009

3✔
5010
        // Exit early if we have already been instructed to shutdown, the peers
3✔
5011
        // will be disconnected in the server shutdown process.
3✔
5012
        if s.Stopped() {
3✔
5013
                return
×
5014
        }
×
5015

5016
        // Capture the peer's public key and string representation.
5017
        pKey := p.PubKey()
3✔
5018
        pubSer := pKey[:]
3✔
5019
        pubStr := string(pubSer)
3✔
5020

3✔
5021
        delete(s.peersByPub, pubStr)
3✔
5022

3✔
5023
        if p.Inbound() {
6✔
5024
                delete(s.inboundPeers, pubStr)
3✔
5025
        } else {
6✔
5026
                delete(s.outboundPeers, pubStr)
3✔
5027
        }
3✔
5028

5029
        // When removing the peer we make sure to disconnect it asynchronously
5030
        // to avoid blocking the main server goroutine because it is holding the
5031
        // server's mutex. Disconnecting the peer might block and wait until the
5032
        // peer has fully started up. This can happen if an inbound and outbound
5033
        // race condition occurs.
5034
        s.wg.Add(1)
3✔
5035
        go func() {
6✔
5036
                defer s.wg.Done()
3✔
5037

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

3✔
5040
                // If this peer had an active persistent connection request,
3✔
5041
                // remove it.
3✔
5042
                if p.ConnReq() != nil {
6✔
5043
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
5044
                }
3✔
5045

5046
                // Remove the peer's access permission from the access manager.
5047
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
5048
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
5049

3✔
5050
                // Copy the peer's error buffer across to the server if it has
3✔
5051
                // any items in it so that we can restore peer errors across
3✔
5052
                // connections. We need to look up the error after the peer has
3✔
5053
                // been disconnected because we write the error in the
3✔
5054
                // `Disconnect` method.
3✔
5055
                s.mu.Lock()
3✔
5056
                if p.ErrorBuffer().Total() > 0 {
6✔
5057
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
5058
                }
3✔
5059
                s.mu.Unlock()
3✔
5060

3✔
5061
                // Inform the peer notifier of a peer offline event so that it
3✔
5062
                // can be reported to clients listening for peer events.
3✔
5063
                var pubKey [33]byte
3✔
5064
                copy(pubKey[:], pubSer)
3✔
5065

3✔
5066
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
5067
        }()
5068
}
5069

5070
// ConnectToPeer requests that the server connect to a Lightning Network peer
5071
// at the specified address. This function will *block* until either a
5072
// connection is established, or the initial handshake process fails.
5073
//
5074
// NOTE: This function is safe for concurrent access.
5075
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
5076
        perm bool, timeout time.Duration) error {
3✔
5077

3✔
5078
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
5079

3✔
5080
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
5081
        // better granularity.  In certain conditions, this method requires
3✔
5082
        // making an outbound connection to a remote peer, which requires the
3✔
5083
        // lock to be released, and subsequently reacquired.
3✔
5084
        s.mu.Lock()
3✔
5085

3✔
5086
        // Ensure we're not already connected to this peer.
3✔
5087
        peer, err := s.findPeerByPubStr(targetPub)
3✔
5088

3✔
5089
        // When there's no error it means we already have a connection with this
3✔
5090
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
5091
        // set, we will ignore the existing connection and continue.
3✔
5092
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
5093
                s.mu.Unlock()
3✔
5094
                return &errPeerAlreadyConnected{peer: peer}
3✔
5095
        }
3✔
5096

5097
        // Peer was not found, continue to pursue connection with peer.
5098

5099
        // If there's already a pending connection request for this pubkey,
5100
        // then we ignore this request to ensure we don't create a redundant
5101
        // connection.
5102
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
5103
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
5104
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
5105
        }
3✔
5106

5107
        // If there's not already a pending or active connection to this node,
5108
        // then instruct the connection manager to attempt to establish a
5109
        // persistent connection to the peer.
5110
        srvrLog.Debugf("Connecting to %v", addr)
3✔
5111
        if perm {
6✔
5112
                connReq := &connmgr.ConnReq{
3✔
5113
                        Addr:      addr,
3✔
5114
                        Permanent: true,
3✔
5115
                }
3✔
5116

3✔
5117
                // Since the user requested a permanent connection, we'll set
3✔
5118
                // the entry to true which will tell the server to continue
3✔
5119
                // reconnecting even if the number of channels with this peer is
3✔
5120
                // zero.
3✔
5121
                s.persistentPeers[targetPub] = true
3✔
5122
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
5123
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
5124
                }
3✔
5125
                s.persistentConnReqs[targetPub] = append(
3✔
5126
                        s.persistentConnReqs[targetPub], connReq,
3✔
5127
                )
3✔
5128
                s.mu.Unlock()
3✔
5129

3✔
5130
                go s.connMgr.Connect(connReq)
3✔
5131

3✔
5132
                return nil
3✔
5133
        }
5134
        s.mu.Unlock()
3✔
5135

3✔
5136
        // If we're not making a persistent connection, then we'll attempt to
3✔
5137
        // connect to the target peer. If the we can't make the connection, or
3✔
5138
        // the crypto negotiation breaks down, then return an error to the
3✔
5139
        // caller.
3✔
5140
        errChan := make(chan error, 1)
3✔
5141
        s.connectToPeer(addr, errChan, timeout)
3✔
5142

3✔
5143
        select {
3✔
5144
        case err := <-errChan:
3✔
5145
                return err
3✔
5146
        case <-s.quit:
×
5147
                return ErrServerShuttingDown
×
5148
        }
5149
}
5150

5151
// connectToPeer establishes a connection to a remote peer. errChan is used to
5152
// notify the caller if the connection attempt has failed. Otherwise, it will be
5153
// closed.
5154
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5155
        errChan chan<- error, timeout time.Duration) {
3✔
5156

3✔
5157
        conn, err := brontide.Dial(
3✔
5158
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5159
        )
3✔
5160
        if err != nil {
6✔
5161
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5162
                select {
3✔
5163
                case errChan <- err:
3✔
5164
                case <-s.quit:
×
5165
                }
5166
                return
3✔
5167
        }
5168

5169
        close(errChan)
3✔
5170

3✔
5171
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5172
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5173

3✔
5174
        s.OutboundPeerConnected(nil, conn)
3✔
5175
}
5176

5177
// DisconnectPeer sends the request to server to close the connection with peer
5178
// identified by public key.
5179
//
5180
// NOTE: This function is safe for concurrent access.
5181
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5182
        pubBytes := pubKey.SerializeCompressed()
3✔
5183
        pubStr := string(pubBytes)
3✔
5184

3✔
5185
        s.mu.Lock()
3✔
5186
        defer s.mu.Unlock()
3✔
5187

3✔
5188
        // Check that were actually connected to this peer. If not, then we'll
3✔
5189
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5190
        // currently connected to.
3✔
5191
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5192
        if err == ErrPeerNotConnected {
6✔
5193
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5194
        }
3✔
5195

5196
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5197

3✔
5198
        s.cancelConnReqs(pubStr, nil)
3✔
5199

3✔
5200
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5201
        // them from this map so we don't attempt to re-connect after we
3✔
5202
        // disconnect.
3✔
5203
        delete(s.persistentPeers, pubStr)
3✔
5204
        delete(s.persistentPeersBackoff, pubStr)
3✔
5205

3✔
5206
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5207
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5208
        //
3✔
5209
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5210
        // goroutine because we might hold the server's mutex.
3✔
5211
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5212

3✔
5213
        return nil
3✔
5214
}
5215

5216
// OpenChannel sends a request to the server to open a channel to the specified
5217
// peer identified by nodeKey with the passed channel funding parameters.
5218
//
5219
// NOTE: This function is safe for concurrent access.
5220
func (s *server) OpenChannel(
5221
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5222

3✔
5223
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5224
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5225
        // not blocked if the caller is not reading the updates.
3✔
5226
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5227
        req.Err = make(chan error, 1)
3✔
5228

3✔
5229
        // First attempt to locate the target peer to open a channel with, if
3✔
5230
        // we're unable to locate the peer then this request will fail.
3✔
5231
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5232
        s.mu.RLock()
3✔
5233
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5234
        if !ok {
3✔
5235
                s.mu.RUnlock()
×
5236

×
5237
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5238
                return req.Updates, req.Err
×
5239
        }
×
5240
        req.Peer = peer
3✔
5241
        s.mu.RUnlock()
3✔
5242

3✔
5243
        // We'll wait until the peer is active before beginning the channel
3✔
5244
        // opening process.
3✔
5245
        select {
3✔
5246
        case <-peer.ActiveSignal():
3✔
5247
        case <-peer.QuitSignal():
×
5248
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5249
                return req.Updates, req.Err
×
5250
        case <-s.quit:
×
5251
                req.Err <- ErrServerShuttingDown
×
5252
                return req.Updates, req.Err
×
5253
        }
5254

5255
        // If the fee rate wasn't specified at this point we fail the funding
5256
        // because of the missing fee rate information. The caller of the
5257
        // `OpenChannel` method needs to make sure that default values for the
5258
        // fee rate are set beforehand.
5259
        if req.FundingFeePerKw == 0 {
3✔
5260
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5261
                        "the channel opening transaction")
×
5262

×
5263
                return req.Updates, req.Err
×
5264
        }
×
5265

5266
        // Spawn a goroutine to send the funding workflow request to the funding
5267
        // manager. This allows the server to continue handling queries instead
5268
        // of blocking on this request which is exported as a synchronous
5269
        // request to the outside world.
5270
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5271

3✔
5272
        return req.Updates, req.Err
3✔
5273
}
5274

5275
// Peers returns a slice of all active peers.
5276
//
5277
// NOTE: This function is safe for concurrent access.
5278
func (s *server) Peers() []*peer.Brontide {
3✔
5279
        s.mu.RLock()
3✔
5280
        defer s.mu.RUnlock()
3✔
5281

3✔
5282
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5283
        for _, peer := range s.peersByPub {
6✔
5284
                peers = append(peers, peer)
3✔
5285
        }
3✔
5286

5287
        return peers
3✔
5288
}
5289

5290
// computeNextBackoff uses a truncated exponential backoff to compute the next
5291
// backoff using the value of the exiting backoff. The returned duration is
5292
// randomized in either direction by 1/20 to prevent tight loops from
5293
// stabilizing.
5294
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5295
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5296
        nextBackoff := 2 * currBackoff
3✔
5297
        if nextBackoff > maxBackoff {
6✔
5298
                nextBackoff = maxBackoff
3✔
5299
        }
3✔
5300

5301
        // Using 1/10 of our duration as a margin, compute a random offset to
5302
        // avoid the nodes entering connection cycles.
5303
        margin := nextBackoff / 10
3✔
5304

3✔
5305
        var wiggle big.Int
3✔
5306
        wiggle.SetUint64(uint64(margin))
3✔
5307
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5308
                // Randomizing is not mission critical, so we'll just return the
×
5309
                // current backoff.
×
5310
                return nextBackoff
×
5311
        }
×
5312

5313
        // Otherwise add in our wiggle, but subtract out half of the margin so
5314
        // that the backoff can tweaked by 1/20 in either direction.
5315
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5316
}
5317

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

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

3✔
5326
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5327
        if err != nil {
3✔
5328
                return nil, err
×
5329
        }
×
5330

5331
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
3✔
5332
        if err != nil {
6✔
5333
                return nil, err
3✔
5334
        }
3✔
5335

5336
        if len(node.Addresses) == 0 {
6✔
5337
                return nil, errNoAdvertisedAddr
3✔
5338
        }
3✔
5339

5340
        return node.Addresses, nil
3✔
5341
}
5342

5343
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5344
// channel update for a target channel.
5345
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5346
        *lnwire.ChannelUpdate1, error) {
3✔
5347

3✔
5348
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5349
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5350
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5351
                if err != nil {
6✔
5352
                        return nil, err
3✔
5353
                }
3✔
5354

5355
                return netann.ExtractChannelUpdate(
3✔
5356
                        ourPubKey[:], info, edge1, edge2,
3✔
5357
                )
3✔
5358
        }
5359
}
5360

5361
// applyChannelUpdate applies the channel update to the different sub-systems of
5362
// the server. The useAlias boolean denotes whether or not to send an alias in
5363
// place of the real SCID.
5364
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5365
        op *wire.OutPoint, useAlias bool) error {
3✔
5366

3✔
5367
        var (
3✔
5368
                peerAlias    *lnwire.ShortChannelID
3✔
5369
                defaultAlias lnwire.ShortChannelID
3✔
5370
        )
3✔
5371

3✔
5372
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5373

3✔
5374
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5375
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5376
        if useAlias {
6✔
5377
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5378
                if foundAlias != defaultAlias {
6✔
5379
                        peerAlias = &foundAlias
3✔
5380
                }
3✔
5381
        }
5382

5383
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5384
                update, discovery.RemoteAlias(peerAlias),
3✔
5385
        )
3✔
5386
        select {
3✔
5387
        case err := <-errChan:
3✔
5388
                return err
3✔
5389
        case <-s.quit:
×
5390
                return ErrServerShuttingDown
×
5391
        }
5392
}
5393

5394
// SendCustomMessage sends a custom message to the peer with the specified
5395
// pubkey.
5396
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5397
        data []byte) error {
3✔
5398

3✔
5399
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5400
        if err != nil {
3✔
5401
                return err
×
5402
        }
×
5403

5404
        // We'll wait until the peer is active.
5405
        select {
3✔
5406
        case <-peer.ActiveSignal():
3✔
5407
        case <-peer.QuitSignal():
×
5408
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5409
        case <-s.quit:
×
5410
                return ErrServerShuttingDown
×
5411
        }
5412

5413
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5414
        if err != nil {
6✔
5415
                return err
3✔
5416
        }
3✔
5417

5418
        // Send the message as low-priority. For now we assume that all
5419
        // application-defined message are low priority.
5420
        return peer.SendMessageLazy(true, msg)
3✔
5421
}
5422

5423
// SendOnionMessage sends a custom message to the peer with the specified
5424
// pubkey.
5425
// TODO(gijs): change this message to include path finding.
5426
func (s *server) SendOnionMessage(peerPub [33]byte,
5427
        blindingPoint *btcec.PublicKey, onion []byte) error {
3✔
5428

3✔
5429
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5430
        if err != nil {
3✔
NEW
5431
                return err
×
NEW
5432
        }
×
5433

5434
        // We'll wait until the peer is active.
5435
        select {
3✔
5436
        case <-peer.ActiveSignal():
3✔
NEW
5437
        case <-peer.QuitSignal():
×
NEW
5438
                return fmt.Errorf("peer %x disconnected", peerPub)
×
NEW
5439
        case <-s.quit:
×
NEW
5440
                return ErrServerShuttingDown
×
5441
        }
5442

5443
        msg := lnwire.NewOnionMessage(blindingPoint, onion)
3✔
5444

3✔
5445
        // Send the message as low-priority. For now we assume that all
3✔
5446
        // application-defined message are low priority.
3✔
5447
        return peer.SendMessageLazy(true, msg)
3✔
5448
}
5449

5450
// newSweepPkScriptGen creates closure that generates a new public key script
5451
// which should be used to sweep any funds into the on-chain wallet.
5452
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5453
// (p2wkh) output.
5454
func newSweepPkScriptGen(
5455
        wallet lnwallet.WalletController,
5456
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5457

3✔
5458
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5459
                sweepAddr, err := wallet.NewAddress(
3✔
5460
                        lnwallet.TaprootPubkey, false,
3✔
5461
                        lnwallet.DefaultAccountName,
3✔
5462
                )
3✔
5463
                if err != nil {
3✔
5464
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5465
                }
×
5466

5467
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5468
                if err != nil {
3✔
5469
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5470
                }
×
5471

5472
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5473
                        wallet, netParams, addr,
3✔
5474
                )
3✔
5475
                if err != nil {
3✔
5476
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5477
                }
×
5478

5479
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5480
                        DeliveryAddress: addr,
3✔
5481
                        InternalKey:     internalKeyDesc,
3✔
5482
                })
3✔
5483
        }
5484
}
5485

5486
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5487
// finished.
5488
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5489
        // Get a list of closed channels.
3✔
5490
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5491
        if err != nil {
3✔
5492
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5493
                return nil
×
5494
        }
×
5495

5496
        // Save the SCIDs in a map.
5497
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5498
        for _, c := range channels {
6✔
5499
                // If the channel is not pending, its FC has been finalized.
3✔
5500
                if !c.IsPending {
6✔
5501
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5502
                }
3✔
5503
        }
5504

5505
        // Double check whether the reported closed channel has indeed finished
5506
        // closing.
5507
        //
5508
        // NOTE: There are misalignments regarding when a channel's FC is
5509
        // marked as finalized. We double check the pending channels to make
5510
        // sure the returned SCIDs are indeed terminated.
5511
        //
5512
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5513
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5514
        if err != nil {
3✔
5515
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5516
                return nil
×
5517
        }
×
5518

5519
        for _, c := range pendings {
6✔
5520
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5521
                        continue
3✔
5522
                }
5523

5524
                // If the channel is still reported as pending, remove it from
5525
                // the map.
5526
                delete(closedSCIDs, c.ShortChannelID)
×
5527

×
5528
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5529
                        c.ShortChannelID)
×
5530
        }
5531

5532
        return closedSCIDs
3✔
5533
}
5534

5535
// getStartingBeat returns the current beat. This is used during the startup to
5536
// initialize blockbeat consumers.
5537
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5538
        // beat is the current blockbeat.
3✔
5539
        var beat *chainio.Beat
3✔
5540

3✔
5541
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5542
        // we will skip fetching the best block.
3✔
5543
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5544
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5545
                        "mode")
×
5546

×
5547
                return &chainio.Beat{}, nil
×
5548
        }
×
5549

5550
        // We should get a notification with the current best block immediately
5551
        // by passing a nil block.
5552
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5553
        if err != nil {
3✔
5554
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5555
        }
×
5556
        defer blockEpochs.Cancel()
3✔
5557

3✔
5558
        // We registered for the block epochs with a nil request. The notifier
3✔
5559
        // should send us the current best block immediately. So we need to
3✔
5560
        // wait for it here because we need to know the current best height.
3✔
5561
        select {
3✔
5562
        case bestBlock := <-blockEpochs.Epochs:
3✔
5563
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5564
                        bestBlock.Hash, bestBlock.Height)
3✔
5565

3✔
5566
                // Update the current blockbeat.
3✔
5567
                beat = chainio.NewBeat(*bestBlock)
3✔
5568

5569
        case <-s.quit:
×
5570
                srvrLog.Debug("LND shutting down")
×
5571
        }
5572

5573
        return beat, nil
3✔
5574
}
5575

5576
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5577
// point has an active RBF chan closer.
5578
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5579
        chanPoint wire.OutPoint) bool {
3✔
5580

3✔
5581
        pubBytes := peerPub.SerializeCompressed()
3✔
5582

3✔
5583
        s.mu.RLock()
3✔
5584
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5585
        s.mu.RUnlock()
3✔
5586
        if !ok {
3✔
5587
                return false
×
5588
        }
×
5589

5590
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5591
}
5592

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

3✔
5601
        // First, we'll attempt to look up the channel based on it's
3✔
5602
        // ChannelPoint.
3✔
5603
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5604
        if err != nil {
3✔
5605
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5606
        }
×
5607

5608
        // From the channel, we can now get the pubkey of the peer, then use
5609
        // that to eventually get the chan closer.
5610
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5611

3✔
5612
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5613
        s.mu.RLock()
3✔
5614
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5615
        s.mu.RUnlock()
3✔
5616
        if !ok {
3✔
5617
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5618
                        "not online", chanPoint)
×
5619
        }
×
5620

5621
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5622
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5623
        )
3✔
5624
        if err != nil {
3✔
5625
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5626
                        "%w", err)
×
5627
        }
×
5628

5629
        return closeUpdates, nil
3✔
5630
}
5631

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

3✔
5640
        // If the channel is present in the switch, then the request should flow
3✔
5641
        // through the switch instead.
3✔
5642
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5643
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5644
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5645
                        "invalid request", chanPoint)
×
5646
        }
×
5647

5648
        // At this point, we know that the channel isn't present in the link, so
5649
        // we'll check to see if we have an entry in the active chan closer map.
5650
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5651
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5652
        )
3✔
5653
        if err != nil {
3✔
5654
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5655
                        "ChannelPoint(%v)", chanPoint)
×
5656
        }
×
5657

5658
        return updates, nil
3✔
5659
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc