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

lightningnetwork / lnd / 13558005087

27 Feb 2025 03:04AM UTC coverage: 58.834% (-0.001%) from 58.835%
13558005087

Pull #8453

github

Roasbeef
lnwallet/chancloser: increase test coverage of state machine
Pull Request #8453: [4/4] - multi: integrate new rbf coop close FSM into the existing peer flow

1079 of 1370 new or added lines in 23 files covered. (78.76%)

578 existing lines in 40 files now uncovered.

137063 of 232965 relevant lines covered (58.83%)

19205.84 hits per line

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

63.96
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

145
// errPeerAlreadyConnected is an error returned by the server when we're
146
// commanded to connect to a peer, but they're already connected.
147
type errPeerAlreadyConnected struct {
148
        peer *peer.Brontide
149
}
150

151
// Error returns the human readable version of this error type.
152
//
153
// NOTE: Part of the error interface.
154
func (e *errPeerAlreadyConnected) Error() string {
1✔
155
        return fmt.Sprintf("already connected to peer: %v", e.peer)
1✔
156
}
1✔
157

158
// server is the main server of the Lightning Network Daemon. The server houses
159
// global state pertaining to the wallet, database, and the rpcserver.
160
// Additionally, the server is also used as a central messaging bus to interact
161
// with any of its companion objects.
162
type server struct {
163
        active   int32 // atomic
164
        stopping int32 // atomic
165

166
        start sync.Once
167
        stop  sync.Once
168

169
        cfg *Config
170

171
        implCfg *ImplementationCfg
172

173
        // identityECDH is an ECDH capable wrapper for the private key used
174
        // to authenticate any incoming connections.
175
        identityECDH keychain.SingleKeyECDH
176

177
        // identityKeyLoc is the key locator for the above wrapped identity key.
178
        identityKeyLoc keychain.KeyLocator
179

180
        // nodeSigner is an implementation of the MessageSigner implementation
181
        // that's backed by the identity private key of the running lnd node.
182
        nodeSigner *netann.NodeSigner
183

184
        chanStatusMgr *netann.ChanStatusManager
185

186
        // listenAddrs is the list of addresses the server is currently
187
        // listening on.
188
        listenAddrs []net.Addr
189

190
        // torController is a client that will communicate with a locally
191
        // running Tor server. This client will handle initiating and
192
        // authenticating the connection to the Tor server, automatically
193
        // creating and setting up onion services, etc.
194
        torController *tor.Controller
195

196
        // natTraversal is the specific NAT traversal technique used to
197
        // automatically set up port forwarding rules in order to advertise to
198
        // the network that the node is accepting inbound connections.
199
        natTraversal nat.Traversal
200

201
        // lastDetectedIP is the last IP detected by the NAT traversal technique
202
        // above. This IP will be watched periodically in a goroutine in order
203
        // to handle dynamic IP changes.
204
        lastDetectedIP net.IP
205

206
        mu sync.RWMutex
207

208
        // peersByPub is a map of the active peers.
209
        //
210
        // NOTE: The key used here is the raw bytes of the peer's public key to
211
        // string conversion, which means it cannot be printed using `%s` as it
212
        // will just print the binary.
213
        //
214
        // TODO(yy): Use the hex string instead.
215
        peersByPub map[string]*peer.Brontide
216

217
        inboundPeers  map[string]*peer.Brontide
218
        outboundPeers map[string]*peer.Brontide
219

220
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
221
        peerDisconnectedListeners map[string][]chan<- struct{}
222

223
        // TODO(yy): the Brontide.Start doesn't know this value, which means it
224
        // will continue to send messages even if there are no active channels
225
        // and the value below is false. Once it's pruned, all its connections
226
        // will be closed, thus the Brontide.Start will return an error.
227
        persistentPeers        map[string]bool
228
        persistentPeersBackoff map[string]time.Duration
229
        persistentPeerAddrs    map[string][]*lnwire.NetAddress
230
        persistentConnReqs     map[string][]*connmgr.ConnReq
231
        persistentRetryCancels map[string]chan struct{}
232

233
        // peerErrors keeps a set of peer error buffers for peers that have
234
        // disconnected from us. This allows us to track historic peer errors
235
        // over connections. The string of the peer's compressed pubkey is used
236
        // as a key for this map.
237
        peerErrors map[string]*queue.CircularBuffer
238

239
        // ignorePeerTermination tracks peers for which the server has initiated
240
        // a disconnect. Adding a peer to this map causes the peer termination
241
        // watcher to short circuit in the event that peers are purposefully
242
        // disconnected.
243
        ignorePeerTermination map[*peer.Brontide]struct{}
244

245
        // scheduledPeerConnection maps a pubkey string to a callback that
246
        // should be executed in the peerTerminationWatcher the prior peer with
247
        // the same pubkey exits.  This allows the server to wait until the
248
        // prior peer has cleaned up successfully, before adding the new peer
249
        // intended to replace it.
250
        scheduledPeerConnection map[string]func()
251

252
        // pongBuf is a shared pong reply buffer we'll use across all active
253
        // peer goroutines. We know the max size of a pong message
254
        // (lnwire.MaxPongBytes), so we can allocate this ahead of time, and
255
        // avoid allocations each time we need to send a pong message.
256
        pongBuf []byte
257

258
        cc *chainreg.ChainControl
259

260
        fundingMgr *funding.Manager
261

262
        graphDB *graphdb.ChannelGraph
263

264
        chanStateDB *channeldb.ChannelStateDB
265

266
        addrSource channeldb.AddrSource
267

268
        // miscDB is the DB that contains all "other" databases within the main
269
        // channel DB that haven't been separated out yet.
270
        miscDB *channeldb.DB
271

272
        invoicesDB invoices.InvoiceDB
273

274
        aliasMgr *aliasmgr.Manager
275

276
        htlcSwitch *htlcswitch.Switch
277

278
        interceptableSwitch *htlcswitch.InterceptableSwitch
279

280
        invoices *invoices.InvoiceRegistry
281

282
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
283

284
        channelNotifier *channelnotifier.ChannelNotifier
285

286
        peerNotifier *peernotifier.PeerNotifier
287

288
        htlcNotifier *htlcswitch.HtlcNotifier
289

290
        witnessBeacon contractcourt.WitnessBeacon
291

292
        breachArbitrator *contractcourt.BreachArbitrator
293

294
        missionController *routing.MissionController
295
        defaultMC         *routing.MissionControl
296

297
        graphBuilder *graph.Builder
298

299
        chanRouter *routing.ChannelRouter
300

301
        controlTower routing.ControlTower
302

303
        authGossiper *discovery.AuthenticatedGossiper
304

305
        localChanMgr *localchans.Manager
306

307
        utxoNursery *contractcourt.UtxoNursery
308

309
        sweeper *sweep.UtxoSweeper
310

311
        chainArb *contractcourt.ChainArbitrator
312

313
        sphinx *hop.OnionProcessor
314

315
        towerClientMgr *wtclient.Manager
316

317
        connMgr *connmgr.ConnManager
318

319
        sigPool *lnwallet.SigPool
320

321
        writePool *pool.Write
322

323
        readPool *pool.Read
324

325
        tlsManager *TLSManager
326

327
        // featureMgr dispatches feature vectors for various contexts within the
328
        // daemon.
329
        featureMgr *feature.Manager
330

331
        // currentNodeAnn is the node announcement that has been broadcast to
332
        // the network upon startup, if the attributes of the node (us) has
333
        // changed since last start.
334
        currentNodeAnn *lnwire.NodeAnnouncement
335

336
        // chansToRestore is the set of channels that upon starting, the server
337
        // should attempt to restore/recover.
338
        chansToRestore walletunlocker.ChannelsToRecover
339

340
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
341
        // backups are consistent at all times. It interacts with the
342
        // channelNotifier to be notified of newly opened and closed channels.
343
        chanSubSwapper *chanbackup.SubSwapper
344

345
        // chanEventStore tracks the behaviour of channels and their remote peers to
346
        // provide insights into their health and performance.
347
        chanEventStore *chanfitness.ChannelEventStore
348

349
        hostAnn *netann.HostAnnouncer
350

351
        // livenessMonitor monitors that lnd has access to critical resources.
352
        livenessMonitor *healthcheck.Monitor
353

354
        customMessageServer *subscribe.Server
355

356
        // txPublisher is a publisher with fee-bumping capability.
357
        txPublisher *sweep.TxPublisher
358

359
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
360
        // of new blocks.
361
        blockbeatDispatcher *chainio.BlockbeatDispatcher
362

363
        quit chan struct{}
364

365
        wg sync.WaitGroup
366
}
367

368
// updatePersistentPeerAddrs subscribes to topology changes and stores
369
// advertised addresses for any NodeAnnouncements from our persisted peers.
370
func (s *server) updatePersistentPeerAddrs() error {
1✔
371
        graphSub, err := s.graphBuilder.SubscribeTopology()
1✔
372
        if err != nil {
1✔
373
                return err
×
374
        }
×
375

376
        s.wg.Add(1)
1✔
377
        go func() {
2✔
378
                defer func() {
2✔
379
                        graphSub.Cancel()
1✔
380
                        s.wg.Done()
1✔
381
                }()
1✔
382

383
                for {
2✔
384
                        select {
1✔
385
                        case <-s.quit:
1✔
386
                                return
1✔
387

388
                        case topChange, ok := <-graphSub.TopologyChanges:
1✔
389
                                // If the router is shutting down, then we will
1✔
390
                                // as well.
1✔
391
                                if !ok {
1✔
392
                                        return
×
393
                                }
×
394

395
                                for _, update := range topChange.NodeUpdates {
2✔
396
                                        pubKeyStr := string(
1✔
397
                                                update.IdentityKey.
1✔
398
                                                        SerializeCompressed(),
1✔
399
                                        )
1✔
400

1✔
401
                                        // We only care about updates from
1✔
402
                                        // our persistentPeers.
1✔
403
                                        s.mu.RLock()
1✔
404
                                        _, ok := s.persistentPeers[pubKeyStr]
1✔
405
                                        s.mu.RUnlock()
1✔
406
                                        if !ok {
2✔
407
                                                continue
1✔
408
                                        }
409

410
                                        addrs := make([]*lnwire.NetAddress, 0,
1✔
411
                                                len(update.Addresses))
1✔
412

1✔
413
                                        for _, addr := range update.Addresses {
2✔
414
                                                addrs = append(addrs,
1✔
415
                                                        &lnwire.NetAddress{
1✔
416
                                                                IdentityKey: update.IdentityKey,
1✔
417
                                                                Address:     addr,
1✔
418
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
1✔
419
                                                        },
1✔
420
                                                )
1✔
421
                                        }
1✔
422

423
                                        s.mu.Lock()
1✔
424

1✔
425
                                        // Update the stored addresses for this
1✔
426
                                        // to peer to reflect the new set.
1✔
427
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
1✔
428

1✔
429
                                        // If there are no outstanding
1✔
430
                                        // connection requests for this peer
1✔
431
                                        // then our work is done since we are
1✔
432
                                        // not currently trying to connect to
1✔
433
                                        // them.
1✔
434
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
2✔
435
                                                s.mu.Unlock()
1✔
436
                                                continue
1✔
437
                                        }
438

439
                                        s.mu.Unlock()
1✔
440

1✔
441
                                        s.connectToPersistentPeer(pubKeyStr)
1✔
442
                                }
443
                        }
444
                }
445
        }()
446

447
        return nil
1✔
448
}
449

450
// CustomMessage is a custom message that is received from a peer.
451
type CustomMessage struct {
452
        // Peer is the peer pubkey
453
        Peer [33]byte
454

455
        // Msg is the custom wire message.
456
        Msg *lnwire.Custom
457
}
458

459
// parseAddr parses an address from its string format to a net.Addr.
460
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
1✔
461
        var (
1✔
462
                host string
1✔
463
                port int
1✔
464
        )
1✔
465

1✔
466
        // Split the address into its host and port components.
1✔
467
        h, p, err := net.SplitHostPort(address)
1✔
468
        if err != nil {
1✔
469
                // If a port wasn't specified, we'll assume the address only
×
470
                // contains the host so we'll use the default port.
×
471
                host = address
×
472
                port = defaultPeerPort
×
473
        } else {
1✔
474
                // Otherwise, we'll note both the host and ports.
1✔
475
                host = h
1✔
476
                portNum, err := strconv.Atoi(p)
1✔
477
                if err != nil {
1✔
478
                        return nil, err
×
479
                }
×
480
                port = portNum
1✔
481
        }
482

483
        if tor.IsOnionHost(host) {
1✔
484
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
485
        }
×
486

487
        // If the host is part of a TCP address, we'll use the network
488
        // specific ResolveTCPAddr function in order to resolve these
489
        // addresses over Tor in order to prevent leaking your real IP
490
        // address.
491
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
1✔
492
        return netCfg.ResolveTCPAddr("tcp", hostPort)
1✔
493
}
494

495
// noiseDial is a factory function which creates a connmgr compliant dialing
496
// function by returning a closure which includes the server's identity key.
497
func noiseDial(idKey keychain.SingleKeyECDH,
498
        netCfg tor.Net, timeout time.Duration) func(net.Addr) (net.Conn, error) {
1✔
499

1✔
500
        return func(a net.Addr) (net.Conn, error) {
2✔
501
                lnAddr := a.(*lnwire.NetAddress)
1✔
502
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
1✔
503
        }
1✔
504
}
505

506
// newServer creates a new instance of the server which is to listen using the
507
// passed listener address.
508
func newServer(cfg *Config, listenAddrs []net.Addr,
509
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
510
        nodeKeyDesc *keychain.KeyDescriptor,
511
        chansToRestore walletunlocker.ChannelsToRecover,
512
        chanPredicate chanacceptor.ChannelAcceptor,
513
        torController *tor.Controller, tlsManager *TLSManager,
514
        leaderElector cluster.LeaderElector,
515
        implCfg *ImplementationCfg) (*server, error) {
1✔
516

1✔
517
        var (
1✔
518
                err         error
1✔
519
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
1✔
520

1✔
521
                // We just derived the full descriptor, so we know the public
1✔
522
                // key is set on it.
1✔
523
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
1✔
524
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
1✔
525
                )
1✔
526
        )
1✔
527

1✔
528
        listeners := make([]net.Listener, len(listenAddrs))
1✔
529
        for i, listenAddr := range listenAddrs {
2✔
530
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
1✔
531
                // doesn't need to call the general lndResolveTCP function
1✔
532
                // since we are resolving a local address.
1✔
533
                listeners[i], err = brontide.NewListener(
1✔
534
                        nodeKeyECDH, listenAddr.String(),
1✔
535
                )
1✔
536
                if err != nil {
1✔
537
                        return nil, err
×
538
                }
×
539
        }
540

541
        var serializedPubKey [33]byte
1✔
542
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
1✔
543

1✔
544
        netParams := cfg.ActiveNetParams.Params
1✔
545

1✔
546
        // Initialize the sphinx router.
1✔
547
        replayLog := htlcswitch.NewDecayedLog(
1✔
548
                dbs.DecayedLogDB, cc.ChainNotifier,
1✔
549
        )
1✔
550
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
1✔
551

1✔
552
        writeBufferPool := pool.NewWriteBuffer(
1✔
553
                pool.DefaultWriteBufferGCInterval,
1✔
554
                pool.DefaultWriteBufferExpiryInterval,
1✔
555
        )
1✔
556

1✔
557
        writePool := pool.NewWrite(
1✔
558
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
1✔
559
        )
1✔
560

1✔
561
        readBufferPool := pool.NewReadBuffer(
1✔
562
                pool.DefaultReadBufferGCInterval,
1✔
563
                pool.DefaultReadBufferExpiryInterval,
1✔
564
        )
1✔
565

1✔
566
        readPool := pool.NewRead(
1✔
567
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
1✔
568
        )
1✔
569

1✔
570
        // If the taproot overlay flag is set, but we don't have an aux funding
1✔
571
        // controller, then we'll exit as this is incompatible.
1✔
572
        if cfg.ProtocolOptions.TaprootOverlayChans &&
1✔
573
                implCfg.AuxFundingController.IsNone() {
1✔
574

×
575
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
576
                        "aux controllers")
×
577
        }
×
578

579
        // For now, the RBF coop close flag and the taproot channel type cannot
580
        // be used together.
581
        //
582
        // TODO(roasbeef): fix
583
        if cfg.ProtocolOptions.RbfCoopClose &&
1✔
584
                cfg.ProtocolOptions.TaprootChans {
1✔
NEW
585

×
NEW
586
                return nil, fmt.Errorf("RBF coop close and taproot " +
×
NEW
587
                        "channels cannot be used together")
×
NEW
588
        }
×
589

590
        //nolint:ll
591
        featureMgr, err := feature.NewManager(feature.Config{
1✔
592
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
1✔
593
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
1✔
594
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
1✔
595
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
1✔
596
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
1✔
597
                NoKeysend:                 !cfg.AcceptKeySend,
1✔
598
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
1✔
599
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
1✔
600
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
1✔
601
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
1✔
602
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
1✔
603
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
1✔
604
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
1✔
605
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
1✔
606
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
1✔
607
                NoRbfCoopClose:            !cfg.ProtocolOptions.RbfCoopClose,
1✔
608
        })
1✔
609
        if err != nil {
1✔
610
                return nil, err
×
611
        }
×
612

613
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
1✔
614
        registryConfig := invoices.RegistryConfig{
1✔
615
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
1✔
616
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
1✔
617
                Clock:                       clock.NewDefaultClock(),
1✔
618
                AcceptKeySend:               cfg.AcceptKeySend,
1✔
619
                AcceptAMP:                   cfg.AcceptAMP,
1✔
620
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
1✔
621
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
1✔
622
                KeysendHoldTime:             cfg.KeysendHoldTime,
1✔
623
                HtlcInterceptor:             invoiceHtlcModifier,
1✔
624
        }
1✔
625

1✔
626
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
1✔
627

1✔
628
        s := &server{
1✔
629
                cfg:            cfg,
1✔
630
                implCfg:        implCfg,
1✔
631
                graphDB:        dbs.GraphDB,
1✔
632
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
1✔
633
                addrSource:     addrSource,
1✔
634
                miscDB:         dbs.ChanStateDB,
1✔
635
                invoicesDB:     dbs.InvoiceDB,
1✔
636
                cc:             cc,
1✔
637
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
1✔
638
                writePool:      writePool,
1✔
639
                readPool:       readPool,
1✔
640
                chansToRestore: chansToRestore,
1✔
641

1✔
642
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
1✔
643
                        cc.ChainNotifier,
1✔
644
                ),
1✔
645
                channelNotifier: channelnotifier.New(
1✔
646
                        dbs.ChanStateDB.ChannelStateDB(),
1✔
647
                ),
1✔
648

1✔
649
                identityECDH:   nodeKeyECDH,
1✔
650
                identityKeyLoc: nodeKeyDesc.KeyLocator,
1✔
651
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
1✔
652

1✔
653
                listenAddrs: listenAddrs,
1✔
654

1✔
655
                // TODO(roasbeef): derive proper onion key based on rotation
1✔
656
                // schedule
1✔
657
                sphinx: hop.NewOnionProcessor(sphinxRouter),
1✔
658

1✔
659
                torController: torController,
1✔
660

1✔
661
                persistentPeers:         make(map[string]bool),
1✔
662
                persistentPeersBackoff:  make(map[string]time.Duration),
1✔
663
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
1✔
664
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
1✔
665
                persistentRetryCancels:  make(map[string]chan struct{}),
1✔
666
                peerErrors:              make(map[string]*queue.CircularBuffer),
1✔
667
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
1✔
668
                scheduledPeerConnection: make(map[string]func()),
1✔
669
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
1✔
670

1✔
671
                peersByPub:                make(map[string]*peer.Brontide),
1✔
672
                inboundPeers:              make(map[string]*peer.Brontide),
1✔
673
                outboundPeers:             make(map[string]*peer.Brontide),
1✔
674
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
1✔
675
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
1✔
676

1✔
677
                invoiceHtlcModifier: invoiceHtlcModifier,
1✔
678

1✔
679
                customMessageServer: subscribe.NewServer(),
1✔
680

1✔
681
                tlsManager: tlsManager,
1✔
682

1✔
683
                featureMgr: featureMgr,
1✔
684
                quit:       make(chan struct{}),
1✔
685
        }
1✔
686

1✔
687
        // Start the low-level services once they are initialized.
1✔
688
        //
1✔
689
        // TODO(yy): break the server startup into four steps,
1✔
690
        // 1. init the low-level services.
1✔
691
        // 2. start the low-level services.
1✔
692
        // 3. init the high-level services.
1✔
693
        // 4. start the high-level services.
1✔
694
        if err := s.startLowLevelServices(); err != nil {
1✔
695
                return nil, err
×
696
        }
×
697

698
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
1✔
699
        if err != nil {
1✔
700
                return nil, err
×
701
        }
×
702

703
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
1✔
704
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
1✔
705
                uint32(currentHeight), currentHash, cc.ChainNotifier,
1✔
706
        )
1✔
707
        s.invoices = invoices.NewRegistry(
1✔
708
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
1✔
709
        )
1✔
710

1✔
711
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
1✔
712

1✔
713
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
1✔
714
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
1✔
715

1✔
716
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
2✔
717
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
1✔
718
                if err != nil {
1✔
719
                        return err
×
720
                }
×
721

722
                s.htlcSwitch.UpdateLinkAliases(link)
1✔
723

1✔
724
                return nil
1✔
725
        }
726

727
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
1✔
728
        if err != nil {
1✔
729
                return nil, err
×
730
        }
×
731

732
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
1✔
733
                DB:                   dbs.ChanStateDB,
1✔
734
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1✔
735
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
1✔
736
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
1✔
737
                LocalChannelClose: func(pubKey []byte,
1✔
738
                        request *htlcswitch.ChanClose) {
2✔
739

1✔
740
                        peer, err := s.FindPeerByPubStr(string(pubKey))
1✔
741
                        if err != nil {
1✔
742
                                srvrLog.Errorf("unable to close channel, peer"+
×
743
                                        " with %v id can't be found: %v",
×
744
                                        pubKey, err,
×
745
                                )
×
746
                                return
×
747
                        }
×
748

749
                        peer.HandleLocalCloseChanReqs(request)
1✔
750
                },
751
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
752
                SwitchPackager:         channeldb.NewSwitchPackager(),
753
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
754
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
755
                Notifier:               s.cc.ChainNotifier,
756
                HtlcNotifier:           s.htlcNotifier,
757
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
758
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
759
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
760
                AllowCircularRoute:     cfg.AllowCircularRoute,
761
                RejectHTLC:             cfg.RejectHTLC,
762
                Clock:                  clock.NewDefaultClock(),
763
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
764
                MaxFeeExposure:         thresholdMSats,
765
                SignAliasUpdate:        s.signAliasUpdate,
766
                IsAlias:                aliasmgr.IsAlias,
767
        }, uint32(currentHeight))
768
        if err != nil {
1✔
769
                return nil, err
×
770
        }
×
771
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
1✔
772
                &htlcswitch.InterceptableSwitchConfig{
1✔
773
                        Switch:             s.htlcSwitch,
1✔
774
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
1✔
775
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
1✔
776
                        RequireInterceptor: s.cfg.RequireInterceptor,
1✔
777
                        Notifier:           s.cc.ChainNotifier,
1✔
778
                },
1✔
779
        )
1✔
780
        if err != nil {
1✔
781
                return nil, err
×
782
        }
×
783

784
        s.witnessBeacon = newPreimageBeacon(
1✔
785
                dbs.ChanStateDB.NewWitnessCache(),
1✔
786
                s.interceptableSwitch.ForwardPacket,
1✔
787
        )
1✔
788

1✔
789
        chanStatusMgrCfg := &netann.ChanStatusConfig{
1✔
790
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
1✔
791
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
1✔
792
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
1✔
793
                OurPubKey:                nodeKeyDesc.PubKey,
1✔
794
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
1✔
795
                MessageSigner:            s.nodeSigner,
1✔
796
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
1✔
797
                ApplyChannelUpdate:       s.applyChannelUpdate,
1✔
798
                DB:                       s.chanStateDB,
1✔
799
                Graph:                    dbs.GraphDB,
1✔
800
        }
1✔
801

1✔
802
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
1✔
803
        if err != nil {
1✔
804
                return nil, err
×
805
        }
×
806
        s.chanStatusMgr = chanStatusMgr
1✔
807

1✔
808
        // If enabled, use either UPnP or NAT-PMP to automatically configure
1✔
809
        // port forwarding for users behind a NAT.
1✔
810
        if cfg.NAT {
1✔
811
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
812

×
813
                discoveryTimeout := time.Duration(10 * time.Second)
×
814

×
815
                ctx, cancel := context.WithTimeout(
×
816
                        context.Background(), discoveryTimeout,
×
817
                )
×
818
                defer cancel()
×
819
                upnp, err := nat.DiscoverUPnP(ctx)
×
820
                if err == nil {
×
821
                        s.natTraversal = upnp
×
822
                } else {
×
823
                        // If we were not able to discover a UPnP enabled device
×
824
                        // on the local network, we'll fall back to attempting
×
825
                        // to discover a NAT-PMP enabled device.
×
826
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
827
                                "device on the local network: %v", err)
×
828

×
829
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
830
                                "enabled device")
×
831

×
832
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
833
                        if err != nil {
×
834
                                err := fmt.Errorf("unable to discover a "+
×
835
                                        "NAT-PMP enabled device on the local "+
×
836
                                        "network: %v", err)
×
837
                                srvrLog.Error(err)
×
838
                                return nil, err
×
839
                        }
×
840

841
                        s.natTraversal = pmp
×
842
                }
843
        }
844

845
        // If we were requested to automatically configure port forwarding,
846
        // we'll use the ports that the server will be listening on.
847
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
1✔
848
        for idx, ip := range cfg.ExternalIPs {
2✔
849
                externalIPStrings[idx] = ip.String()
1✔
850
        }
1✔
851
        if s.natTraversal != nil {
1✔
852
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
853
                for _, listenAddr := range listenAddrs {
×
854
                        // At this point, the listen addresses should have
×
855
                        // already been normalized, so it's safe to ignore the
×
856
                        // errors.
×
857
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
858
                        port, _ := strconv.Atoi(portStr)
×
859

×
860
                        listenPorts = append(listenPorts, uint16(port))
×
861
                }
×
862

863
                ips, err := s.configurePortForwarding(listenPorts...)
×
864
                if err != nil {
×
865
                        srvrLog.Errorf("Unable to automatically set up port "+
×
866
                                "forwarding using %s: %v",
×
867
                                s.natTraversal.Name(), err)
×
868
                } else {
×
869
                        srvrLog.Infof("Automatically set up port forwarding "+
×
870
                                "using %s to advertise external IP",
×
871
                                s.natTraversal.Name())
×
872
                        externalIPStrings = append(externalIPStrings, ips...)
×
873
                }
×
874
        }
875

876
        // If external IP addresses have been specified, add those to the list
877
        // of this server's addresses.
878
        externalIPs, err := lncfg.NormalizeAddresses(
1✔
879
                externalIPStrings, strconv.Itoa(defaultPeerPort),
1✔
880
                cfg.net.ResolveTCPAddr,
1✔
881
        )
1✔
882
        if err != nil {
1✔
883
                return nil, err
×
884
        }
×
885

886
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
1✔
887
        selfAddrs = append(selfAddrs, externalIPs...)
1✔
888

1✔
889
        // We'll now reconstruct a node announcement based on our current
1✔
890
        // configuration so we can send it out as a sort of heart beat within
1✔
891
        // the network.
1✔
892
        //
1✔
893
        // We'll start by parsing the node color from configuration.
1✔
894
        color, err := lncfg.ParseHexColor(cfg.Color)
1✔
895
        if err != nil {
1✔
896
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
897
                return nil, err
×
898
        }
×
899

900
        // If no alias is provided, default to first 10 characters of public
901
        // key.
902
        alias := cfg.Alias
1✔
903
        if alias == "" {
2✔
904
                alias = hex.EncodeToString(serializedPubKey[:10])
1✔
905
        }
1✔
906
        nodeAlias, err := lnwire.NewNodeAlias(alias)
1✔
907
        if err != nil {
1✔
908
                return nil, err
×
909
        }
×
910
        selfNode := &models.LightningNode{
1✔
911
                HaveNodeAnnouncement: true,
1✔
912
                LastUpdate:           time.Now(),
1✔
913
                Addresses:            selfAddrs,
1✔
914
                Alias:                nodeAlias.String(),
1✔
915
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
1✔
916
                Color:                color,
1✔
917
        }
1✔
918
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
1✔
919

1✔
920
        // Based on the disk representation of the node announcement generated
1✔
921
        // above, we'll generate a node announcement that can go out on the
1✔
922
        // network so we can properly sign it.
1✔
923
        nodeAnn, err := selfNode.NodeAnnouncement(false)
1✔
924
        if err != nil {
1✔
925
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
926
        }
×
927

928
        // With the announcement generated, we'll sign it to properly
929
        // authenticate the message on the network.
930
        authSig, err := netann.SignAnnouncement(
1✔
931
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
1✔
932
        )
1✔
933
        if err != nil {
1✔
934
                return nil, fmt.Errorf("unable to generate signature for "+
×
935
                        "self node announcement: %v", err)
×
936
        }
×
937
        selfNode.AuthSigBytes = authSig.Serialize()
1✔
938
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
1✔
939
                selfNode.AuthSigBytes,
1✔
940
        )
1✔
941
        if err != nil {
1✔
942
                return nil, err
×
943
        }
×
944

945
        // Finally, we'll update the representation on disk, and update our
946
        // cached in-memory version as well.
947
        if err := dbs.GraphDB.SetSourceNode(selfNode); err != nil {
1✔
948
                return nil, fmt.Errorf("can't set self node: %w", err)
×
949
        }
×
950
        s.currentNodeAnn = nodeAnn
1✔
951

1✔
952
        // The router will get access to the payment ID sequencer, such that it
1✔
953
        // can generate unique payment IDs.
1✔
954
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
1✔
955
        if err != nil {
1✔
956
                return nil, err
×
957
        }
×
958

959
        // Instantiate mission control with config from the sub server.
960
        //
961
        // TODO(joostjager): When we are further in the process of moving to sub
962
        // servers, the mission control instance itself can be moved there too.
963
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
1✔
964

1✔
965
        // We only initialize a probability estimator if there's no custom one.
1✔
966
        var estimator routing.Estimator
1✔
967
        if cfg.Estimator != nil {
1✔
968
                estimator = cfg.Estimator
×
969
        } else {
1✔
970
                switch routingConfig.ProbabilityEstimatorType {
1✔
971
                case routing.AprioriEstimatorName:
1✔
972
                        aCfg := routingConfig.AprioriConfig
1✔
973
                        aprioriConfig := routing.AprioriConfig{
1✔
974
                                AprioriHopProbability: aCfg.HopProbability,
1✔
975
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
1✔
976
                                AprioriWeight:         aCfg.Weight,
1✔
977
                                CapacityFraction:      aCfg.CapacityFraction,
1✔
978
                        }
1✔
979

1✔
980
                        estimator, err = routing.NewAprioriEstimator(
1✔
981
                                aprioriConfig,
1✔
982
                        )
1✔
983
                        if err != nil {
1✔
984
                                return nil, err
×
985
                        }
×
986

987
                case routing.BimodalEstimatorName:
×
988
                        bCfg := routingConfig.BimodalConfig
×
989
                        bimodalConfig := routing.BimodalConfig{
×
990
                                BimodalNodeWeight: bCfg.NodeWeight,
×
991
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
992
                                        bCfg.Scale,
×
993
                                ),
×
994
                                BimodalDecayTime: bCfg.DecayTime,
×
995
                        }
×
996

×
997
                        estimator, err = routing.NewBimodalEstimator(
×
998
                                bimodalConfig,
×
999
                        )
×
1000
                        if err != nil {
×
1001
                                return nil, err
×
1002
                        }
×
1003

1004
                default:
×
1005
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1006
                                routingConfig.ProbabilityEstimatorType)
×
1007
                }
1008
        }
1009

1010
        mcCfg := &routing.MissionControlConfig{
1✔
1011
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
1✔
1012
                Estimator:               estimator,
1✔
1013
                MaxMcHistory:            routingConfig.MaxMcHistory,
1✔
1014
                McFlushInterval:         routingConfig.McFlushInterval,
1✔
1015
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
1✔
1016
        }
1✔
1017

1✔
1018
        s.missionController, err = routing.NewMissionController(
1✔
1019
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
1✔
1020
        )
1✔
1021
        if err != nil {
1✔
1022
                return nil, fmt.Errorf("can't create mission control "+
×
1023
                        "manager: %w", err)
×
1024
        }
×
1025
        s.defaultMC, err = s.missionController.GetNamespacedStore(
1✔
1026
                routing.DefaultMissionControlNamespace,
1✔
1027
        )
1✔
1028
        if err != nil {
1✔
1029
                return nil, fmt.Errorf("can't create mission control in the "+
×
1030
                        "default namespace: %w", err)
×
1031
        }
×
1032

1033
        srvrLog.Debugf("Instantiating payment session source with config: "+
1✔
1034
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
1✔
1035
                int64(routingConfig.AttemptCost),
1✔
1036
                float64(routingConfig.AttemptCostPPM)/10000,
1✔
1037
                routingConfig.MinRouteProbability)
1✔
1038

1✔
1039
        pathFindingConfig := routing.PathFindingConfig{
1✔
1040
                AttemptCost: lnwire.NewMSatFromSatoshis(
1✔
1041
                        routingConfig.AttemptCost,
1✔
1042
                ),
1✔
1043
                AttemptCostPPM: routingConfig.AttemptCostPPM,
1✔
1044
                MinProbability: routingConfig.MinRouteProbability,
1✔
1045
        }
1✔
1046

1✔
1047
        sourceNode, err := dbs.GraphDB.SourceNode()
1✔
1048
        if err != nil {
1✔
1049
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1050
        }
×
1051
        paymentSessionSource := &routing.SessionSource{
1✔
1052
                GraphSessionFactory: dbs.GraphDB,
1✔
1053
                SourceNode:          sourceNode,
1✔
1054
                MissionControl:      s.defaultMC,
1✔
1055
                GetLink:             s.htlcSwitch.GetLinkByShortID,
1✔
1056
                PathFindingConfig:   pathFindingConfig,
1✔
1057
        }
1✔
1058

1✔
1059
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
1✔
1060

1✔
1061
        s.controlTower = routing.NewControlTower(paymentControl)
1✔
1062

1✔
1063
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
1✔
1064
                cfg.Routing.StrictZombiePruning
1✔
1065

1✔
1066
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
1✔
1067
                SelfNode:            selfNode.PubKeyBytes,
1✔
1068
                Graph:               dbs.GraphDB,
1✔
1069
                Chain:               cc.ChainIO,
1✔
1070
                ChainView:           cc.ChainView,
1✔
1071
                Notifier:            cc.ChainNotifier,
1✔
1072
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
1✔
1073
                GraphPruneInterval:  time.Hour,
1✔
1074
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
1✔
1075
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
1✔
1076
                StrictZombiePruning: strictPruning,
1✔
1077
                IsAlias:             aliasmgr.IsAlias,
1✔
1078
        })
1✔
1079
        if err != nil {
1✔
1080
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1081
        }
×
1082

1083
        s.chanRouter, err = routing.New(routing.Config{
1✔
1084
                SelfNode:           selfNode.PubKeyBytes,
1✔
1085
                RoutingGraph:       dbs.GraphDB,
1✔
1086
                Chain:              cc.ChainIO,
1✔
1087
                Payer:              s.htlcSwitch,
1✔
1088
                Control:            s.controlTower,
1✔
1089
                MissionControl:     s.defaultMC,
1✔
1090
                SessionSource:      paymentSessionSource,
1✔
1091
                GetLink:            s.htlcSwitch.GetLinkByShortID,
1✔
1092
                NextPaymentID:      sequencer.NextID,
1✔
1093
                PathFindingConfig:  pathFindingConfig,
1✔
1094
                Clock:              clock.NewDefaultClock(),
1✔
1095
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
1✔
1096
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
1✔
1097
                TrafficShaper:      implCfg.TrafficShaper,
1✔
1098
        })
1✔
1099
        if err != nil {
1✔
1100
                return nil, fmt.Errorf("can't create router: %w", err)
×
1101
        }
×
1102

1103
        chanSeries := discovery.NewChanSeries(s.graphDB)
1✔
1104
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
1✔
1105
        if err != nil {
1✔
1106
                return nil, err
×
1107
        }
×
1108
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
1✔
1109
        if err != nil {
1✔
1110
                return nil, err
×
1111
        }
×
1112

1113
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
1✔
1114

1✔
1115
        s.authGossiper = discovery.New(discovery.Config{
1✔
1116
                Graph:                 s.graphBuilder,
1✔
1117
                ChainIO:               s.cc.ChainIO,
1✔
1118
                Notifier:              s.cc.ChainNotifier,
1✔
1119
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
1✔
1120
                Broadcast:             s.BroadcastMessage,
1✔
1121
                ChanSeries:            chanSeries,
1✔
1122
                NotifyWhenOnline:      s.NotifyWhenOnline,
1✔
1123
                NotifyWhenOffline:     s.NotifyWhenOffline,
1✔
1124
                FetchSelfAnnouncement: s.getNodeAnnouncement,
1✔
1125
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
1✔
1126
                        error) {
1✔
1127

×
1128
                        return s.genNodeAnnouncement(nil)
×
1129
                },
×
1130
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1131
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1132
                RetransmitTicker:        ticker.New(time.Minute * 30),
1133
                RebroadcastInterval:     time.Hour * 24,
1134
                WaitingProofStore:       waitingProofStore,
1135
                MessageStore:            gossipMessageStore,
1136
                AnnSigner:               s.nodeSigner,
1137
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1138
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1139
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1140
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1141
                MinimumBatchSize:        10,
1142
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1143
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1144
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1145
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1146
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1147
                IsAlias:                 aliasmgr.IsAlias,
1148
                SignAliasUpdate:         s.signAliasUpdate,
1149
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1150
                GetAlias:                s.aliasMgr.GetPeerAlias,
1151
                FindChannel:             s.findChannel,
1152
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1153
                ScidCloser:              scidCloserMan,
1154
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1155
        }, nodeKeyDesc)
1156

1157
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
1✔
1158
        //nolint:ll
1✔
1159
        s.localChanMgr = &localchans.Manager{
1✔
1160
                SelfPub:              nodeKeyDesc.PubKey,
1✔
1161
                DefaultRoutingPolicy: cc.RoutingPolicy,
1✔
1162
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
1✔
1163
                        *models.ChannelEdgePolicy) error) error {
2✔
1164

1✔
1165
                        return s.graphDB.ForEachNodeChannel(selfVertex,
1✔
1166
                                func(_ kvdb.RTx, c *models.ChannelEdgeInfo,
1✔
1167
                                        e *models.ChannelEdgePolicy,
1✔
1168
                                        _ *models.ChannelEdgePolicy) error {
2✔
1169

1✔
1170
                                        // NOTE: The invoked callback here may
1✔
1171
                                        // receive a nil channel policy.
1✔
1172
                                        return cb(c, e)
1✔
1173
                                },
1✔
1174
                        )
1175
                },
1176
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1177
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1178
                FetchChannel:              s.chanStateDB.FetchChannel,
1179
                AddEdge: func(edge *models.ChannelEdgeInfo) error {
×
1180
                        return s.graphBuilder.AddEdge(edge)
×
1181
                },
×
1182
        }
1183

1184
        utxnStore, err := contractcourt.NewNurseryStore(
1✔
1185
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
1✔
1186
        )
1✔
1187
        if err != nil {
1✔
1188
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1189
                return nil, err
×
1190
        }
×
1191

1192
        sweeperStore, err := sweep.NewSweeperStore(
1✔
1193
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
1✔
1194
        )
1✔
1195
        if err != nil {
1✔
1196
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1197
                return nil, err
×
1198
        }
×
1199

1200
        aggregator := sweep.NewBudgetAggregator(
1✔
1201
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
1✔
1202
                s.implCfg.AuxSweeper,
1✔
1203
        )
1✔
1204

1✔
1205
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
1✔
1206
                Signer:     cc.Wallet.Cfg.Signer,
1✔
1207
                Wallet:     cc.Wallet,
1✔
1208
                Estimator:  cc.FeeEstimator,
1✔
1209
                Notifier:   cc.ChainNotifier,
1✔
1210
                AuxSweeper: s.implCfg.AuxSweeper,
1✔
1211
        })
1✔
1212

1✔
1213
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
1✔
1214
                FeeEstimator: cc.FeeEstimator,
1✔
1215
                GenSweepScript: newSweepPkScriptGen(
1✔
1216
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
1✔
1217
                ),
1✔
1218
                Signer:               cc.Wallet.Cfg.Signer,
1✔
1219
                Wallet:               newSweeperWallet(cc.Wallet),
1✔
1220
                Mempool:              cc.MempoolNotifier,
1✔
1221
                Notifier:             cc.ChainNotifier,
1✔
1222
                Store:                sweeperStore,
1✔
1223
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
1✔
1224
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
1✔
1225
                Aggregator:           aggregator,
1✔
1226
                Publisher:            s.txPublisher,
1✔
1227
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
1✔
1228
        })
1✔
1229

1✔
1230
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
1✔
1231
                ChainIO:             cc.ChainIO,
1✔
1232
                ConfDepth:           1,
1✔
1233
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
1✔
1234
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
1✔
1235
                Notifier:            cc.ChainNotifier,
1✔
1236
                PublishTransaction:  cc.Wallet.PublishTransaction,
1✔
1237
                Store:               utxnStore,
1✔
1238
                SweepInput:          s.sweeper.SweepInput,
1✔
1239
                Budget:              s.cfg.Sweeper.Budget,
1✔
1240
        })
1✔
1241

1✔
1242
        // Construct a closure that wraps the htlcswitch's CloseLink method.
1✔
1243
        closeLink := func(chanPoint *wire.OutPoint,
1✔
1244
                closureType contractcourt.ChannelCloseType) {
2✔
1245
                // TODO(conner): Properly respect the update and error channels
1✔
1246
                // returned by CloseLink.
1✔
1247

1✔
1248
                // Instruct the switch to close the channel.  Provide no close out
1✔
1249
                // delivery script or target fee per kw because user input is not
1✔
1250
                // available when the remote peer closes the channel.
1✔
1251
                s.htlcSwitch.CloseLink(
1✔
1252
                        context.Background(), chanPoint, closureType, 0, 0, nil,
1✔
1253
                )
1✔
1254
        }
1✔
1255

1256
        // We will use the following channel to reliably hand off contract
1257
        // breach events from the ChannelArbitrator to the BreachArbitrator,
1258
        contractBreaches := make(chan *contractcourt.ContractBreachEvent, 1)
1✔
1259

1✔
1260
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
1✔
1261
                &contractcourt.BreachConfig{
1✔
1262
                        CloseLink: closeLink,
1✔
1263
                        DB:        s.chanStateDB,
1✔
1264
                        Estimator: s.cc.FeeEstimator,
1✔
1265
                        GenSweepScript: newSweepPkScriptGen(
1✔
1266
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
1✔
1267
                        ),
1✔
1268
                        Notifier:           cc.ChainNotifier,
1✔
1269
                        PublishTransaction: cc.Wallet.PublishTransaction,
1✔
1270
                        ContractBreaches:   contractBreaches,
1✔
1271
                        Signer:             cc.Wallet.Cfg.Signer,
1✔
1272
                        Store: contractcourt.NewRetributionStore(
1✔
1273
                                dbs.ChanStateDB,
1✔
1274
                        ),
1✔
1275
                        AuxSweeper: s.implCfg.AuxSweeper,
1✔
1276
                },
1✔
1277
        )
1✔
1278

1✔
1279
        //nolint:ll
1✔
1280
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
1✔
1281
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
1✔
1282
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
1✔
1283
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
1✔
1284
                NewSweepAddr: func() ([]byte, error) {
1✔
1285
                        addr, err := newSweepPkScriptGen(
×
1286
                                cc.Wallet, netParams,
×
1287
                        )().Unpack()
×
1288
                        if err != nil {
×
1289
                                return nil, err
×
1290
                        }
×
1291

1292
                        return addr.DeliveryAddress, nil
×
1293
                },
1294
                PublishTx: cc.Wallet.PublishTransaction,
1295
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
1✔
1296
                        for _, msg := range msgs {
2✔
1297
                                err := s.htlcSwitch.ProcessContractResolution(msg)
1✔
1298
                                if err != nil {
1✔
1299
                                        return err
×
1300
                                }
×
1301
                        }
1302
                        return nil
1✔
1303
                },
1304
                IncubateOutputs: func(chanPoint wire.OutPoint,
1305
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1306
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1307
                        broadcastHeight uint32,
1308
                        deadlineHeight fn.Option[int32]) error {
1✔
1309

1✔
1310
                        return s.utxoNursery.IncubateOutputs(
1✔
1311
                                chanPoint, outHtlcRes, inHtlcRes,
1✔
1312
                                broadcastHeight, deadlineHeight,
1✔
1313
                        )
1✔
1314
                },
1✔
1315
                PreimageDB:   s.witnessBeacon,
1316
                Notifier:     cc.ChainNotifier,
1317
                Mempool:      cc.MempoolNotifier,
1318
                Signer:       cc.Wallet.Cfg.Signer,
1319
                FeeEstimator: cc.FeeEstimator,
1320
                ChainIO:      cc.ChainIO,
1321
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
1✔
1322
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
1✔
1323
                        s.htlcSwitch.RemoveLink(chanID)
1✔
1324
                        return nil
1✔
1325
                },
1✔
1326
                IsOurAddress: cc.Wallet.IsOurAddress,
1327
                ContractBreach: func(chanPoint wire.OutPoint,
1328
                        breachRet *lnwallet.BreachRetribution) error {
1✔
1329

1✔
1330
                        // processACK will handle the BreachArbitrator ACKing
1✔
1331
                        // the event.
1✔
1332
                        finalErr := make(chan error, 1)
1✔
1333
                        processACK := func(brarErr error) {
2✔
1334
                                if brarErr != nil {
1✔
1335
                                        finalErr <- brarErr
×
1336
                                        return
×
1337
                                }
×
1338

1339
                                // If the BreachArbitrator successfully handled
1340
                                // the event, we can signal that the handoff
1341
                                // was successful.
1342
                                finalErr <- nil
1✔
1343
                        }
1344

1345
                        event := &contractcourt.ContractBreachEvent{
1✔
1346
                                ChanPoint:         chanPoint,
1✔
1347
                                ProcessACK:        processACK,
1✔
1348
                                BreachRetribution: breachRet,
1✔
1349
                        }
1✔
1350

1✔
1351
                        // Send the contract breach event to the
1✔
1352
                        // BreachArbitrator.
1✔
1353
                        select {
1✔
1354
                        case contractBreaches <- event:
1✔
1355
                        case <-s.quit:
×
1356
                                return ErrServerShuttingDown
×
1357
                        }
1358

1359
                        // We'll wait for a final error to be available from
1360
                        // the BreachArbitrator.
1361
                        select {
1✔
1362
                        case err := <-finalErr:
1✔
1363
                                return err
1✔
1364
                        case <-s.quit:
×
1365
                                return ErrServerShuttingDown
×
1366
                        }
1367
                },
1368
                DisableChannel: func(chanPoint wire.OutPoint) error {
1✔
1369
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
1✔
1370
                },
1✔
1371
                Sweeper:                       s.sweeper,
1372
                Registry:                      s.invoices,
1373
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1374
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1375
                OnionProcessor:                s.sphinx,
1376
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1377
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1378
                Clock:                         clock.NewDefaultClock(),
1379
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1380
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1381
                HtlcNotifier:                  s.htlcNotifier,
1382
                Budget:                        *s.cfg.Sweeper.Budget,
1383

1384
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1385
                QueryIncomingCircuit: func(
1386
                        circuit models.CircuitKey) *models.CircuitKey {
1✔
1387

1✔
1388
                        // Get the circuit map.
1✔
1389
                        circuits := s.htlcSwitch.CircuitLookup()
1✔
1390

1✔
1391
                        // Lookup the outgoing circuit.
1✔
1392
                        pc := circuits.LookupOpenCircuit(circuit)
1✔
1393
                        if pc == nil {
2✔
1394
                                return nil
1✔
1395
                        }
1✔
1396

1397
                        return &pc.Incoming
1✔
1398
                },
1399
                AuxLeafStore: implCfg.AuxLeafStore,
1400
                AuxSigner:    implCfg.AuxSigner,
1401
                AuxResolver:  implCfg.AuxContractResolver,
1402
        }, dbs.ChanStateDB)
1403

1404
        // Select the configuration and funding parameters for Bitcoin.
1405
        chainCfg := cfg.Bitcoin
1✔
1406
        minRemoteDelay := funding.MinBtcRemoteDelay
1✔
1407
        maxRemoteDelay := funding.MaxBtcRemoteDelay
1✔
1408

1✔
1409
        var chanIDSeed [32]byte
1✔
1410
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
1✔
1411
                return nil, err
×
1412
        }
×
1413

1414
        // Wrap the DeleteChannelEdges method so that the funding manager can
1415
        // use it without depending on several layers of indirection.
1416
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
1✔
1417
                *models.ChannelEdgePolicy, error) {
2✔
1418

1✔
1419
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
1✔
1420
                        scid.ToUint64(),
1✔
1421
                )
1✔
1422
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
1✔
1423
                        // This is unlikely but there is a slim chance of this
×
1424
                        // being hit if lnd was killed via SIGKILL and the
×
1425
                        // funding manager was stepping through the delete
×
1426
                        // alias edge logic.
×
1427
                        return nil, nil
×
1428
                } else if err != nil {
1✔
1429
                        return nil, err
×
1430
                }
×
1431

1432
                // Grab our key to find our policy.
1433
                var ourKey [33]byte
1✔
1434
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
1✔
1435

1✔
1436
                var ourPolicy *models.ChannelEdgePolicy
1✔
1437
                if info != nil && info.NodeKey1Bytes == ourKey {
2✔
1438
                        ourPolicy = e1
1✔
1439
                } else {
2✔
1440
                        ourPolicy = e2
1✔
1441
                }
1✔
1442

1443
                if ourPolicy == nil {
1✔
1444
                        // Something is wrong, so return an error.
×
1445
                        return nil, fmt.Errorf("we don't have an edge")
×
1446
                }
×
1447

1448
                err = s.graphDB.DeleteChannelEdges(
1✔
1449
                        false, false, scid.ToUint64(),
1✔
1450
                )
1✔
1451
                return ourPolicy, err
1✔
1452
        }
1453

1454
        // For the reservationTimeout and the zombieSweeperInterval different
1455
        // values are set in case we are in a dev environment so enhance test
1456
        // capacilities.
1457
        reservationTimeout := chanfunding.DefaultReservationTimeout
1✔
1458
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
1✔
1459

1✔
1460
        // Get the development config for funding manager. If we are not in
1✔
1461
        // development mode, this would be nil.
1✔
1462
        var devCfg *funding.DevConfig
1✔
1463
        if lncfg.IsDevBuild() {
2✔
1464
                devCfg = &funding.DevConfig{
1✔
1465
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
1✔
1466
                }
1✔
1467

1✔
1468
                reservationTimeout = cfg.Dev.GetReservationTimeout()
1✔
1469
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
1✔
1470

1✔
1471
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
1✔
1472
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
1✔
1473
                        devCfg, reservationTimeout, zombieSweeperInterval)
1✔
1474
        }
1✔
1475

1476
        //nolint:ll
1477
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
1✔
1478
                Dev:                devCfg,
1✔
1479
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
1✔
1480
                IDKey:              nodeKeyDesc.PubKey,
1✔
1481
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
1✔
1482
                Wallet:             cc.Wallet,
1✔
1483
                PublishTransaction: cc.Wallet.PublishTransaction,
1✔
1484
                UpdateLabel: func(hash chainhash.Hash, label string) error {
2✔
1485
                        return cc.Wallet.LabelTransaction(hash, label, true)
1✔
1486
                },
1✔
1487
                Notifier:     cc.ChainNotifier,
1488
                ChannelDB:    s.chanStateDB,
1489
                FeeEstimator: cc.FeeEstimator,
1490
                SignMessage:  cc.MsgSigner.SignMessage,
1491
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1492
                        error) {
1✔
1493

1✔
1494
                        return s.genNodeAnnouncement(nil)
1✔
1495
                },
1✔
1496
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1497
                NotifyWhenOnline:     s.NotifyWhenOnline,
1498
                TempChanIDSeed:       chanIDSeed,
1499
                FindChannel:          s.findChannel,
1500
                DefaultRoutingPolicy: cc.RoutingPolicy,
1501
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1502
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1503
                        pushAmt lnwire.MilliSatoshi) uint16 {
1✔
1504
                        // For large channels we increase the number
1✔
1505
                        // of confirmations we require for the
1✔
1506
                        // channel to be considered open. As it is
1✔
1507
                        // always the responder that gets to choose
1✔
1508
                        // value, the pushAmt is value being pushed
1✔
1509
                        // to us. This means we have more to lose
1✔
1510
                        // in the case this gets re-orged out, and
1✔
1511
                        // we will require more confirmations before
1✔
1512
                        // we consider it open.
1✔
1513

1✔
1514
                        // In case the user has explicitly specified
1✔
1515
                        // a default value for the number of
1✔
1516
                        // confirmations, we use it.
1✔
1517
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
1✔
1518
                        if defaultConf != 0 {
2✔
1519
                                return defaultConf
1✔
1520
                        }
1✔
1521

1522
                        minConf := uint64(3)
×
1523
                        maxConf := uint64(6)
×
1524

×
1525
                        // If this is a wumbo channel, then we'll require the
×
1526
                        // max amount of confirmations.
×
1527
                        if chanAmt > MaxFundingAmount {
×
1528
                                return uint16(maxConf)
×
1529
                        }
×
1530

1531
                        // If not we return a value scaled linearly
1532
                        // between 3 and 6, depending on channel size.
1533
                        // TODO(halseth): Use 1 as minimum?
1534
                        maxChannelSize := uint64(
×
1535
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1536
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1537
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1538
                        if conf < minConf {
×
1539
                                conf = minConf
×
1540
                        }
×
1541
                        if conf > maxConf {
×
1542
                                conf = maxConf
×
1543
                        }
×
1544
                        return uint16(conf)
×
1545
                },
1546
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
1✔
1547
                        // We scale the remote CSV delay (the time the
1✔
1548
                        // remote have to claim funds in case of a unilateral
1✔
1549
                        // close) linearly from minRemoteDelay blocks
1✔
1550
                        // for small channels, to maxRemoteDelay blocks
1✔
1551
                        // for channels of size MaxFundingAmount.
1✔
1552

1✔
1553
                        // In case the user has explicitly specified
1✔
1554
                        // a default value for the remote delay, we
1✔
1555
                        // use it.
1✔
1556
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
1✔
1557
                        if defaultDelay > 0 {
2✔
1558
                                return defaultDelay
1✔
1559
                        }
1✔
1560

1561
                        // If this is a wumbo channel, then we'll require the
1562
                        // max value.
1563
                        if chanAmt > MaxFundingAmount {
×
1564
                                return maxRemoteDelay
×
1565
                        }
×
1566

1567
                        // If not we scale according to channel size.
1568
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1569
                                chanAmt / MaxFundingAmount)
×
1570
                        if delay < minRemoteDelay {
×
1571
                                delay = minRemoteDelay
×
1572
                        }
×
1573
                        if delay > maxRemoteDelay {
×
1574
                                delay = maxRemoteDelay
×
1575
                        }
×
1576
                        return delay
×
1577
                },
1578
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1579
                        peerKey *btcec.PublicKey) error {
1✔
1580

1✔
1581
                        // First, we'll mark this new peer as a persistent peer
1✔
1582
                        // for re-connection purposes. If the peer is not yet
1✔
1583
                        // tracked or the user hasn't requested it to be perm,
1✔
1584
                        // we'll set false to prevent the server from continuing
1✔
1585
                        // to connect to this peer even if the number of
1✔
1586
                        // channels with this peer is zero.
1✔
1587
                        s.mu.Lock()
1✔
1588
                        pubStr := string(peerKey.SerializeCompressed())
1✔
1589
                        if _, ok := s.persistentPeers[pubStr]; !ok {
2✔
1590
                                s.persistentPeers[pubStr] = false
1✔
1591
                        }
1✔
1592
                        s.mu.Unlock()
1✔
1593

1✔
1594
                        // With that taken care of, we'll send this channel to
1✔
1595
                        // the chain arb so it can react to on-chain events.
1✔
1596
                        return s.chainArb.WatchNewChannel(channel)
1✔
1597
                },
1598
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
1✔
1599
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
1✔
1600
                        return s.htlcSwitch.UpdateShortChanID(cid)
1✔
1601
                },
1✔
1602
                RequiredRemoteChanReserve: func(chanAmt,
1603
                        dustLimit btcutil.Amount) btcutil.Amount {
1✔
1604

1✔
1605
                        // By default, we'll require the remote peer to maintain
1✔
1606
                        // at least 1% of the total channel capacity at all
1✔
1607
                        // times. If this value ends up dipping below the dust
1✔
1608
                        // limit, then we'll use the dust limit itself as the
1✔
1609
                        // reserve as required by BOLT #2.
1✔
1610
                        reserve := chanAmt / 100
1✔
1611
                        if reserve < dustLimit {
2✔
1612
                                reserve = dustLimit
1✔
1613
                        }
1✔
1614

1615
                        return reserve
1✔
1616
                },
1617
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
1✔
1618
                        // By default, we'll allow the remote peer to fully
1✔
1619
                        // utilize the full bandwidth of the channel, minus our
1✔
1620
                        // required reserve.
1✔
1621
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
1✔
1622
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
1✔
1623
                },
1✔
1624
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
1✔
1625
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
2✔
1626
                                return cfg.DefaultRemoteMaxHtlcs
1✔
1627
                        }
1✔
1628

1629
                        // By default, we'll permit them to utilize the full
1630
                        // channel bandwidth.
1631
                        return uint16(input.MaxHTLCNumber / 2)
×
1632
                },
1633
                ZombieSweeperInterval:         zombieSweeperInterval,
1634
                ReservationTimeout:            reservationTimeout,
1635
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1636
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1637
                MaxPendingChannels:            cfg.MaxPendingChannels,
1638
                RejectPush:                    cfg.RejectPush,
1639
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1640
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
1641
                OpenChannelPredicate:          chanPredicate,
1642
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
1643
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1644
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1645
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1646
                DeleteAliasEdge:      deleteAliasEdge,
1647
                AliasManager:         s.aliasMgr,
1648
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1649
                AuxFundingController: implCfg.AuxFundingController,
1650
                AuxSigner:            implCfg.AuxSigner,
1651
                AuxResolver:          implCfg.AuxContractResolver,
1652
        })
1653
        if err != nil {
1✔
1654
                return nil, err
×
1655
        }
×
1656

1657
        // Next, we'll assemble the sub-system that will maintain an on-disk
1658
        // static backup of the latest channel state.
1659
        chanNotifier := &channelNotifier{
1✔
1660
                chanNotifier: s.channelNotifier,
1✔
1661
                addrs:        s.addrSource,
1✔
1662
        }
1✔
1663
        backupFile := chanbackup.NewMultiFile(
1✔
1664
                cfg.BackupFilePath, cfg.NoBackupArchive,
1✔
1665
        )
1✔
1666
        startingChans, err := chanbackup.FetchStaticChanBackups(
1✔
1667
                s.chanStateDB, s.addrSource,
1✔
1668
        )
1✔
1669
        if err != nil {
1✔
1670
                return nil, err
×
1671
        }
×
1672
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
1✔
1673
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
1✔
1674
        )
1✔
1675
        if err != nil {
1✔
1676
                return nil, err
×
1677
        }
×
1678

1679
        // Assemble a peer notifier which will provide clients with subscriptions
1680
        // to peer online and offline events.
1681
        s.peerNotifier = peernotifier.New()
1✔
1682

1✔
1683
        // Create a channel event store which monitors all open channels.
1✔
1684
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
1✔
1685
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
2✔
1686
                        return s.channelNotifier.SubscribeChannelEvents()
1✔
1687
                },
1✔
1688
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
1✔
1689
                        return s.peerNotifier.SubscribePeerEvents()
1✔
1690
                },
1✔
1691
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1692
                Clock:           clock.NewDefaultClock(),
1693
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1694
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1695
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1696
        })
1697

1698
        if cfg.WtClient.Active {
2✔
1699
                policy := wtpolicy.DefaultPolicy()
1✔
1700
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
1✔
1701

1✔
1702
                // We expose the sweep fee rate in sat/vbyte, but the tower
1✔
1703
                // protocol operations on sat/kw.
1✔
1704
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
1✔
1705
                        1000 * cfg.WtClient.SweepFeeRate,
1✔
1706
                )
1✔
1707

1✔
1708
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
1✔
1709

1✔
1710
                if err := policy.Validate(); err != nil {
1✔
1711
                        return nil, err
×
1712
                }
×
1713

1714
                // authDial is the wrapper around the btrontide.Dial for the
1715
                // watchtower.
1716
                authDial := func(localKey keychain.SingleKeyECDH,
1✔
1717
                        netAddr *lnwire.NetAddress,
1✔
1718
                        dialer tor.DialFunc) (wtserver.Peer, error) {
2✔
1719

1✔
1720
                        return brontide.Dial(
1✔
1721
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
1✔
1722
                        )
1✔
1723
                }
1✔
1724

1725
                // buildBreachRetribution is a call-back that can be used to
1726
                // query the BreachRetribution info and channel type given a
1727
                // channel ID and commitment height.
1728
                buildBreachRetribution := func(chanID lnwire.ChannelID,
1✔
1729
                        commitHeight uint64) (*lnwallet.BreachRetribution,
1✔
1730
                        channeldb.ChannelType, error) {
2✔
1731

1✔
1732
                        channel, err := s.chanStateDB.FetchChannelByID(
1✔
1733
                                nil, chanID,
1✔
1734
                        )
1✔
1735
                        if err != nil {
1✔
1736
                                return nil, 0, err
×
1737
                        }
×
1738

1739
                        br, err := lnwallet.NewBreachRetribution(
1✔
1740
                                channel, commitHeight, 0, nil,
1✔
1741
                                implCfg.AuxLeafStore,
1✔
1742
                                implCfg.AuxContractResolver,
1✔
1743
                        )
1✔
1744
                        if err != nil {
1✔
1745
                                return nil, 0, err
×
1746
                        }
×
1747

1748
                        return br, channel.ChanType, nil
1✔
1749
                }
1750

1751
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
1✔
1752

1✔
1753
                // Copy the policy for legacy channels and set the blob flag
1✔
1754
                // signalling support for anchor channels.
1✔
1755
                anchorPolicy := policy
1✔
1756
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
1✔
1757

1✔
1758
                // Copy the policy for legacy channels and set the blob flag
1✔
1759
                // signalling support for taproot channels.
1✔
1760
                taprootPolicy := policy
1✔
1761
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
1✔
1762
                        blob.FlagTaprootChannel,
1✔
1763
                )
1✔
1764

1✔
1765
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
1✔
1766
                        FetchClosedChannel:     fetchClosedChannel,
1✔
1767
                        BuildBreachRetribution: buildBreachRetribution,
1✔
1768
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
1✔
1769
                        ChainNotifier:          s.cc.ChainNotifier,
1✔
1770
                        SubscribeChannelEvents: func() (subscribe.Subscription,
1✔
1771
                                error) {
2✔
1772

1✔
1773
                                return s.channelNotifier.
1✔
1774
                                        SubscribeChannelEvents()
1✔
1775
                        },
1✔
1776
                        Signer: cc.Wallet.Cfg.Signer,
1777
                        NewAddress: func() ([]byte, error) {
1✔
1778
                                addr, err := newSweepPkScriptGen(
1✔
1779
                                        cc.Wallet, netParams,
1✔
1780
                                )().Unpack()
1✔
1781
                                if err != nil {
1✔
1782
                                        return nil, err
×
1783
                                }
×
1784

1785
                                return addr.DeliveryAddress, nil
1✔
1786
                        },
1787
                        SecretKeyRing:      s.cc.KeyRing,
1788
                        Dial:               cfg.net.Dial,
1789
                        AuthDial:           authDial,
1790
                        DB:                 dbs.TowerClientDB,
1791
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1792
                        MinBackoff:         10 * time.Second,
1793
                        MaxBackoff:         5 * time.Minute,
1794
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1795
                }, policy, anchorPolicy, taprootPolicy)
1796
                if err != nil {
1✔
1797
                        return nil, err
×
1798
                }
×
1799
        }
1800

1801
        if len(cfg.ExternalHosts) != 0 {
1✔
1802
                advertisedIPs := make(map[string]struct{})
×
1803
                for _, addr := range s.currentNodeAnn.Addresses {
×
1804
                        advertisedIPs[addr.String()] = struct{}{}
×
1805
                }
×
1806

1807
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1808
                        Hosts:         cfg.ExternalHosts,
×
1809
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1810
                        LookupHost: func(host string) (net.Addr, error) {
×
1811
                                return lncfg.ParseAddressString(
×
1812
                                        host, strconv.Itoa(defaultPeerPort),
×
1813
                                        cfg.net.ResolveTCPAddr,
×
1814
                                )
×
1815
                        },
×
1816
                        AdvertisedIPs: advertisedIPs,
1817
                        AnnounceNewIPs: netann.IPAnnouncer(
1818
                                func(modifier ...netann.NodeAnnModifier) (
1819
                                        lnwire.NodeAnnouncement, error) {
×
1820

×
1821
                                        return s.genNodeAnnouncement(
×
1822
                                                nil, modifier...,
×
1823
                                        )
×
1824
                                }),
×
1825
                })
1826
        }
1827

1828
        // Create liveness monitor.
1829
        s.createLivenessMonitor(cfg, cc, leaderElector)
1✔
1830

1✔
1831
        // Create the connection manager which will be responsible for
1✔
1832
        // maintaining persistent outbound connections and also accepting new
1✔
1833
        // incoming connections
1✔
1834
        cmgr, err := connmgr.New(&connmgr.Config{
1✔
1835
                Listeners:      listeners,
1✔
1836
                OnAccept:       s.InboundPeerConnected,
1✔
1837
                RetryDuration:  time.Second * 5,
1✔
1838
                TargetOutbound: 100,
1✔
1839
                Dial: noiseDial(
1✔
1840
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
1✔
1841
                ),
1✔
1842
                OnConnection: s.OutboundPeerConnected,
1✔
1843
        })
1✔
1844
        if err != nil {
1✔
1845
                return nil, err
×
1846
        }
×
1847
        s.connMgr = cmgr
1✔
1848

1✔
1849
        // Finally, register the subsystems in blockbeat.
1✔
1850
        s.registerBlockConsumers()
1✔
1851

1✔
1852
        return s, nil
1✔
1853
}
1854

1855
// UpdateRoutingConfig is a callback function to update the routing config
1856
// values in the main cfg.
1857
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
1✔
1858
        routerCfg := s.cfg.SubRPCServers.RouterRPC
1✔
1859

1✔
1860
        switch c := cfg.Estimator.Config().(type) {
1✔
1861
        case routing.AprioriConfig:
1✔
1862
                routerCfg.ProbabilityEstimatorType =
1✔
1863
                        routing.AprioriEstimatorName
1✔
1864

1✔
1865
                targetCfg := routerCfg.AprioriConfig
1✔
1866
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
1✔
1867
                targetCfg.Weight = c.AprioriWeight
1✔
1868
                targetCfg.CapacityFraction = c.CapacityFraction
1✔
1869
                targetCfg.HopProbability = c.AprioriHopProbability
1✔
1870

1871
        case routing.BimodalConfig:
1✔
1872
                routerCfg.ProbabilityEstimatorType =
1✔
1873
                        routing.BimodalEstimatorName
1✔
1874

1✔
1875
                targetCfg := routerCfg.BimodalConfig
1✔
1876
                targetCfg.Scale = int64(c.BimodalScaleMsat)
1✔
1877
                targetCfg.NodeWeight = c.BimodalNodeWeight
1✔
1878
                targetCfg.DecayTime = c.BimodalDecayTime
1✔
1879
        }
1880

1881
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
1✔
1882
}
1883

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

1903
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1904
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1905
// may differ from what is on disk.
1906
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1907
        error) {
1✔
1908

1✔
1909
        data, err := u.DataToSign()
1✔
1910
        if err != nil {
1✔
1911
                return nil, err
×
1912
        }
×
1913

1914
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
1✔
1915
}
1916

1917
// createLivenessMonitor creates a set of health checks using our configured
1918
// values and uses these checks to create a liveness monitor. Available
1919
// health checks,
1920
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1921
//   - diskCheck
1922
//   - tlsHealthCheck
1923
//   - torController, only created when tor is enabled.
1924
//
1925
// If a health check has been disabled by setting attempts to 0, our monitor
1926
// will not run it.
1927
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1928
        leaderElector cluster.LeaderElector) {
1✔
1929

1✔
1930
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
1✔
1931
        if cfg.Bitcoin.Node == "nochainbackend" {
1✔
1932
                srvrLog.Info("Disabling chain backend checks for " +
×
1933
                        "nochainbackend mode")
×
1934

×
1935
                chainBackendAttempts = 0
×
1936
        }
×
1937

1938
        chainHealthCheck := healthcheck.NewObservation(
1✔
1939
                "chain backend",
1✔
1940
                cc.HealthCheck,
1✔
1941
                cfg.HealthChecks.ChainCheck.Interval,
1✔
1942
                cfg.HealthChecks.ChainCheck.Timeout,
1✔
1943
                cfg.HealthChecks.ChainCheck.Backoff,
1✔
1944
                chainBackendAttempts,
1✔
1945
        )
1✔
1946

1✔
1947
        diskCheck := healthcheck.NewObservation(
1✔
1948
                "disk space",
1✔
1949
                func() error {
1✔
1950
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1951
                                cfg.LndDir,
×
1952
                        )
×
1953
                        if err != nil {
×
1954
                                return err
×
1955
                        }
×
1956

1957
                        // If we have more free space than we require,
1958
                        // we return a nil error.
1959
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1960
                                return nil
×
1961
                        }
×
1962

1963
                        return fmt.Errorf("require: %v free space, got: %v",
×
1964
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1965
                                free)
×
1966
                },
1967
                cfg.HealthChecks.DiskCheck.Interval,
1968
                cfg.HealthChecks.DiskCheck.Timeout,
1969
                cfg.HealthChecks.DiskCheck.Backoff,
1970
                cfg.HealthChecks.DiskCheck.Attempts,
1971
        )
1972

1973
        tlsHealthCheck := healthcheck.NewObservation(
1✔
1974
                "tls",
1✔
1975
                func() error {
1✔
1976
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1977
                                s.cc.KeyRing,
×
1978
                        )
×
1979
                        if err != nil {
×
1980
                                return err
×
1981
                        }
×
1982
                        if expired {
×
1983
                                return fmt.Errorf("TLS certificate is "+
×
1984
                                        "expired as of %v", expTime)
×
1985
                        }
×
1986

1987
                        // If the certificate is not outdated, no error needs
1988
                        // to be returned
1989
                        return nil
×
1990
                },
1991
                cfg.HealthChecks.TLSCheck.Interval,
1992
                cfg.HealthChecks.TLSCheck.Timeout,
1993
                cfg.HealthChecks.TLSCheck.Backoff,
1994
                cfg.HealthChecks.TLSCheck.Attempts,
1995
        )
1996

1997
        checks := []*healthcheck.Observation{
1✔
1998
                chainHealthCheck, diskCheck, tlsHealthCheck,
1✔
1999
        }
1✔
2000

1✔
2001
        // If Tor is enabled, add the healthcheck for tor connection.
1✔
2002
        if s.torController != nil {
1✔
2003
                torConnectionCheck := healthcheck.NewObservation(
×
2004
                        "tor connection",
×
2005
                        func() error {
×
2006
                                return healthcheck.CheckTorServiceStatus(
×
2007
                                        s.torController,
×
2008
                                        s.createNewHiddenService,
×
2009
                                )
×
2010
                        },
×
2011
                        cfg.HealthChecks.TorConnection.Interval,
2012
                        cfg.HealthChecks.TorConnection.Timeout,
2013
                        cfg.HealthChecks.TorConnection.Backoff,
2014
                        cfg.HealthChecks.TorConnection.Attempts,
2015
                )
2016
                checks = append(checks, torConnectionCheck)
×
2017
        }
2018

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

1✔
2027
                remoteSignerConnectionCheck := healthcheck.NewObservation(
1✔
2028
                        "remote signer connection",
1✔
2029
                        rpcwallet.HealthCheck(
1✔
2030
                                s.cfg.RemoteSigner,
1✔
2031

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

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

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

2071
                                if !leader {
×
2072
                                        srvrLog.Debug("Not the current leader")
×
2073
                                        return fmt.Errorf("not the current " +
×
2074
                                                "leader")
×
2075
                                }
×
2076

2077
                                return nil
×
2078
                        },
2079
                        cfg.HealthChecks.LeaderCheck.Interval,
2080
                        cfg.HealthChecks.LeaderCheck.Timeout,
2081
                        cfg.HealthChecks.LeaderCheck.Backoff,
2082
                        cfg.HealthChecks.LeaderCheck.Attempts,
2083
                )
2084

2085
                checks = append(checks, leaderCheck)
×
2086
        }
2087

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

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

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

2110
// add is used to add a cleanup function to be called when
2111
// the run function is executed.
2112
func (c cleaner) add(cleanup func() error) cleaner {
1✔
2113
        return append(c, cleanup)
1✔
2114
}
1✔
2115

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

2125
// startLowLevelServices starts the low-level services of the server. These
2126
// services must be started successfully before running the main server. The
2127
// services are,
2128
// 1. the chain notifier.
2129
//
2130
// TODO(yy): identify and add more low-level services here.
2131
func (s *server) startLowLevelServices() error {
1✔
2132
        var startErr error
1✔
2133

1✔
2134
        cleanup := cleaner{}
1✔
2135

1✔
2136
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
1✔
2137
        if err := s.cc.ChainNotifier.Start(); err != nil {
1✔
2138
                startErr = err
×
2139
        }
×
2140

2141
        if startErr != nil {
1✔
2142
                cleanup.run()
×
2143
        }
×
2144

2145
        return startErr
1✔
2146
}
2147

2148
// Start starts the main daemon server, all requested listeners, and any helper
2149
// goroutines.
2150
// NOTE: This function is safe for concurrent access.
2151
//
2152
//nolint:funlen
2153
func (s *server) Start() error {
1✔
2154
        // Get the current blockbeat.
1✔
2155
        beat, err := s.getStartingBeat()
1✔
2156
        if err != nil {
1✔
2157
                return err
×
2158
        }
×
2159

2160
        var startErr error
1✔
2161

1✔
2162
        // If one sub system fails to start, the following code ensures that the
1✔
2163
        // previous started ones are stopped. It also ensures a proper wallet
1✔
2164
        // shutdown which is important for releasing its resources (boltdb, etc...)
1✔
2165
        cleanup := cleaner{}
1✔
2166

1✔
2167
        s.start.Do(func() {
2✔
2168
                cleanup = cleanup.add(s.customMessageServer.Stop)
1✔
2169
                if err := s.customMessageServer.Start(); err != nil {
1✔
2170
                        startErr = err
×
2171
                        return
×
2172
                }
×
2173

2174
                if s.hostAnn != nil {
1✔
2175
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2176
                        if err := s.hostAnn.Start(); err != nil {
×
2177
                                startErr = err
×
2178
                                return
×
2179
                        }
×
2180
                }
2181

2182
                if s.livenessMonitor != nil {
2✔
2183
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
1✔
2184
                        if err := s.livenessMonitor.Start(); err != nil {
1✔
2185
                                startErr = err
×
2186
                                return
×
2187
                        }
×
2188
                }
2189

2190
                // Start the notification server. This is used so channel
2191
                // management goroutines can be notified when a funding
2192
                // transaction reaches a sufficient number of confirmations, or
2193
                // when the input for the funding transaction is spent in an
2194
                // attempt at an uncooperative close by the counterparty.
2195
                cleanup = cleanup.add(s.sigPool.Stop)
1✔
2196
                if err := s.sigPool.Start(); err != nil {
1✔
2197
                        startErr = err
×
2198
                        return
×
2199
                }
×
2200

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

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

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

2219
                cleanup = cleanup.add(s.channelNotifier.Stop)
1✔
2220
                if err := s.channelNotifier.Start(); err != nil {
1✔
2221
                        startErr = err
×
2222
                        return
×
2223
                }
×
2224

2225
                cleanup = cleanup.add(func() error {
1✔
2226
                        return s.peerNotifier.Stop()
×
2227
                })
×
2228
                if err := s.peerNotifier.Start(); err != nil {
1✔
2229
                        startErr = err
×
2230
                        return
×
2231
                }
×
2232

2233
                cleanup = cleanup.add(s.htlcNotifier.Stop)
1✔
2234
                if err := s.htlcNotifier.Start(); err != nil {
1✔
2235
                        startErr = err
×
2236
                        return
×
2237
                }
×
2238

2239
                if s.towerClientMgr != nil {
2✔
2240
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
1✔
2241
                        if err := s.towerClientMgr.Start(); err != nil {
1✔
2242
                                startErr = err
×
2243
                                return
×
2244
                        }
×
2245
                }
2246

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

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

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

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

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

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

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

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

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

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

2310
                cleanup = cleanup.add(s.chanRouter.Stop)
1✔
2311
                if err := s.chanRouter.Start(); err != nil {
1✔
2312
                        startErr = err
×
2313
                        return
×
2314
                }
×
2315
                // The authGossiper depends on the chanRouter and therefore
2316
                // should be started after it.
2317
                cleanup = cleanup.add(s.authGossiper.Stop)
1✔
2318
                if err := s.authGossiper.Start(); err != nil {
1✔
2319
                        startErr = err
×
2320
                        return
×
2321
                }
×
2322

2323
                cleanup = cleanup.add(s.invoices.Stop)
1✔
2324
                if err := s.invoices.Start(); err != nil {
1✔
2325
                        startErr = err
×
2326
                        return
×
2327
                }
×
2328

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

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

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

2347
                cleanup.add(func() error {
1✔
2348
                        s.missionController.StopStoreTickers()
×
2349
                        return nil
×
2350
                })
×
2351
                s.missionController.RunStoreTickers()
1✔
2352

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

2385
                // chanSubSwapper must be started after the `channelNotifier`
2386
                // because it depends on channel events as a synchronization
2387
                // point.
2388
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
1✔
2389
                if err := s.chanSubSwapper.Start(); err != nil {
1✔
2390
                        startErr = err
×
2391
                        return
×
2392
                }
×
2393

2394
                if s.torController != nil {
1✔
2395
                        cleanup = cleanup.add(s.torController.Stop)
×
2396
                        if err := s.createNewHiddenService(); err != nil {
×
2397
                                startErr = err
×
2398
                                return
×
2399
                        }
×
2400
                }
2401

2402
                if s.natTraversal != nil {
1✔
2403
                        s.wg.Add(1)
×
2404
                        go s.watchExternalIP()
×
2405
                }
×
2406

2407
                // Start connmgr last to prevent connections before init.
2408
                cleanup = cleanup.add(func() error {
1✔
2409
                        s.connMgr.Stop()
×
2410
                        return nil
×
2411
                })
×
2412
                s.connMgr.Start()
1✔
2413

1✔
2414
                // If peers are specified as a config option, we'll add those
1✔
2415
                // peers first.
1✔
2416
                for _, peerAddrCfg := range s.cfg.AddPeers {
2✔
2417
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
1✔
2418
                                peerAddrCfg,
1✔
2419
                        )
1✔
2420
                        if err != nil {
1✔
2421
                                startErr = fmt.Errorf("unable to parse peer "+
×
2422
                                        "pubkey from config: %v", err)
×
2423
                                return
×
2424
                        }
×
2425
                        addr, err := parseAddr(parsedHost, s.cfg.net)
1✔
2426
                        if err != nil {
1✔
2427
                                startErr = fmt.Errorf("unable to parse peer "+
×
2428
                                        "address provided as a config option: "+
×
2429
                                        "%v", err)
×
2430
                                return
×
2431
                        }
×
2432

2433
                        peerAddr := &lnwire.NetAddress{
1✔
2434
                                IdentityKey: parsedPubkey,
1✔
2435
                                Address:     addr,
1✔
2436
                                ChainNet:    s.cfg.ActiveNetParams.Net,
1✔
2437
                        }
1✔
2438

1✔
2439
                        err = s.ConnectToPeer(
1✔
2440
                                peerAddr, true,
1✔
2441
                                s.cfg.ConnectionTimeout,
1✔
2442
                        )
1✔
2443
                        if err != nil {
1✔
2444
                                startErr = fmt.Errorf("unable to connect to "+
×
2445
                                        "peer address provided as a config "+
×
2446
                                        "option: %v", err)
×
2447
                                return
×
2448
                        }
×
2449
                }
2450

2451
                // Subscribe to NodeAnnouncements that advertise new addresses
2452
                // our persistent peers.
2453
                if err := s.updatePersistentPeerAddrs(); err != nil {
1✔
2454
                        startErr = err
×
2455
                        return
×
2456
                }
×
2457

2458
                // With all the relevant sub-systems started, we'll now attempt
2459
                // to establish persistent connections to our direct channel
2460
                // collaborators within the network. Before doing so however,
2461
                // we'll prune our set of link nodes found within the database
2462
                // to ensure we don't reconnect to any nodes we no longer have
2463
                // open channels with.
2464
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
1✔
2465
                        startErr = err
×
2466
                        return
×
2467
                }
×
2468
                if err := s.establishPersistentConnections(); err != nil {
1✔
2469
                        startErr = err
×
2470
                        return
×
2471
                }
×
2472

2473
                // setSeedList is a helper function that turns multiple DNS seed
2474
                // server tuples from the command line or config file into the
2475
                // data structure we need and does a basic formal sanity check
2476
                // in the process.
2477
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
1✔
2478
                        if len(tuples) == 0 {
×
2479
                                return
×
2480
                        }
×
2481

2482
                        result := make([][2]string, len(tuples))
×
2483
                        for idx, tuple := range tuples {
×
2484
                                tuple = strings.TrimSpace(tuple)
×
2485
                                if len(tuple) == 0 {
×
2486
                                        return
×
2487
                                }
×
2488

2489
                                servers := strings.Split(tuple, ",")
×
2490
                                if len(servers) > 2 || len(servers) == 0 {
×
2491
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2492
                                                "seed tuple: %v", servers)
×
2493
                                        return
×
2494
                                }
×
2495

2496
                                copy(result[idx][:], servers)
×
2497
                        }
2498

2499
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2500
                }
2501

2502
                // Let users overwrite the DNS seed nodes. We only allow them
2503
                // for bitcoin mainnet/testnet/signet.
2504
                if s.cfg.Bitcoin.MainNet {
1✔
2505
                        setSeedList(
×
2506
                                s.cfg.Bitcoin.DNSSeeds,
×
2507
                                chainreg.BitcoinMainnetGenesis,
×
2508
                        )
×
2509
                }
×
2510
                if s.cfg.Bitcoin.TestNet3 {
1✔
2511
                        setSeedList(
×
2512
                                s.cfg.Bitcoin.DNSSeeds,
×
2513
                                chainreg.BitcoinTestnetGenesis,
×
2514
                        )
×
2515
                }
×
2516
                if s.cfg.Bitcoin.SigNet {
1✔
2517
                        setSeedList(
×
2518
                                s.cfg.Bitcoin.DNSSeeds,
×
2519
                                chainreg.BitcoinSignetGenesis,
×
2520
                        )
×
2521
                }
×
2522

2523
                // If network bootstrapping hasn't been disabled, then we'll
2524
                // configure the set of active bootstrappers, and launch a
2525
                // dedicated goroutine to maintain a set of persistent
2526
                // connections.
2527
                if shouldPeerBootstrap(s.cfg) {
1✔
2528
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2529
                        if err != nil {
×
2530
                                startErr = err
×
2531
                                return
×
2532
                        }
×
2533

2534
                        s.wg.Add(1)
×
2535
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2536
                } else {
1✔
2537
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
1✔
2538
                }
1✔
2539

2540
                // Start the blockbeat after all other subsystems have been
2541
                // started so they are ready to receive new blocks.
2542
                cleanup = cleanup.add(func() error {
1✔
2543
                        s.blockbeatDispatcher.Stop()
×
2544
                        return nil
×
2545
                })
×
2546
                if err := s.blockbeatDispatcher.Start(); err != nil {
1✔
2547
                        startErr = err
×
2548
                        return
×
2549
                }
×
2550

2551
                // Set the active flag now that we've completed the full
2552
                // startup.
2553
                atomic.StoreInt32(&s.active, 1)
1✔
2554
        })
2555

2556
        if startErr != nil {
1✔
2557
                cleanup.run()
×
2558
        }
×
2559
        return startErr
1✔
2560
}
2561

2562
// Stop gracefully shutsdown the main daemon server. This function will signal
2563
// any active goroutines, or helper objects to exit, then blocks until they've
2564
// all successfully exited. Additionally, any/all listeners are closed.
2565
// NOTE: This function is safe for concurrent access.
2566
func (s *server) Stop() error {
1✔
2567
        s.stop.Do(func() {
2✔
2568
                atomic.StoreInt32(&s.stopping, 1)
1✔
2569

1✔
2570
                close(s.quit)
1✔
2571

1✔
2572
                // Shutdown connMgr first to prevent conns during shutdown.
1✔
2573
                s.connMgr.Stop()
1✔
2574

1✔
2575
                // Stop dispatching blocks to other systems immediately.
1✔
2576
                s.blockbeatDispatcher.Stop()
1✔
2577

1✔
2578
                // Shutdown the wallet, funding manager, and the rpc server.
1✔
2579
                if err := s.chanStatusMgr.Stop(); err != nil {
1✔
2580
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2581
                }
×
2582
                if err := s.htlcSwitch.Stop(); err != nil {
1✔
2583
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2584
                }
×
2585
                if err := s.sphinx.Stop(); err != nil {
1✔
2586
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2587
                }
×
2588
                if err := s.invoices.Stop(); err != nil {
1✔
2589
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2590
                }
×
2591
                if err := s.interceptableSwitch.Stop(); err != nil {
1✔
2592
                        srvrLog.Warnf("failed to stop interceptable "+
×
2593
                                "switch: %v", err)
×
2594
                }
×
2595
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
1✔
2596
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2597
                                "modifier: %v", err)
×
2598
                }
×
2599
                if err := s.chanRouter.Stop(); err != nil {
1✔
2600
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2601
                }
×
2602
                if err := s.graphBuilder.Stop(); err != nil {
1✔
2603
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2604
                }
×
2605
                if err := s.chainArb.Stop(); err != nil {
1✔
2606
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2607
                }
×
2608
                if err := s.fundingMgr.Stop(); err != nil {
1✔
2609
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2610
                }
×
2611
                if err := s.breachArbitrator.Stop(); err != nil {
1✔
2612
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2613
                                err)
×
2614
                }
×
2615
                if err := s.utxoNursery.Stop(); err != nil {
1✔
2616
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2617
                }
×
2618
                if err := s.authGossiper.Stop(); err != nil {
1✔
2619
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2620
                }
×
2621
                if err := s.sweeper.Stop(); err != nil {
1✔
2622
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2623
                }
×
2624
                if err := s.txPublisher.Stop(); err != nil {
1✔
2625
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2626
                }
×
2627
                if err := s.channelNotifier.Stop(); err != nil {
1✔
2628
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2629
                }
×
2630
                if err := s.peerNotifier.Stop(); err != nil {
1✔
2631
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2632
                }
×
2633
                if err := s.htlcNotifier.Stop(); err != nil {
1✔
2634
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2635
                }
×
2636

2637
                // Update channel.backup file. Make sure to do it before
2638
                // stopping chanSubSwapper.
2639
                singles, err := chanbackup.FetchStaticChanBackups(
1✔
2640
                        s.chanStateDB, s.addrSource,
1✔
2641
                )
1✔
2642
                if err != nil {
1✔
2643
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2644
                                err)
×
2645
                } else {
1✔
2646
                        err := s.chanSubSwapper.ManualUpdate(singles)
1✔
2647
                        if err != nil {
2✔
2648
                                srvrLog.Warnf("Manual update of channel "+
1✔
2649
                                        "backup failed: %v", err)
1✔
2650
                        }
1✔
2651
                }
2652

2653
                if err := s.chanSubSwapper.Stop(); err != nil {
1✔
2654
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2655
                }
×
2656
                if err := s.cc.ChainNotifier.Stop(); err != nil {
1✔
2657
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2658
                }
×
2659
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
1✔
2660
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2661
                                err)
×
2662
                }
×
2663
                if err := s.chanEventStore.Stop(); err != nil {
1✔
2664
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2665
                                err)
×
2666
                }
×
2667
                s.missionController.StopStoreTickers()
1✔
2668

1✔
2669
                // Disconnect from each active peers to ensure that
1✔
2670
                // peerTerminationWatchers signal completion to each peer.
1✔
2671
                for _, peer := range s.Peers() {
2✔
2672
                        err := s.DisconnectPeer(peer.IdentityKey())
1✔
2673
                        if err != nil {
1✔
2674
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2675
                                        "received error: %v", peer.IdentityKey(),
×
2676
                                        err,
×
2677
                                )
×
2678
                        }
×
2679
                }
2680

2681
                // Now that all connections have been torn down, stop the tower
2682
                // client which will reliably flush all queued states to the
2683
                // tower. If this is halted for any reason, the force quit timer
2684
                // will kick in and abort to allow this method to return.
2685
                if s.towerClientMgr != nil {
2✔
2686
                        if err := s.towerClientMgr.Stop(); err != nil {
1✔
2687
                                srvrLog.Warnf("Unable to shut down tower "+
×
2688
                                        "client manager: %v", err)
×
2689
                        }
×
2690
                }
2691

2692
                if s.hostAnn != nil {
1✔
2693
                        if err := s.hostAnn.Stop(); err != nil {
×
2694
                                srvrLog.Warnf("unable to shut down host "+
×
2695
                                        "annoucner: %v", err)
×
2696
                        }
×
2697
                }
2698

2699
                if s.livenessMonitor != nil {
2✔
2700
                        if err := s.livenessMonitor.Stop(); err != nil {
1✔
2701
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2702
                                        "monitor: %v", err)
×
2703
                        }
×
2704
                }
2705

2706
                // Wait for all lingering goroutines to quit.
2707
                srvrLog.Debug("Waiting for server to shutdown...")
1✔
2708
                s.wg.Wait()
1✔
2709

1✔
2710
                srvrLog.Debug("Stopping buffer pools...")
1✔
2711
                s.sigPool.Stop()
1✔
2712
                s.writePool.Stop()
1✔
2713
                s.readPool.Stop()
1✔
2714
        })
2715

2716
        return nil
1✔
2717
}
2718

2719
// Stopped returns true if the server has been instructed to shutdown.
2720
// NOTE: This function is safe for concurrent access.
2721
func (s *server) Stopped() bool {
1✔
2722
        return atomic.LoadInt32(&s.stopping) != 0
1✔
2723
}
1✔
2724

2725
// configurePortForwarding attempts to set up port forwarding for the different
2726
// ports that the server will be listening on.
2727
//
2728
// NOTE: This should only be used when using some kind of NAT traversal to
2729
// automatically set up forwarding rules.
2730
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2731
        ip, err := s.natTraversal.ExternalIP()
×
2732
        if err != nil {
×
2733
                return nil, err
×
2734
        }
×
2735
        s.lastDetectedIP = ip
×
2736

×
2737
        externalIPs := make([]string, 0, len(ports))
×
2738
        for _, port := range ports {
×
2739
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2740
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2741
                        continue
×
2742
                }
2743

2744
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2745
                externalIPs = append(externalIPs, hostIP)
×
2746
        }
2747

2748
        return externalIPs, nil
×
2749
}
2750

2751
// removePortForwarding attempts to clear the forwarding rules for the different
2752
// ports the server is currently listening on.
2753
//
2754
// NOTE: This should only be used when using some kind of NAT traversal to
2755
// automatically set up forwarding rules.
2756
func (s *server) removePortForwarding() {
×
2757
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2758
        for _, port := range forwardedPorts {
×
2759
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2760
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2761
                                "port %d: %v", port, err)
×
2762
                }
×
2763
        }
2764
}
2765

2766
// watchExternalIP continuously checks for an updated external IP address every
2767
// 15 minutes. Once a new IP address has been detected, it will automatically
2768
// handle port forwarding rules and send updated node announcements to the
2769
// currently connected peers.
2770
//
2771
// NOTE: This MUST be run as a goroutine.
2772
func (s *server) watchExternalIP() {
×
2773
        defer s.wg.Done()
×
2774

×
2775
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2776
        // up by the server.
×
2777
        defer s.removePortForwarding()
×
2778

×
2779
        // Keep track of the external IPs set by the user to avoid replacing
×
2780
        // them when detecting a new IP.
×
2781
        ipsSetByUser := make(map[string]struct{})
×
2782
        for _, ip := range s.cfg.ExternalIPs {
×
2783
                ipsSetByUser[ip.String()] = struct{}{}
×
2784
        }
×
2785

2786
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2787

×
2788
        ticker := time.NewTicker(15 * time.Minute)
×
2789
        defer ticker.Stop()
×
2790
out:
×
2791
        for {
×
2792
                select {
×
2793
                case <-ticker.C:
×
2794
                        // We'll start off by making sure a new IP address has
×
2795
                        // been detected.
×
2796
                        ip, err := s.natTraversal.ExternalIP()
×
2797
                        if err != nil {
×
2798
                                srvrLog.Debugf("Unable to retrieve the "+
×
2799
                                        "external IP address: %v", err)
×
2800
                                continue
×
2801
                        }
2802

2803
                        // Periodically renew the NAT port forwarding.
2804
                        for _, port := range forwardedPorts {
×
2805
                                err := s.natTraversal.AddPortMapping(port)
×
2806
                                if err != nil {
×
2807
                                        srvrLog.Warnf("Unable to automatically "+
×
2808
                                                "re-create port forwarding using %s: %v",
×
2809
                                                s.natTraversal.Name(), err)
×
2810
                                } else {
×
2811
                                        srvrLog.Debugf("Automatically re-created "+
×
2812
                                                "forwarding for port %d using %s to "+
×
2813
                                                "advertise external IP",
×
2814
                                                port, s.natTraversal.Name())
×
2815
                                }
×
2816
                        }
2817

2818
                        if ip.Equal(s.lastDetectedIP) {
×
2819
                                continue
×
2820
                        }
2821

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

×
2824
                        // Next, we'll craft the new addresses that will be
×
2825
                        // included in the new node announcement and advertised
×
2826
                        // to the network. Each address will consist of the new
×
2827
                        // IP detected and one of the currently advertised
×
2828
                        // ports.
×
2829
                        var newAddrs []net.Addr
×
2830
                        for _, port := range forwardedPorts {
×
2831
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2832
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2833
                                if err != nil {
×
2834
                                        srvrLog.Debugf("Unable to resolve "+
×
2835
                                                "host %v: %v", addr, err)
×
2836
                                        continue
×
2837
                                }
2838

2839
                                newAddrs = append(newAddrs, addr)
×
2840
                        }
2841

2842
                        // Skip the update if we weren't able to resolve any of
2843
                        // the new addresses.
2844
                        if len(newAddrs) == 0 {
×
2845
                                srvrLog.Debug("Skipping node announcement " +
×
2846
                                        "update due to not being able to " +
×
2847
                                        "resolve any new addresses")
×
2848
                                continue
×
2849
                        }
2850

2851
                        // Now, we'll need to update the addresses in our node's
2852
                        // announcement in order to propagate the update
2853
                        // throughout the network. We'll only include addresses
2854
                        // that have a different IP from the previous one, as
2855
                        // the previous IP is no longer valid.
2856
                        currentNodeAnn := s.getNodeAnnouncement()
×
2857

×
2858
                        for _, addr := range currentNodeAnn.Addresses {
×
2859
                                host, _, err := net.SplitHostPort(addr.String())
×
2860
                                if err != nil {
×
2861
                                        srvrLog.Debugf("Unable to determine "+
×
2862
                                                "host from address %v: %v",
×
2863
                                                addr, err)
×
2864
                                        continue
×
2865
                                }
2866

2867
                                // We'll also make sure to include external IPs
2868
                                // set manually by the user.
2869
                                _, setByUser := ipsSetByUser[addr.String()]
×
2870
                                if setByUser || host != s.lastDetectedIP.String() {
×
2871
                                        newAddrs = append(newAddrs, addr)
×
2872
                                }
×
2873
                        }
2874

2875
                        // Then, we'll generate a new timestamped node
2876
                        // announcement with the updated addresses and broadcast
2877
                        // it to our peers.
2878
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2879
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2880
                        )
×
2881
                        if err != nil {
×
2882
                                srvrLog.Debugf("Unable to generate new node "+
×
2883
                                        "announcement: %v", err)
×
2884
                                continue
×
2885
                        }
2886

2887
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2888
                        if err != nil {
×
2889
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2890
                                        "announcement to peers: %v", err)
×
2891
                                continue
×
2892
                        }
2893

2894
                        // Finally, update the last IP seen to the current one.
2895
                        s.lastDetectedIP = ip
×
2896
                case <-s.quit:
×
2897
                        break out
×
2898
                }
2899
        }
2900
}
2901

2902
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2903
// based on the server, and currently active bootstrap mechanisms as defined
2904
// within the current configuration.
2905
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2906
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2907

×
2908
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2909

×
2910
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2911
        // this can be used by default if we've already partially seeded the
×
2912
        // network.
×
2913
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2914
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2915
        if err != nil {
×
2916
                return nil, err
×
2917
        }
×
2918
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2919

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

×
2925
                // If we have a set of DNS seeds for this chain, then we'll add
×
2926
                // it as an additional bootstrapping source.
×
2927
                if ok {
×
2928
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2929
                                "seeds: %v", dnsSeeds)
×
2930

×
2931
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2932
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2933
                        )
×
2934
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2935
                }
×
2936
        }
2937

2938
        return bootStrappers, nil
×
2939
}
2940

2941
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2942
// needs to ignore, which is made of three parts,
2943
//   - the node itself needs to be skipped as it doesn't make sense to connect
2944
//     to itself.
2945
//   - the peers that already have connections with, as in s.peersByPub.
2946
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2947
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2948
        s.mu.RLock()
×
2949
        defer s.mu.RUnlock()
×
2950

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

×
2953
        // We should ignore ourselves from bootstrapping.
×
2954
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2955
        ignore[selfKey] = struct{}{}
×
2956

×
2957
        // Ignore all connected peers.
×
2958
        for _, peer := range s.peersByPub {
×
2959
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2960
                ignore[nID] = struct{}{}
×
2961
        }
×
2962

2963
        // Ignore all persistent peers as they have a dedicated reconnecting
2964
        // process.
2965
        for pubKeyStr := range s.persistentPeers {
×
2966
                var nID autopilot.NodeID
×
2967
                copy(nID[:], []byte(pubKeyStr))
×
2968
                ignore[nID] = struct{}{}
×
2969
        }
×
2970

2971
        return ignore
×
2972
}
2973

2974
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2975
// and maintain a target minimum number of outbound connections. With this
2976
// invariant, we ensure that our node is connected to a diverse set of peers
2977
// and that nodes newly joining the network receive an up to date network view
2978
// as soon as possible.
2979
func (s *server) peerBootstrapper(numTargetPeers uint32,
2980
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2981

×
2982
        defer s.wg.Done()
×
2983

×
2984
        // Before we continue, init the ignore peers map.
×
2985
        ignoreList := s.createBootstrapIgnorePeers()
×
2986

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

×
2991
        // Once done, we'll attempt to maintain our target minimum number of
×
2992
        // peers.
×
2993
        //
×
2994
        // We'll use a 15 second backoff, and double the time every time an
×
2995
        // epoch fails up to a ceiling.
×
2996
        backOff := time.Second * 15
×
2997

×
2998
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2999
        // see if we've reached our minimum number of peers.
×
3000
        sampleTicker := time.NewTicker(backOff)
×
3001
        defer sampleTicker.Stop()
×
3002

×
3003
        // We'll use the number of attempts and errors to determine if we need
×
3004
        // to increase the time between discovery epochs.
×
3005
        var epochErrors uint32 // To be used atomically.
×
3006
        var epochAttempts uint32
×
3007

×
3008
        for {
×
3009
                select {
×
3010
                // The ticker has just woken us up, so we'll need to check if
3011
                // we need to attempt to connect our to any more peers.
3012
                case <-sampleTicker.C:
×
3013
                        // Obtain the current number of peers, so we can gauge
×
3014
                        // if we need to sample more peers or not.
×
3015
                        s.mu.RLock()
×
3016
                        numActivePeers := uint32(len(s.peersByPub))
×
3017
                        s.mu.RUnlock()
×
3018

×
3019
                        // If we have enough peers, then we can loop back
×
3020
                        // around to the next round as we're done here.
×
3021
                        if numActivePeers >= numTargetPeers {
×
3022
                                continue
×
3023
                        }
3024

3025
                        // If all of our attempts failed during this last back
3026
                        // off period, then will increase our backoff to 5
3027
                        // minute ceiling to avoid an excessive number of
3028
                        // queries
3029
                        //
3030
                        // TODO(roasbeef): add reverse policy too?
3031

3032
                        if epochAttempts > 0 &&
×
3033
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3034

×
3035
                                sampleTicker.Stop()
×
3036

×
3037
                                backOff *= 2
×
3038
                                if backOff > bootstrapBackOffCeiling {
×
3039
                                        backOff = bootstrapBackOffCeiling
×
3040
                                }
×
3041

3042
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3043
                                        "%v", backOff)
×
3044
                                sampleTicker = time.NewTicker(backOff)
×
3045
                                continue
×
3046
                        }
3047

3048
                        atomic.StoreUint32(&epochErrors, 0)
×
3049
                        epochAttempts = 0
×
3050

×
3051
                        // Since we know need more peers, we'll compute the
×
3052
                        // exact number we need to reach our threshold.
×
3053
                        numNeeded := numTargetPeers - numActivePeers
×
3054

×
3055
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3056
                                "peers", numNeeded)
×
3057

×
3058
                        // With the number of peers we need calculated, we'll
×
3059
                        // query the network bootstrappers to sample a set of
×
3060
                        // random addrs for us.
×
3061
                        //
×
3062
                        // Before we continue, get a copy of the ignore peers
×
3063
                        // map.
×
3064
                        ignoreList = s.createBootstrapIgnorePeers()
×
3065

×
3066
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3067
                                ignoreList, numNeeded*2, bootstrappers...,
×
3068
                        )
×
3069
                        if err != nil {
×
3070
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3071
                                        "peers: %v", err)
×
3072
                                continue
×
3073
                        }
3074

3075
                        // Finally, we'll launch a new goroutine for each
3076
                        // prospective peer candidates.
3077
                        for _, addr := range peerAddrs {
×
3078
                                epochAttempts++
×
3079

×
3080
                                go func(a *lnwire.NetAddress) {
×
3081
                                        // TODO(roasbeef): can do AS, subnet,
×
3082
                                        // country diversity, etc
×
3083
                                        errChan := make(chan error, 1)
×
3084
                                        s.connectToPeer(
×
3085
                                                a, errChan,
×
3086
                                                s.cfg.ConnectionTimeout,
×
3087
                                        )
×
3088
                                        select {
×
3089
                                        case err := <-errChan:
×
3090
                                                if err == nil {
×
3091
                                                        return
×
3092
                                                }
×
3093

3094
                                                srvrLog.Errorf("Unable to "+
×
3095
                                                        "connect to %v: %v",
×
3096
                                                        a, err)
×
3097
                                                atomic.AddUint32(&epochErrors, 1)
×
3098
                                        case <-s.quit:
×
3099
                                        }
3100
                                }(addr)
3101
                        }
3102
                case <-s.quit:
×
3103
                        return
×
3104
                }
3105
        }
3106
}
3107

3108
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3109
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3110
// query back off each time we encounter a failure.
3111
const bootstrapBackOffCeiling = time.Minute * 5
3112

3113
// initialPeerBootstrap attempts to continuously connect to peers on startup
3114
// until the target number of peers has been reached. This ensures that nodes
3115
// receive an up to date network view as soon as possible.
3116
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
3117
        numTargetPeers uint32,
3118
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3119

×
3120
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3121
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3122

×
3123
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3124
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3125
        var delaySignal <-chan time.Time
×
3126
        delayTime := time.Second * 2
×
3127

×
3128
        // As want to be more aggressive, we'll use a lower back off celling
×
3129
        // then the main peer bootstrap logic.
×
3130
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3131

×
3132
        for attempts := 0; ; attempts++ {
×
3133
                // Check if the server has been requested to shut down in order
×
3134
                // to prevent blocking.
×
3135
                if s.Stopped() {
×
3136
                        return
×
3137
                }
×
3138

3139
                // We can exit our aggressive initial peer bootstrapping stage
3140
                // if we've reached out target number of peers.
3141
                s.mu.RLock()
×
3142
                numActivePeers := uint32(len(s.peersByPub))
×
3143
                s.mu.RUnlock()
×
3144

×
3145
                if numActivePeers >= numTargetPeers {
×
3146
                        return
×
3147
                }
×
3148

3149
                if attempts > 0 {
×
3150
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3151
                                "bootstrap peers (attempt #%v)", delayTime,
×
3152
                                attempts)
×
3153

×
3154
                        // We've completed at least one iterating and haven't
×
3155
                        // finished, so we'll start to insert a delay period
×
3156
                        // between each attempt.
×
3157
                        delaySignal = time.After(delayTime)
×
3158
                        select {
×
3159
                        case <-delaySignal:
×
3160
                        case <-s.quit:
×
3161
                                return
×
3162
                        }
3163

3164
                        // After our delay, we'll double the time we wait up to
3165
                        // the max back off period.
3166
                        delayTime *= 2
×
3167
                        if delayTime > backOffCeiling {
×
3168
                                delayTime = backOffCeiling
×
3169
                        }
×
3170
                }
3171

3172
                // Otherwise, we'll request for the remaining number of peers
3173
                // in order to reach our target.
3174
                peersNeeded := numTargetPeers - numActivePeers
×
3175
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3176
                        ignore, peersNeeded, bootstrappers...,
×
3177
                )
×
3178
                if err != nil {
×
3179
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3180
                                "peers: %v", err)
×
3181
                        continue
×
3182
                }
3183

3184
                // Then, we'll attempt to establish a connection to the
3185
                // different peer addresses retrieved by our bootstrappers.
3186
                var wg sync.WaitGroup
×
3187
                for _, bootstrapAddr := range bootstrapAddrs {
×
3188
                        wg.Add(1)
×
3189
                        go func(addr *lnwire.NetAddress) {
×
3190
                                defer wg.Done()
×
3191

×
3192
                                errChan := make(chan error, 1)
×
3193
                                go s.connectToPeer(
×
3194
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3195
                                )
×
3196

×
3197
                                // We'll only allow this connection attempt to
×
3198
                                // take up to 3 seconds. This allows us to move
×
3199
                                // quickly by discarding peers that are slowing
×
3200
                                // us down.
×
3201
                                select {
×
3202
                                case err := <-errChan:
×
3203
                                        if err == nil {
×
3204
                                                return
×
3205
                                        }
×
3206
                                        srvrLog.Errorf("Unable to connect to "+
×
3207
                                                "%v: %v", addr, err)
×
3208
                                // TODO: tune timeout? 3 seconds might be *too*
3209
                                // aggressive but works well.
3210
                                case <-time.After(3 * time.Second):
×
3211
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3212
                                                "to not establishing a "+
×
3213
                                                "connection within 3 seconds",
×
3214
                                                addr)
×
3215
                                case <-s.quit:
×
3216
                                }
3217
                        }(bootstrapAddr)
3218
                }
3219

3220
                wg.Wait()
×
3221
        }
3222
}
3223

3224
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3225
// order to listen for inbound connections over Tor.
3226
func (s *server) createNewHiddenService() error {
×
3227
        // Determine the different ports the server is listening on. The onion
×
3228
        // service's virtual port will map to these ports and one will be picked
×
3229
        // at random when the onion service is being accessed.
×
3230
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3231
        for _, listenAddr := range s.listenAddrs {
×
3232
                port := listenAddr.(*net.TCPAddr).Port
×
3233
                listenPorts = append(listenPorts, port)
×
3234
        }
×
3235

3236
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3237
        if err != nil {
×
3238
                return err
×
3239
        }
×
3240

3241
        // Once the port mapping has been set, we can go ahead and automatically
3242
        // create our onion service. The service's private key will be saved to
3243
        // disk in order to regain access to this service when restarting `lnd`.
3244
        onionCfg := tor.AddOnionConfig{
×
3245
                VirtualPort: defaultPeerPort,
×
3246
                TargetPorts: listenPorts,
×
3247
                Store: tor.NewOnionFile(
×
3248
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3249
                        encrypter,
×
3250
                ),
×
3251
        }
×
3252

×
3253
        switch {
×
3254
        case s.cfg.Tor.V2:
×
3255
                onionCfg.Type = tor.V2
×
3256
        case s.cfg.Tor.V3:
×
3257
                onionCfg.Type = tor.V3
×
3258
        }
3259

3260
        addr, err := s.torController.AddOnion(onionCfg)
×
3261
        if err != nil {
×
3262
                return err
×
3263
        }
×
3264

3265
        // Now that the onion service has been created, we'll add the onion
3266
        // address it can be reached at to our list of advertised addresses.
3267
        newNodeAnn, err := s.genNodeAnnouncement(
×
3268
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3269
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3270
                },
×
3271
        )
3272
        if err != nil {
×
3273
                return fmt.Errorf("unable to generate new node "+
×
3274
                        "announcement: %v", err)
×
3275
        }
×
3276

3277
        // Finally, we'll update the on-disk version of our announcement so it
3278
        // will eventually propagate to nodes in the network.
3279
        selfNode := &models.LightningNode{
×
3280
                HaveNodeAnnouncement: true,
×
3281
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3282
                Addresses:            newNodeAnn.Addresses,
×
3283
                Alias:                newNodeAnn.Alias.String(),
×
3284
                Features: lnwire.NewFeatureVector(
×
3285
                        newNodeAnn.Features, lnwire.Features,
×
3286
                ),
×
3287
                Color:        newNodeAnn.RGBColor,
×
3288
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3289
        }
×
3290
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3291
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3292
                return fmt.Errorf("can't set self node: %w", err)
×
3293
        }
×
3294

3295
        return nil
×
3296
}
3297

3298
// findChannel finds a channel given a public key and ChannelID. It is an
3299
// optimization that is quicker than seeking for a channel given only the
3300
// ChannelID.
3301
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3302
        *channeldb.OpenChannel, error) {
1✔
3303

1✔
3304
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
1✔
3305
        if err != nil {
1✔
3306
                return nil, err
×
3307
        }
×
3308

3309
        for _, channel := range nodeChans {
2✔
3310
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
2✔
3311
                        return channel, nil
1✔
3312
                }
1✔
3313
        }
3314

3315
        return nil, fmt.Errorf("unable to find channel")
1✔
3316
}
3317

3318
// getNodeAnnouncement fetches the current, fully signed node announcement.
3319
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
1✔
3320
        s.mu.Lock()
1✔
3321
        defer s.mu.Unlock()
1✔
3322

1✔
3323
        return *s.currentNodeAnn
1✔
3324
}
1✔
3325

3326
// genNodeAnnouncement generates and returns the current fully signed node
3327
// announcement. The time stamp of the announcement will be updated in order
3328
// to ensure it propagates through the network.
3329
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3330
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
1✔
3331

1✔
3332
        s.mu.Lock()
1✔
3333
        defer s.mu.Unlock()
1✔
3334

1✔
3335
        // First, try to update our feature manager with the updated set of
1✔
3336
        // features.
1✔
3337
        if features != nil {
2✔
3338
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
1✔
3339
                        feature.SetNodeAnn: features,
1✔
3340
                }
1✔
3341
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
1✔
3342
                if err != nil {
2✔
3343
                        return lnwire.NodeAnnouncement{}, err
1✔
3344
                }
1✔
3345

3346
                // If we could successfully update our feature manager, add
3347
                // an update modifier to include these new features to our
3348
                // set.
3349
                modifiers = append(
1✔
3350
                        modifiers, netann.NodeAnnSetFeatures(features),
1✔
3351
                )
1✔
3352
        }
3353

3354
        // Always update the timestamp when refreshing to ensure the update
3355
        // propagates.
3356
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
1✔
3357

1✔
3358
        // Apply the requested changes to the node announcement.
1✔
3359
        for _, modifier := range modifiers {
2✔
3360
                modifier(s.currentNodeAnn)
1✔
3361
        }
1✔
3362

3363
        // Sign a new update after applying all of the passed modifiers.
3364
        err := netann.SignNodeAnnouncement(
1✔
3365
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
1✔
3366
        )
1✔
3367
        if err != nil {
1✔
3368
                return lnwire.NodeAnnouncement{}, err
×
3369
        }
×
3370

3371
        return *s.currentNodeAnn, nil
1✔
3372
}
3373

3374
// updateAndBroadcastSelfNode generates a new node announcement
3375
// applying the giving modifiers and updating the time stamp
3376
// to ensure it propagates through the network. Then it broadcasts
3377
// it to the network.
3378
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
3379
        modifiers ...netann.NodeAnnModifier) error {
1✔
3380

1✔
3381
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
1✔
3382
        if err != nil {
2✔
3383
                return fmt.Errorf("unable to generate new node "+
1✔
3384
                        "announcement: %v", err)
1✔
3385
        }
1✔
3386

3387
        // Update the on-disk version of our announcement.
3388
        // Load and modify self node istead of creating anew instance so we
3389
        // don't risk overwriting any existing values.
3390
        selfNode, err := s.graphDB.SourceNode()
1✔
3391
        if err != nil {
1✔
3392
                return fmt.Errorf("unable to get current source node: %w", err)
×
3393
        }
×
3394

3395
        selfNode.HaveNodeAnnouncement = true
1✔
3396
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
1✔
3397
        selfNode.Addresses = newNodeAnn.Addresses
1✔
3398
        selfNode.Alias = newNodeAnn.Alias.String()
1✔
3399
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
1✔
3400
        selfNode.Color = newNodeAnn.RGBColor
1✔
3401
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
1✔
3402

1✔
3403
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
1✔
3404

1✔
3405
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
1✔
3406
                return fmt.Errorf("can't set self node: %w", err)
×
3407
        }
×
3408

3409
        // Finally, propagate it to the nodes in the network.
3410
        err = s.BroadcastMessage(nil, &newNodeAnn)
1✔
3411
        if err != nil {
1✔
3412
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3413
                        "announcement to peers: %v", err)
×
3414
                return err
×
3415
        }
×
3416

3417
        return nil
1✔
3418
}
3419

3420
type nodeAddresses struct {
3421
        pubKey    *btcec.PublicKey
3422
        addresses []net.Addr
3423
}
3424

3425
// establishPersistentConnections attempts to establish persistent connections
3426
// to all our direct channel collaborators. In order to promote liveness of our
3427
// active channels, we instruct the connection manager to attempt to establish
3428
// and maintain persistent connections to all our direct channel counterparties.
3429
func (s *server) establishPersistentConnections() error {
1✔
3430
        // nodeAddrsMap stores the combination of node public keys and addresses
1✔
3431
        // that we'll attempt to reconnect to. PubKey strings are used as keys
1✔
3432
        // since other PubKey forms can't be compared.
1✔
3433
        nodeAddrsMap := map[string]*nodeAddresses{}
1✔
3434

1✔
3435
        // Iterate through the list of LinkNodes to find addresses we should
1✔
3436
        // attempt to connect to based on our set of previous connections. Set
1✔
3437
        // the reconnection port to the default peer port.
1✔
3438
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
1✔
3439
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
1✔
3440
                return err
×
3441
        }
×
3442
        for _, node := range linkNodes {
2✔
3443
                pubStr := string(node.IdentityPub.SerializeCompressed())
1✔
3444
                nodeAddrs := &nodeAddresses{
1✔
3445
                        pubKey:    node.IdentityPub,
1✔
3446
                        addresses: node.Addresses,
1✔
3447
                }
1✔
3448
                nodeAddrsMap[pubStr] = nodeAddrs
1✔
3449
        }
1✔
3450

3451
        // After checking our previous connections for addresses to connect to,
3452
        // iterate through the nodes in our channel graph to find addresses
3453
        // that have been added via NodeAnnouncement messages.
3454
        sourceNode, err := s.graphDB.SourceNode()
1✔
3455
        if err != nil {
1✔
3456
                return err
×
3457
        }
×
3458

3459
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3460
        // each of the nodes.
3461
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
1✔
3462
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
1✔
3463
                tx kvdb.RTx,
1✔
3464
                chanInfo *models.ChannelEdgeInfo,
1✔
3465
                policy, _ *models.ChannelEdgePolicy) error {
2✔
3466

1✔
3467
                // If the remote party has announced the channel to us, but we
1✔
3468
                // haven't yet, then we won't have a policy. However, we don't
1✔
3469
                // need this to connect to the peer, so we'll log it and move on.
1✔
3470
                if policy == nil {
1✔
3471
                        srvrLog.Warnf("No channel policy found for "+
×
3472
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3473
                }
×
3474

3475
                // We'll now fetch the peer opposite from us within this
3476
                // channel so we can queue up a direct connection to them.
3477
                channelPeer, err := s.graphDB.FetchOtherNode(
1✔
3478
                        tx, chanInfo, selfPub,
1✔
3479
                )
1✔
3480
                if err != nil {
1✔
3481
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3482
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3483
                                err)
×
3484
                }
×
3485

3486
                pubStr := string(channelPeer.PubKeyBytes[:])
1✔
3487

1✔
3488
                // Add all unique addresses from channel
1✔
3489
                // graph/NodeAnnouncements to the list of addresses we'll
1✔
3490
                // connect to for this peer.
1✔
3491
                addrSet := make(map[string]net.Addr)
1✔
3492
                for _, addr := range channelPeer.Addresses {
2✔
3493
                        switch addr.(type) {
1✔
3494
                        case *net.TCPAddr:
1✔
3495
                                addrSet[addr.String()] = addr
1✔
3496

3497
                        // We'll only attempt to connect to Tor addresses if Tor
3498
                        // outbound support is enabled.
3499
                        case *tor.OnionAddr:
×
3500
                                if s.cfg.Tor.Active {
×
3501
                                        addrSet[addr.String()] = addr
×
3502
                                }
×
3503
                        }
3504
                }
3505

3506
                // If this peer is also recorded as a link node, we'll add any
3507
                // additional addresses that have not already been selected.
3508
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
1✔
3509
                if ok {
2✔
3510
                        for _, lnAddress := range linkNodeAddrs.addresses {
2✔
3511
                                switch lnAddress.(type) {
1✔
3512
                                case *net.TCPAddr:
1✔
3513
                                        addrSet[lnAddress.String()] = lnAddress
1✔
3514

3515
                                // We'll only attempt to connect to Tor
3516
                                // addresses if Tor outbound support is enabled.
3517
                                case *tor.OnionAddr:
×
3518
                                        if s.cfg.Tor.Active {
×
3519
                                                addrSet[lnAddress.String()] = lnAddress
×
3520
                                        }
×
3521
                                }
3522
                        }
3523
                }
3524

3525
                // Construct a slice of the deduped addresses.
3526
                var addrs []net.Addr
1✔
3527
                for _, addr := range addrSet {
2✔
3528
                        addrs = append(addrs, addr)
1✔
3529
                }
1✔
3530

3531
                n := &nodeAddresses{
1✔
3532
                        addresses: addrs,
1✔
3533
                }
1✔
3534
                n.pubKey, err = channelPeer.PubKey()
1✔
3535
                if err != nil {
1✔
3536
                        return err
×
3537
                }
×
3538

3539
                nodeAddrsMap[pubStr] = n
1✔
3540
                return nil
1✔
3541
        })
3542
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
1✔
3543
                return err
×
3544
        }
×
3545

3546
        srvrLog.Debugf("Establishing %v persistent connections on start",
1✔
3547
                len(nodeAddrsMap))
1✔
3548

1✔
3549
        // Acquire and hold server lock until all persistent connection requests
1✔
3550
        // have been recorded and sent to the connection manager.
1✔
3551
        s.mu.Lock()
1✔
3552
        defer s.mu.Unlock()
1✔
3553

1✔
3554
        // Iterate through the combined list of addresses from prior links and
1✔
3555
        // node announcements and attempt to reconnect to each node.
1✔
3556
        var numOutboundConns int
1✔
3557
        for pubStr, nodeAddr := range nodeAddrsMap {
2✔
3558
                // Add this peer to the set of peers we should maintain a
1✔
3559
                // persistent connection with. We set the value to false to
1✔
3560
                // indicate that we should not continue to reconnect if the
1✔
3561
                // number of channels returns to zero, since this peer has not
1✔
3562
                // been requested as perm by the user.
1✔
3563
                s.persistentPeers[pubStr] = false
1✔
3564
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
2✔
3565
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
1✔
3566
                }
1✔
3567

3568
                for _, address := range nodeAddr.addresses {
2✔
3569
                        // Create a wrapper address which couples the IP and
1✔
3570
                        // the pubkey so the brontide authenticated connection
1✔
3571
                        // can be established.
1✔
3572
                        lnAddr := &lnwire.NetAddress{
1✔
3573
                                IdentityKey: nodeAddr.pubKey,
1✔
3574
                                Address:     address,
1✔
3575
                        }
1✔
3576

1✔
3577
                        s.persistentPeerAddrs[pubStr] = append(
1✔
3578
                                s.persistentPeerAddrs[pubStr], lnAddr)
1✔
3579
                }
1✔
3580

3581
                // We'll connect to the first 10 peers immediately, then
3582
                // randomly stagger any remaining connections if the
3583
                // stagger initial reconnect flag is set. This ensures
3584
                // that mobile nodes or nodes with a small number of
3585
                // channels obtain connectivity quickly, but larger
3586
                // nodes are able to disperse the costs of connecting to
3587
                // all peers at once.
3588
                if numOutboundConns < numInstantInitReconnect ||
1✔
3589
                        !s.cfg.StaggerInitialReconnect {
2✔
3590

1✔
3591
                        go s.connectToPersistentPeer(pubStr)
1✔
3592
                } else {
1✔
3593
                        go s.delayInitialReconnect(pubStr)
×
3594
                }
×
3595

3596
                numOutboundConns++
1✔
3597
        }
3598

3599
        return nil
1✔
3600
}
3601

3602
// delayInitialReconnect will attempt a reconnection to the given peer after
3603
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3604
//
3605
// NOTE: This method MUST be run as a goroutine.
3606
func (s *server) delayInitialReconnect(pubStr string) {
×
3607
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3608
        select {
×
3609
        case <-time.After(delay):
×
3610
                s.connectToPersistentPeer(pubStr)
×
3611
        case <-s.quit:
×
3612
        }
3613
}
3614

3615
// prunePersistentPeerConnection removes all internal state related to
3616
// persistent connections to a peer within the server. This is used to avoid
3617
// persistent connection retries to peers we do not have any open channels with.
3618
func (s *server) prunePersistentPeerConnection(compressedPubKey [33]byte) {
1✔
3619
        pubKeyStr := string(compressedPubKey[:])
1✔
3620

1✔
3621
        s.mu.Lock()
1✔
3622
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
2✔
3623
                delete(s.persistentPeers, pubKeyStr)
1✔
3624
                delete(s.persistentPeersBackoff, pubKeyStr)
1✔
3625
                delete(s.persistentPeerAddrs, pubKeyStr)
1✔
3626
                s.cancelConnReqs(pubKeyStr, nil)
1✔
3627
                s.mu.Unlock()
1✔
3628

1✔
3629
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
1✔
3630
                        "peer has no open channels", compressedPubKey)
1✔
3631

1✔
3632
                return
1✔
3633
        }
1✔
3634
        s.mu.Unlock()
1✔
3635
}
3636

3637
// BroadcastMessage sends a request to the server to broadcast a set of
3638
// messages to all peers other than the one specified by the `skips` parameter.
3639
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3640
// the target peers.
3641
//
3642
// NOTE: This function is safe for concurrent access.
3643
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3644
        msgs ...lnwire.Message) error {
1✔
3645

1✔
3646
        // Filter out peers found in the skips map. We synchronize access to
1✔
3647
        // peersByPub throughout this process to ensure we deliver messages to
1✔
3648
        // exact set of peers present at the time of invocation.
1✔
3649
        s.mu.RLock()
1✔
3650
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
1✔
3651
        for pubStr, sPeer := range s.peersByPub {
2✔
3652
                if skips != nil {
2✔
3653
                        if _, ok := skips[sPeer.PubKey()]; ok {
2✔
3654
                                srvrLog.Tracef("Skipping %x in broadcast with "+
1✔
3655
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
1✔
3656
                                continue
1✔
3657
                        }
3658
                }
3659

3660
                peers = append(peers, sPeer)
1✔
3661
        }
3662
        s.mu.RUnlock()
1✔
3663

1✔
3664
        // Iterate over all known peers, dispatching a go routine to enqueue
1✔
3665
        // all messages to each of peers.
1✔
3666
        var wg sync.WaitGroup
1✔
3667
        for _, sPeer := range peers {
2✔
3668
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
1✔
3669
                        sPeer.PubKey())
1✔
3670

1✔
3671
                // Dispatch a go routine to enqueue all messages to this peer.
1✔
3672
                wg.Add(1)
1✔
3673
                s.wg.Add(1)
1✔
3674
                go func(p lnpeer.Peer) {
2✔
3675
                        defer s.wg.Done()
1✔
3676
                        defer wg.Done()
1✔
3677

1✔
3678
                        p.SendMessageLazy(false, msgs...)
1✔
3679
                }(sPeer)
1✔
3680
        }
3681

3682
        // Wait for all messages to have been dispatched before returning to
3683
        // caller.
3684
        wg.Wait()
1✔
3685

1✔
3686
        return nil
1✔
3687
}
3688

3689
// NotifyWhenOnline can be called by other subsystems to get notified when a
3690
// particular peer comes online. The peer itself is sent across the peerChan.
3691
//
3692
// NOTE: This function is safe for concurrent access.
3693
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3694
        peerChan chan<- lnpeer.Peer) {
1✔
3695

1✔
3696
        s.mu.Lock()
1✔
3697

1✔
3698
        // Compute the target peer's identifier.
1✔
3699
        pubStr := string(peerKey[:])
1✔
3700

1✔
3701
        // Check if peer is connected.
1✔
3702
        peer, ok := s.peersByPub[pubStr]
1✔
3703
        if ok {
2✔
3704
                // Unlock here so that the mutex isn't held while we are
1✔
3705
                // waiting for the peer to become active.
1✔
3706
                s.mu.Unlock()
1✔
3707

1✔
3708
                // Wait until the peer signals that it is actually active
1✔
3709
                // rather than only in the server's maps.
1✔
3710
                select {
1✔
3711
                case <-peer.ActiveSignal():
1✔
3712
                case <-peer.QuitSignal():
×
3713
                        // The peer quit, so we'll add the channel to the slice
×
3714
                        // and return.
×
3715
                        s.mu.Lock()
×
3716
                        s.peerConnectedListeners[pubStr] = append(
×
3717
                                s.peerConnectedListeners[pubStr], peerChan,
×
3718
                        )
×
3719
                        s.mu.Unlock()
×
3720
                        return
×
3721
                }
3722

3723
                // Connected, can return early.
3724
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
1✔
3725

1✔
3726
                select {
1✔
3727
                case peerChan <- peer:
1✔
3728
                case <-s.quit:
×
3729
                }
3730

3731
                return
1✔
3732
        }
3733

3734
        // Not connected, store this listener such that it can be notified when
3735
        // the peer comes online.
3736
        s.peerConnectedListeners[pubStr] = append(
1✔
3737
                s.peerConnectedListeners[pubStr], peerChan,
1✔
3738
        )
1✔
3739
        s.mu.Unlock()
1✔
3740
}
3741

3742
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3743
// the given public key has been disconnected. The notification is signaled by
3744
// closing the channel returned.
3745
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
1✔
3746
        s.mu.Lock()
1✔
3747
        defer s.mu.Unlock()
1✔
3748

1✔
3749
        c := make(chan struct{})
1✔
3750

1✔
3751
        // If the peer is already offline, we can immediately trigger the
1✔
3752
        // notification.
1✔
3753
        peerPubKeyStr := string(peerPubKey[:])
1✔
3754
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
1✔
3755
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3756
                close(c)
×
3757
                return c
×
3758
        }
×
3759

3760
        // Otherwise, the peer is online, so we'll keep track of the channel to
3761
        // trigger the notification once the server detects the peer
3762
        // disconnects.
3763
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
1✔
3764
                s.peerDisconnectedListeners[peerPubKeyStr], c,
1✔
3765
        )
1✔
3766

1✔
3767
        return c
1✔
3768
}
3769

3770
// FindPeer will return the peer that corresponds to the passed in public key.
3771
// This function is used by the funding manager, allowing it to update the
3772
// daemon's local representation of the remote peer.
3773
//
3774
// NOTE: This function is safe for concurrent access.
3775
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
1✔
3776
        s.mu.RLock()
1✔
3777
        defer s.mu.RUnlock()
1✔
3778

1✔
3779
        pubStr := string(peerKey.SerializeCompressed())
1✔
3780

1✔
3781
        return s.findPeerByPubStr(pubStr)
1✔
3782
}
1✔
3783

3784
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3785
// which should be a string representation of the peer's serialized, compressed
3786
// public key.
3787
//
3788
// NOTE: This function is safe for concurrent access.
3789
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
1✔
3790
        s.mu.RLock()
1✔
3791
        defer s.mu.RUnlock()
1✔
3792

1✔
3793
        return s.findPeerByPubStr(pubStr)
1✔
3794
}
1✔
3795

3796
// findPeerByPubStr is an internal method that retrieves the specified peer from
3797
// the server's internal state using.
3798
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
1✔
3799
        peer, ok := s.peersByPub[pubStr]
1✔
3800
        if !ok {
2✔
3801
                return nil, ErrPeerNotConnected
1✔
3802
        }
1✔
3803

3804
        return peer, nil
1✔
3805
}
3806

3807
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3808
// exponential backoff. If no previous backoff was known, the default is
3809
// returned.
3810
func (s *server) nextPeerBackoff(pubStr string,
3811
        startTime time.Time) time.Duration {
1✔
3812

1✔
3813
        // Now, determine the appropriate backoff to use for the retry.
1✔
3814
        backoff, ok := s.persistentPeersBackoff[pubStr]
1✔
3815
        if !ok {
2✔
3816
                // If an existing backoff was unknown, use the default.
1✔
3817
                return s.cfg.MinBackoff
1✔
3818
        }
1✔
3819

3820
        // If the peer failed to start properly, we'll just use the previous
3821
        // backoff to compute the subsequent randomized exponential backoff
3822
        // duration. This will roughly double on average.
3823
        if startTime.IsZero() {
1✔
3824
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3825
        }
×
3826

3827
        // The peer succeeded in starting. If the connection didn't last long
3828
        // enough to be considered stable, we'll continue to back off retries
3829
        // with this peer.
3830
        connDuration := time.Since(startTime)
1✔
3831
        if connDuration < defaultStableConnDuration {
2✔
3832
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
1✔
3833
        }
1✔
3834

3835
        // The peer succeed in starting and this was stable peer, so we'll
3836
        // reduce the timeout duration by the length of the connection after
3837
        // applying randomized exponential backoff. We'll only apply this in the
3838
        // case that:
3839
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3840
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3841
        if relaxedBackoff > s.cfg.MinBackoff {
×
3842
                return relaxedBackoff
×
3843
        }
×
3844

3845
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3846
        // the stable connection lasted much longer than our previous backoff.
3847
        // To reward such good behavior, we'll reconnect after the default
3848
        // timeout.
3849
        return s.cfg.MinBackoff
×
3850
}
3851

3852
// shouldDropLocalConnection determines if our local connection to a remote peer
3853
// should be dropped in the case of concurrent connection establishment. In
3854
// order to deterministically decide which connection should be dropped, we'll
3855
// utilize the ordering of the local and remote public key. If we didn't use
3856
// such a tie breaker, then we risk _both_ connections erroneously being
3857
// dropped.
3858
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3859
        localPubBytes := local.SerializeCompressed()
×
3860
        remotePubPbytes := remote.SerializeCompressed()
×
3861

×
3862
        // The connection that comes from the node with a "smaller" pubkey
×
3863
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3864
        // should drop our established connection.
×
3865
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3866
}
×
3867

3868
// InboundPeerConnected initializes a new peer in response to a new inbound
3869
// connection.
3870
//
3871
// NOTE: This function is safe for concurrent access.
3872
func (s *server) InboundPeerConnected(conn net.Conn) {
1✔
3873
        // Exit early if we have already been instructed to shutdown, this
1✔
3874
        // prevents any delayed callbacks from accidentally registering peers.
1✔
3875
        if s.Stopped() {
1✔
3876
                return
×
3877
        }
×
3878

3879
        nodePub := conn.(*brontide.Conn).RemotePub()
1✔
3880
        pubSer := nodePub.SerializeCompressed()
1✔
3881
        pubStr := string(pubSer)
1✔
3882

1✔
3883
        var pubBytes [33]byte
1✔
3884
        copy(pubBytes[:], pubSer)
1✔
3885

1✔
3886
        s.mu.Lock()
1✔
3887
        defer s.mu.Unlock()
1✔
3888

1✔
3889
        // If the remote node's public key is banned, drop the connection.
1✔
3890
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
1✔
3891
        if dcErr != nil {
1✔
3892
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3893
                        "peer: %v", dcErr)
×
3894
                conn.Close()
×
3895

×
3896
                return
×
3897
        }
×
3898

3899
        if shouldDc {
1✔
3900
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3901
                        "banned.", pubSer)
×
3902

×
3903
                conn.Close()
×
3904

×
3905
                return
×
3906
        }
×
3907

3908
        // If we already have an outbound connection to this peer, then ignore
3909
        // this new connection.
3910
        if p, ok := s.outboundPeers[pubStr]; ok {
2✔
3911
                srvrLog.Debugf("Already have outbound connection for %v, "+
1✔
3912
                        "ignoring inbound connection from local=%v, remote=%v",
1✔
3913
                        p, conn.LocalAddr(), conn.RemoteAddr())
1✔
3914

1✔
3915
                conn.Close()
1✔
3916
                return
1✔
3917
        }
1✔
3918

3919
        // If we already have a valid connection that is scheduled to take
3920
        // precedence once the prior peer has finished disconnecting, we'll
3921
        // ignore this connection.
3922
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
1✔
3923
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3924
                        "scheduled", conn.RemoteAddr(), p)
×
3925
                conn.Close()
×
3926
                return
×
3927
        }
×
3928

3929
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
1✔
3930

1✔
3931
        // Check to see if we already have a connection with this peer. If so,
1✔
3932
        // we may need to drop our existing connection. This prevents us from
1✔
3933
        // having duplicate connections to the same peer. We forgo adding a
1✔
3934
        // default case as we expect these to be the only error values returned
1✔
3935
        // from findPeerByPubStr.
1✔
3936
        connectedPeer, err := s.findPeerByPubStr(pubStr)
1✔
3937
        switch err {
1✔
3938
        case ErrPeerNotConnected:
1✔
3939
                // We were unable to locate an existing connection with the
1✔
3940
                // target peer, proceed to connect.
1✔
3941
                s.cancelConnReqs(pubStr, nil)
1✔
3942
                s.peerConnected(conn, nil, true)
1✔
3943

3944
        case nil:
×
3945
                // We already have a connection with the incoming peer. If the
×
3946
                // connection we've already established should be kept and is
×
3947
                // not of the same type of the new connection (inbound), then
×
3948
                // we'll close out the new connection s.t there's only a single
×
3949
                // connection between us.
×
3950
                localPub := s.identityECDH.PubKey()
×
3951
                if !connectedPeer.Inbound() &&
×
3952
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3953

×
3954
                        srvrLog.Warnf("Received inbound connection from "+
×
3955
                                "peer %v, but already have outbound "+
×
3956
                                "connection, dropping conn", connectedPeer)
×
3957
                        conn.Close()
×
3958
                        return
×
3959
                }
×
3960

3961
                // Otherwise, if we should drop the connection, then we'll
3962
                // disconnect our already connected peer.
3963
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3964
                        connectedPeer)
×
3965

×
3966
                s.cancelConnReqs(pubStr, nil)
×
3967

×
3968
                // Remove the current peer from the server's internal state and
×
3969
                // signal that the peer termination watcher does not need to
×
3970
                // execute for this peer.
×
3971
                s.removePeer(connectedPeer)
×
3972
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3973
                s.scheduledPeerConnection[pubStr] = func() {
×
3974
                        s.peerConnected(conn, nil, true)
×
3975
                }
×
3976
        }
3977
}
3978

3979
// OutboundPeerConnected initializes a new peer in response to a new outbound
3980
// connection.
3981
// NOTE: This function is safe for concurrent access.
3982
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
1✔
3983
        // Exit early if we have already been instructed to shutdown, this
1✔
3984
        // prevents any delayed callbacks from accidentally registering peers.
1✔
3985
        if s.Stopped() {
1✔
3986
                return
×
3987
        }
×
3988

3989
        nodePub := conn.(*brontide.Conn).RemotePub()
1✔
3990
        pubSer := nodePub.SerializeCompressed()
1✔
3991
        pubStr := string(pubSer)
1✔
3992

1✔
3993
        var pubBytes [33]byte
1✔
3994
        copy(pubBytes[:], pubSer)
1✔
3995

1✔
3996
        s.mu.Lock()
1✔
3997
        defer s.mu.Unlock()
1✔
3998

1✔
3999
        // If the remote node's public key is banned, drop the connection.
1✔
4000
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
1✔
4001
        if dcErr != nil {
1✔
4002
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
4003
                        "peer: %v", dcErr)
×
4004
                conn.Close()
×
4005

×
4006
                return
×
4007
        }
×
4008

4009
        if shouldDc {
1✔
4010
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
4011
                        "banned.", pubSer)
×
4012

×
4013
                if connReq != nil {
×
4014
                        s.connMgr.Remove(connReq.ID())
×
4015
                }
×
4016

4017
                conn.Close()
×
4018

×
4019
                return
×
4020
        }
4021

4022
        // If we already have an inbound connection to this peer, then ignore
4023
        // this new connection.
4024
        if p, ok := s.inboundPeers[pubStr]; ok {
2✔
4025
                srvrLog.Debugf("Already have inbound connection for %v, "+
1✔
4026
                        "ignoring outbound connection from local=%v, remote=%v",
1✔
4027
                        p, conn.LocalAddr(), conn.RemoteAddr())
1✔
4028

1✔
4029
                if connReq != nil {
2✔
4030
                        s.connMgr.Remove(connReq.ID())
1✔
4031
                }
1✔
4032
                conn.Close()
1✔
4033
                return
1✔
4034
        }
4035
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
1✔
4036
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4037
                s.connMgr.Remove(connReq.ID())
×
4038
                conn.Close()
×
4039
                return
×
4040
        }
×
4041

4042
        // If we already have a valid connection that is scheduled to take
4043
        // precedence once the prior peer has finished disconnecting, we'll
4044
        // ignore this connection.
4045
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
1✔
4046
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
4047

×
4048
                if connReq != nil {
×
4049
                        s.connMgr.Remove(connReq.ID())
×
4050
                }
×
4051

4052
                conn.Close()
×
4053
                return
×
4054
        }
4055

4056
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
1✔
4057
                conn.RemoteAddr())
1✔
4058

1✔
4059
        if connReq != nil {
2✔
4060
                // A successful connection was returned by the connmgr.
1✔
4061
                // Immediately cancel all pending requests, excluding the
1✔
4062
                // outbound connection we just established.
1✔
4063
                ignore := connReq.ID()
1✔
4064
                s.cancelConnReqs(pubStr, &ignore)
1✔
4065
        } else {
2✔
4066
                // This was a successful connection made by some other
1✔
4067
                // subsystem. Remove all requests being managed by the connmgr.
1✔
4068
                s.cancelConnReqs(pubStr, nil)
1✔
4069
        }
1✔
4070

4071
        // If we already have a connection with this peer, decide whether or not
4072
        // we need to drop the stale connection. We forgo adding a default case
4073
        // as we expect these to be the only error values returned from
4074
        // findPeerByPubStr.
4075
        connectedPeer, err := s.findPeerByPubStr(pubStr)
1✔
4076
        switch err {
1✔
4077
        case ErrPeerNotConnected:
1✔
4078
                // We were unable to locate an existing connection with the
1✔
4079
                // target peer, proceed to connect.
1✔
4080
                s.peerConnected(conn, connReq, false)
1✔
4081

4082
        case nil:
×
4083
                // We already have a connection with the incoming peer. If the
×
4084
                // connection we've already established should be kept and is
×
4085
                // not of the same type of the new connection (outbound), then
×
4086
                // we'll close out the new connection s.t there's only a single
×
4087
                // connection between us.
×
4088
                localPub := s.identityECDH.PubKey()
×
4089
                if connectedPeer.Inbound() &&
×
4090
                        shouldDropLocalConnection(localPub, nodePub) {
×
4091

×
4092
                        srvrLog.Warnf("Established outbound connection to "+
×
4093
                                "peer %v, but already have inbound "+
×
4094
                                "connection, dropping conn", connectedPeer)
×
4095
                        if connReq != nil {
×
4096
                                s.connMgr.Remove(connReq.ID())
×
4097
                        }
×
4098
                        conn.Close()
×
4099
                        return
×
4100
                }
4101

4102
                // Otherwise, _their_ connection should be dropped. So we'll
4103
                // disconnect the peer and send the now obsolete peer to the
4104
                // server for garbage collection.
4105
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4106
                        connectedPeer)
×
4107

×
4108
                // Remove the current peer from the server's internal state and
×
4109
                // signal that the peer termination watcher does not need to
×
4110
                // execute for this peer.
×
4111
                s.removePeer(connectedPeer)
×
4112
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4113
                s.scheduledPeerConnection[pubStr] = func() {
×
4114
                        s.peerConnected(conn, connReq, false)
×
4115
                }
×
4116
        }
4117
}
4118

4119
// UnassignedConnID is the default connection ID that a request can have before
4120
// it actually is submitted to the connmgr.
4121
// TODO(conner): move into connmgr package, or better, add connmgr method for
4122
// generating atomic IDs
4123
const UnassignedConnID uint64 = 0
4124

4125
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4126
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4127
// Afterwards, each connection request removed from the connmgr. The caller can
4128
// optionally specify a connection ID to ignore, which prevents us from
4129
// canceling a successful request. All persistent connreqs for the provided
4130
// pubkey are discarded after the operationjw.
4131
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
1✔
4132
        // First, cancel any lingering persistent retry attempts, which will
1✔
4133
        // prevent retries for any with backoffs that are still maturing.
1✔
4134
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
2✔
4135
                close(cancelChan)
1✔
4136
                delete(s.persistentRetryCancels, pubStr)
1✔
4137
        }
1✔
4138

4139
        // Next, check to see if we have any outstanding persistent connection
4140
        // requests to this peer. If so, then we'll remove all of these
4141
        // connection requests, and also delete the entry from the map.
4142
        connReqs, ok := s.persistentConnReqs[pubStr]
1✔
4143
        if !ok {
2✔
4144
                return
1✔
4145
        }
1✔
4146

4147
        for _, connReq := range connReqs {
2✔
4148
                srvrLog.Tracef("Canceling %s:", connReqs)
1✔
4149

1✔
4150
                // Atomically capture the current request identifier.
1✔
4151
                connID := connReq.ID()
1✔
4152

1✔
4153
                // Skip any zero IDs, this indicates the request has not
1✔
4154
                // yet been schedule.
1✔
4155
                if connID == UnassignedConnID {
1✔
4156
                        continue
×
4157
                }
4158

4159
                // Skip a particular connection ID if instructed.
4160
                if skip != nil && connID == *skip {
2✔
4161
                        continue
1✔
4162
                }
4163

4164
                s.connMgr.Remove(connID)
1✔
4165
        }
4166

4167
        delete(s.persistentConnReqs, pubStr)
1✔
4168
}
4169

4170
// handleCustomMessage dispatches an incoming custom peers message to
4171
// subscribers.
4172
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
1✔
4173
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
1✔
4174
                peer, msg.Type)
1✔
4175

1✔
4176
        return s.customMessageServer.SendUpdate(&CustomMessage{
1✔
4177
                Peer: peer,
1✔
4178
                Msg:  msg,
1✔
4179
        })
1✔
4180
}
1✔
4181

4182
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4183
// messages.
4184
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
1✔
4185
        return s.customMessageServer.Subscribe()
1✔
4186
}
1✔
4187

4188
// peerConnected is a function that handles initialization a newly connected
4189
// peer by adding it to the server's global list of all active peers, and
4190
// starting all the goroutines the peer needs to function properly. The inbound
4191
// boolean should be true if the peer initiated the connection to us.
4192
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4193
        inbound bool) {
1✔
4194

1✔
4195
        brontideConn := conn.(*brontide.Conn)
1✔
4196
        addr := conn.RemoteAddr()
1✔
4197
        pubKey := brontideConn.RemotePub()
1✔
4198

1✔
4199
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
1✔
4200
                pubKey.SerializeCompressed(), addr, inbound)
1✔
4201

1✔
4202
        peerAddr := &lnwire.NetAddress{
1✔
4203
                IdentityKey: pubKey,
1✔
4204
                Address:     addr,
1✔
4205
                ChainNet:    s.cfg.ActiveNetParams.Net,
1✔
4206
        }
1✔
4207

1✔
4208
        // With the brontide connection established, we'll now craft the feature
1✔
4209
        // vectors to advertise to the remote node.
1✔
4210
        initFeatures := s.featureMgr.Get(feature.SetInit)
1✔
4211
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
1✔
4212

1✔
4213
        // Lookup past error caches for the peer in the server. If no buffer is
1✔
4214
        // found, create a fresh buffer.
1✔
4215
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
1✔
4216
        errBuffer, ok := s.peerErrors[pkStr]
1✔
4217
        if !ok {
2✔
4218
                var err error
1✔
4219
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
1✔
4220
                if err != nil {
1✔
4221
                        srvrLog.Errorf("unable to create peer %v", err)
×
4222
                        return
×
4223
                }
×
4224
        }
4225

4226
        // If we directly set the peer.Config TowerClient member to the
4227
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4228
        // the peer.Config's TowerClient member will not evaluate to nil even
4229
        // though the underlying value is nil. To avoid this gotcha which can
4230
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4231
        // TowerClient if needed.
4232
        var towerClient wtclient.ClientManager
1✔
4233
        if s.towerClientMgr != nil {
2✔
4234
                towerClient = s.towerClientMgr
1✔
4235
        }
1✔
4236

4237
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
1✔
4238
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
1✔
4239

1✔
4240
        // Now that we've established a connection, create a peer, and it to the
1✔
4241
        // set of currently active peers. Configure the peer with the incoming
1✔
4242
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
1✔
4243
        // offered that would trigger channel closure. In case of outgoing
1✔
4244
        // htlcs, an extra block is added to prevent the channel from being
1✔
4245
        // closed when the htlc is outstanding and a new block comes in.
1✔
4246
        pCfg := peer.Config{
1✔
4247
                Conn:                    brontideConn,
1✔
4248
                ConnReq:                 connReq,
1✔
4249
                Addr:                    peerAddr,
1✔
4250
                Inbound:                 inbound,
1✔
4251
                Features:                initFeatures,
1✔
4252
                LegacyFeatures:          legacyFeatures,
1✔
4253
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
1✔
4254
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
1✔
4255
                ErrorBuffer:             errBuffer,
1✔
4256
                WritePool:               s.writePool,
1✔
4257
                ReadPool:                s.readPool,
1✔
4258
                Switch:                  s.htlcSwitch,
1✔
4259
                InterceptSwitch:         s.interceptableSwitch,
1✔
4260
                ChannelDB:               s.chanStateDB,
1✔
4261
                ChannelGraph:            s.graphDB,
1✔
4262
                ChainArb:                s.chainArb,
1✔
4263
                AuthGossiper:            s.authGossiper,
1✔
4264
                ChanStatusMgr:           s.chanStatusMgr,
1✔
4265
                ChainIO:                 s.cc.ChainIO,
1✔
4266
                FeeEstimator:            s.cc.FeeEstimator,
1✔
4267
                Signer:                  s.cc.Wallet.Cfg.Signer,
1✔
4268
                SigPool:                 s.sigPool,
1✔
4269
                Wallet:                  s.cc.Wallet,
1✔
4270
                ChainNotifier:           s.cc.ChainNotifier,
1✔
4271
                BestBlockView:           s.cc.BestBlockTracker,
1✔
4272
                RoutingPolicy:           s.cc.RoutingPolicy,
1✔
4273
                Sphinx:                  s.sphinx,
1✔
4274
                WitnessBeacon:           s.witnessBeacon,
1✔
4275
                Invoices:                s.invoices,
1✔
4276
                ChannelNotifier:         s.channelNotifier,
1✔
4277
                HtlcNotifier:            s.htlcNotifier,
1✔
4278
                TowerClient:             towerClient,
1✔
4279
                DisconnectPeer:          s.DisconnectPeer,
1✔
4280
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
1✔
4281
                        lnwire.NodeAnnouncement, error) {
2✔
4282

1✔
4283
                        return s.genNodeAnnouncement(nil)
1✔
4284
                },
1✔
4285

4286
                PongBuf: s.pongBuf,
4287

4288
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4289

4290
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4291

4292
                FundingManager: s.fundingMgr,
4293

4294
                Hodl:                    s.cfg.Hodl,
4295
                UnsafeReplay:            s.cfg.UnsafeReplay,
4296
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4297
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4298
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4299
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4300
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4301
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4302
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4303
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4304
                HandleCustomMessage:    s.handleCustomMessage,
4305
                GetAliases:             s.aliasMgr.GetAliases,
4306
                RequestAlias:           s.aliasMgr.RequestAlias,
4307
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4308
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4309
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4310
                MaxFeeExposure:         thresholdMSats,
4311
                Quit:                   s.quit,
4312
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4313
                AuxSigner:              s.implCfg.AuxSigner,
4314
                MsgRouter:              s.implCfg.MsgRouter,
4315
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4316
                AuxResolver:            s.implCfg.AuxContractResolver,
4317
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4318
                ShouldFwdExpEndorsement: func() bool {
1✔
4319
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
2✔
4320
                                return false
1✔
4321
                        }
1✔
4322

4323
                        return clock.NewDefaultClock().Now().Before(
1✔
4324
                                EndorsementExperimentEnd,
1✔
4325
                        )
1✔
4326
                },
4327
        }
4328

4329
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
1✔
4330
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
1✔
4331

1✔
4332
        p := peer.NewBrontide(pCfg)
1✔
4333

1✔
4334
        // TODO(roasbeef): update IP address for link-node
1✔
4335
        //  * also mark last-seen, do it one single transaction?
1✔
4336

1✔
4337
        s.addPeer(p)
1✔
4338

1✔
4339
        // Once we have successfully added the peer to the server, we can
1✔
4340
        // delete the previous error buffer from the server's map of error
1✔
4341
        // buffers.
1✔
4342
        delete(s.peerErrors, pkStr)
1✔
4343

1✔
4344
        // Dispatch a goroutine to asynchronously start the peer. This process
1✔
4345
        // includes sending and receiving Init messages, which would be a DOS
1✔
4346
        // vector if we held the server's mutex throughout the procedure.
1✔
4347
        s.wg.Add(1)
1✔
4348
        go s.peerInitializer(p)
1✔
4349
}
4350

4351
// addPeer adds the passed peer to the server's global state of all active
4352
// peers.
4353
func (s *server) addPeer(p *peer.Brontide) {
1✔
4354
        if p == nil {
1✔
4355
                return
×
4356
        }
×
4357

4358
        pubBytes := p.IdentityKey().SerializeCompressed()
1✔
4359

1✔
4360
        // Ignore new peers if we're shutting down.
1✔
4361
        if s.Stopped() {
1✔
4362
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4363
                        pubBytes)
×
4364
                p.Disconnect(ErrServerShuttingDown)
×
4365

×
4366
                return
×
4367
        }
×
4368

4369
        // Track the new peer in our indexes so we can quickly look it up either
4370
        // according to its public key, or its peer ID.
4371
        // TODO(roasbeef): pipe all requests through to the
4372
        // queryHandler/peerManager
4373

4374
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4375
        // be human-readable.
4376
        pubStr := string(pubBytes)
1✔
4377

1✔
4378
        s.peersByPub[pubStr] = p
1✔
4379

1✔
4380
        if p.Inbound() {
2✔
4381
                s.inboundPeers[pubStr] = p
1✔
4382
        } else {
2✔
4383
                s.outboundPeers[pubStr] = p
1✔
4384
        }
1✔
4385

4386
        // Inform the peer notifier of a peer online event so that it can be reported
4387
        // to clients listening for peer events.
4388
        var pubKey [33]byte
1✔
4389
        copy(pubKey[:], pubBytes)
1✔
4390

1✔
4391
        s.peerNotifier.NotifyPeerOnline(pubKey)
1✔
4392
}
4393

4394
// peerInitializer asynchronously starts a newly connected peer after it has
4395
// been added to the server's peer map. This method sets up a
4396
// peerTerminationWatcher for the given peer, and ensures that it executes even
4397
// if the peer failed to start. In the event of a successful connection, this
4398
// method reads the negotiated, local feature-bits and spawns the appropriate
4399
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4400
// be signaled of the new peer once the method returns.
4401
//
4402
// NOTE: This MUST be launched as a goroutine.
4403
func (s *server) peerInitializer(p *peer.Brontide) {
1✔
4404
        defer s.wg.Done()
1✔
4405

1✔
4406
        pubBytes := p.IdentityKey().SerializeCompressed()
1✔
4407

1✔
4408
        // Avoid initializing peers while the server is exiting.
1✔
4409
        if s.Stopped() {
1✔
4410
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4411
                        pubBytes)
×
4412
                return
×
4413
        }
×
4414

4415
        // Create a channel that will be used to signal a successful start of
4416
        // the link. This prevents the peer termination watcher from beginning
4417
        // its duty too early.
4418
        ready := make(chan struct{})
1✔
4419

1✔
4420
        // Before starting the peer, launch a goroutine to watch for the
1✔
4421
        // unexpected termination of this peer, which will ensure all resources
1✔
4422
        // are properly cleaned up, and re-establish persistent connections when
1✔
4423
        // necessary. The peer termination watcher will be short circuited if
1✔
4424
        // the peer is ever added to the ignorePeerTermination map, indicating
1✔
4425
        // that the server has already handled the removal of this peer.
1✔
4426
        s.wg.Add(1)
1✔
4427
        go s.peerTerminationWatcher(p, ready)
1✔
4428

1✔
4429
        // Start the peer! If an error occurs, we Disconnect the peer, which
1✔
4430
        // will unblock the peerTerminationWatcher.
1✔
4431
        if err := p.Start(); err != nil {
1✔
4432
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
4433

×
4434
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
4435
                return
×
4436
        }
×
4437

4438
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4439
        // was successful, and to begin watching the peer's wait group.
4440
        close(ready)
1✔
4441

1✔
4442
        s.mu.Lock()
1✔
4443
        defer s.mu.Unlock()
1✔
4444

1✔
4445
        // Check if there are listeners waiting for this peer to come online.
1✔
4446
        srvrLog.Debugf("Notifying that peer %v is online", p)
1✔
4447

1✔
4448
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
1✔
4449
        // route.Vertex as the key type of peerConnectedListeners.
1✔
4450
        pubStr := string(pubBytes)
1✔
4451
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
2✔
4452
                select {
1✔
4453
                case peerChan <- p:
1✔
4454
                case <-s.quit:
×
4455
                        return
×
4456
                }
4457
        }
4458
        delete(s.peerConnectedListeners, pubStr)
1✔
4459
}
4460

4461
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4462
// and then cleans up all resources allocated to the peer, notifies relevant
4463
// sub-systems of its demise, and finally handles re-connecting to the peer if
4464
// it's persistent. If the server intentionally disconnects a peer, it should
4465
// have a corresponding entry in the ignorePeerTermination map which will cause
4466
// the cleanup routine to exit early. The passed `ready` chan is used to
4467
// synchronize when WaitForDisconnect should begin watching on the peer's
4468
// waitgroup. The ready chan should only be signaled if the peer starts
4469
// successfully, otherwise the peer should be disconnected instead.
4470
//
4471
// NOTE: This MUST be launched as a goroutine.
4472
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
1✔
4473
        defer s.wg.Done()
1✔
4474

1✔
4475
        p.WaitForDisconnect(ready)
1✔
4476

1✔
4477
        srvrLog.Debugf("Peer %v has been disconnected", p)
1✔
4478

1✔
4479
        // If the server is exiting then we can bail out early ourselves as all
1✔
4480
        // the other sub-systems will already be shutting down.
1✔
4481
        if s.Stopped() {
2✔
4482
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
1✔
4483
                return
1✔
4484
        }
1✔
4485

4486
        // Next, we'll cancel all pending funding reservations with this node.
4487
        // If we tried to initiate any funding flows that haven't yet finished,
4488
        // then we need to unlock those committed outputs so they're still
4489
        // available for use.
4490
        s.fundingMgr.CancelPeerReservations(p.PubKey())
1✔
4491

1✔
4492
        pubKey := p.IdentityKey()
1✔
4493

1✔
4494
        // We'll also inform the gossiper that this peer is no longer active,
1✔
4495
        // so we don't need to maintain sync state for it any longer.
1✔
4496
        s.authGossiper.PruneSyncState(p.PubKey())
1✔
4497

1✔
4498
        // Tell the switch to remove all links associated with this peer.
1✔
4499
        // Passing nil as the target link indicates that all links associated
1✔
4500
        // with this interface should be closed.
1✔
4501
        //
1✔
4502
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
1✔
4503
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
1✔
4504
        if err != nil && err != htlcswitch.ErrNoLinksFound {
1✔
4505
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4506
        }
×
4507

4508
        for _, link := range links {
2✔
4509
                s.htlcSwitch.RemoveLink(link.ChanID())
1✔
4510
        }
1✔
4511

4512
        s.mu.Lock()
1✔
4513
        defer s.mu.Unlock()
1✔
4514

1✔
4515
        // If there were any notification requests for when this peer
1✔
4516
        // disconnected, we can trigger them now.
1✔
4517
        srvrLog.Debugf("Notifying that peer %v is offline", p)
1✔
4518
        pubStr := string(pubKey.SerializeCompressed())
1✔
4519
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
2✔
4520
                close(offlineChan)
1✔
4521
        }
1✔
4522
        delete(s.peerDisconnectedListeners, pubStr)
1✔
4523

1✔
4524
        // If the server has already removed this peer, we can short circuit the
1✔
4525
        // peer termination watcher and skip cleanup.
1✔
4526
        if _, ok := s.ignorePeerTermination[p]; ok {
1✔
4527
                delete(s.ignorePeerTermination, p)
×
4528

×
4529
                pubKey := p.PubKey()
×
4530
                pubStr := string(pubKey[:])
×
4531

×
4532
                // If a connection callback is present, we'll go ahead and
×
4533
                // execute it now that previous peer has fully disconnected. If
×
4534
                // the callback is not present, this likely implies the peer was
×
4535
                // purposefully disconnected via RPC, and that no reconnect
×
4536
                // should be attempted.
×
4537
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4538
                if ok {
×
4539
                        delete(s.scheduledPeerConnection, pubStr)
×
4540
                        connCallback()
×
4541
                }
×
4542
                return
×
4543
        }
4544

4545
        // First, cleanup any remaining state the server has regarding the peer
4546
        // in question.
4547
        s.removePeer(p)
1✔
4548

1✔
4549
        // Next, check to see if this is a persistent peer or not.
1✔
4550
        if _, ok := s.persistentPeers[pubStr]; !ok {
2✔
4551
                return
1✔
4552
        }
1✔
4553

4554
        // Get the last address that we used to connect to the peer.
4555
        addrs := []net.Addr{
1✔
4556
                p.NetAddress().Address,
1✔
4557
        }
1✔
4558

1✔
4559
        // We'll ensure that we locate all the peers advertised addresses for
1✔
4560
        // reconnection purposes.
1✔
4561
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
1✔
4562
        switch {
1✔
4563
        // We found advertised addresses, so use them.
4564
        case err == nil:
1✔
4565
                addrs = advertisedAddrs
1✔
4566

4567
        // The peer doesn't have an advertised address.
4568
        case err == errNoAdvertisedAddr:
1✔
4569
                // If it is an outbound peer then we fall back to the existing
1✔
4570
                // peer address.
1✔
4571
                if !p.Inbound() {
2✔
4572
                        break
1✔
4573
                }
4574

4575
                // Fall back to the existing peer address if
4576
                // we're not accepting connections over Tor.
4577
                if s.torController == nil {
2✔
4578
                        break
1✔
4579
                }
4580

4581
                // If we are, the peer's address won't be known
4582
                // to us (we'll see a private address, which is
4583
                // the address used by our onion service to dial
4584
                // to lnd), so we don't have enough information
4585
                // to attempt a reconnect.
4586
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4587
                        "to inbound peer %v without "+
×
4588
                        "advertised address", p)
×
4589
                return
×
4590

4591
        // We came across an error retrieving an advertised
4592
        // address, log it, and fall back to the existing peer
4593
        // address.
4594
        default:
1✔
4595
                srvrLog.Errorf("Unable to retrieve advertised "+
1✔
4596
                        "address for node %x: %v", p.PubKey(),
1✔
4597
                        err)
1✔
4598
        }
4599

4600
        // Make an easy lookup map so that we can check if an address
4601
        // is already in the address list that we have stored for this peer.
4602
        existingAddrs := make(map[string]bool)
1✔
4603
        for _, addr := range s.persistentPeerAddrs[pubStr] {
2✔
4604
                existingAddrs[addr.String()] = true
1✔
4605
        }
1✔
4606

4607
        // Add any missing addresses for this peer to persistentPeerAddr.
4608
        for _, addr := range addrs {
2✔
4609
                if existingAddrs[addr.String()] {
1✔
4610
                        continue
×
4611
                }
4612

4613
                s.persistentPeerAddrs[pubStr] = append(
1✔
4614
                        s.persistentPeerAddrs[pubStr],
1✔
4615
                        &lnwire.NetAddress{
1✔
4616
                                IdentityKey: p.IdentityKey(),
1✔
4617
                                Address:     addr,
1✔
4618
                                ChainNet:    p.NetAddress().ChainNet,
1✔
4619
                        },
1✔
4620
                )
1✔
4621
        }
4622

4623
        // Record the computed backoff in the backoff map.
4624
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
1✔
4625
        s.persistentPeersBackoff[pubStr] = backoff
1✔
4626

1✔
4627
        // Initialize a retry canceller for this peer if one does not
1✔
4628
        // exist.
1✔
4629
        cancelChan, ok := s.persistentRetryCancels[pubStr]
1✔
4630
        if !ok {
2✔
4631
                cancelChan = make(chan struct{})
1✔
4632
                s.persistentRetryCancels[pubStr] = cancelChan
1✔
4633
        }
1✔
4634

4635
        // We choose not to wait group this go routine since the Connect
4636
        // call can stall for arbitrarily long if we shutdown while an
4637
        // outbound connection attempt is being made.
4638
        go func() {
2✔
4639
                srvrLog.Debugf("Scheduling connection re-establishment to "+
1✔
4640
                        "persistent peer %x in %s",
1✔
4641
                        p.IdentityKey().SerializeCompressed(), backoff)
1✔
4642

1✔
4643
                select {
1✔
4644
                case <-time.After(backoff):
1✔
4645
                case <-cancelChan:
1✔
4646
                        return
1✔
4647
                case <-s.quit:
1✔
4648
                        return
1✔
4649
                }
4650

4651
                srvrLog.Debugf("Attempting to re-establish persistent "+
1✔
4652
                        "connection to peer %x",
1✔
4653
                        p.IdentityKey().SerializeCompressed())
1✔
4654

1✔
4655
                s.connectToPersistentPeer(pubStr)
1✔
4656
        }()
4657
}
4658

4659
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4660
// to connect to the peer. It creates connection requests if there are
4661
// currently none for a given address and it removes old connection requests
4662
// if the associated address is no longer in the latest address list for the
4663
// peer.
4664
func (s *server) connectToPersistentPeer(pubKeyStr string) {
1✔
4665
        s.mu.Lock()
1✔
4666
        defer s.mu.Unlock()
1✔
4667

1✔
4668
        // Create an easy lookup map of the addresses we have stored for the
1✔
4669
        // peer. We will remove entries from this map if we have existing
1✔
4670
        // connection requests for the associated address and then any leftover
1✔
4671
        // entries will indicate which addresses we should create new
1✔
4672
        // connection requests for.
1✔
4673
        addrMap := make(map[string]*lnwire.NetAddress)
1✔
4674
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
2✔
4675
                addrMap[addr.String()] = addr
1✔
4676
        }
1✔
4677

4678
        // Go through each of the existing connection requests and
4679
        // check if they correspond to the latest set of addresses. If
4680
        // there is a connection requests that does not use one of the latest
4681
        // advertised addresses then remove that connection request.
4682
        var updatedConnReqs []*connmgr.ConnReq
1✔
4683
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
2✔
4684
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
1✔
4685

1✔
4686
                switch _, ok := addrMap[lnAddr]; ok {
1✔
4687
                // If the existing connection request is using one of the
4688
                // latest advertised addresses for the peer then we add it to
4689
                // updatedConnReqs and remove the associated address from
4690
                // addrMap so that we don't recreate this connReq later on.
4691
                case true:
×
4692
                        updatedConnReqs = append(
×
4693
                                updatedConnReqs, connReq,
×
4694
                        )
×
4695
                        delete(addrMap, lnAddr)
×
4696

4697
                // If the existing connection request is using an address that
4698
                // is not one of the latest advertised addresses for the peer
4699
                // then we remove the connecting request from the connection
4700
                // manager.
4701
                case false:
1✔
4702
                        srvrLog.Info(
1✔
4703
                                "Removing conn req:", connReq.Addr.String(),
1✔
4704
                        )
1✔
4705
                        s.connMgr.Remove(connReq.ID())
1✔
4706
                }
4707
        }
4708

4709
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
1✔
4710

1✔
4711
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
1✔
4712
        if !ok {
2✔
4713
                cancelChan = make(chan struct{})
1✔
4714
                s.persistentRetryCancels[pubKeyStr] = cancelChan
1✔
4715
        }
1✔
4716

4717
        // Any addresses left in addrMap are new ones that we have not made
4718
        // connection requests for. So create new connection requests for those.
4719
        // If there is more than one address in the address map, stagger the
4720
        // creation of the connection requests for those.
4721
        go func() {
2✔
4722
                ticker := time.NewTicker(multiAddrConnectionStagger)
1✔
4723
                defer ticker.Stop()
1✔
4724

1✔
4725
                for _, addr := range addrMap {
2✔
4726
                        // Send the persistent connection request to the
1✔
4727
                        // connection manager, saving the request itself so we
1✔
4728
                        // can cancel/restart the process as needed.
1✔
4729
                        connReq := &connmgr.ConnReq{
1✔
4730
                                Addr:      addr,
1✔
4731
                                Permanent: true,
1✔
4732
                        }
1✔
4733

1✔
4734
                        s.mu.Lock()
1✔
4735
                        s.persistentConnReqs[pubKeyStr] = append(
1✔
4736
                                s.persistentConnReqs[pubKeyStr], connReq,
1✔
4737
                        )
1✔
4738
                        s.mu.Unlock()
1✔
4739

1✔
4740
                        srvrLog.Debugf("Attempting persistent connection to "+
1✔
4741
                                "channel peer %v", addr)
1✔
4742

1✔
4743
                        go s.connMgr.Connect(connReq)
1✔
4744

1✔
4745
                        select {
1✔
4746
                        case <-s.quit:
1✔
4747
                                return
1✔
4748
                        case <-cancelChan:
1✔
4749
                                return
1✔
4750
                        case <-ticker.C:
1✔
4751
                        }
4752
                }
4753
        }()
4754
}
4755

4756
// removePeer removes the passed peer from the server's state of all active
4757
// peers.
4758
func (s *server) removePeer(p *peer.Brontide) {
1✔
4759
        if p == nil {
1✔
4760
                return
×
4761
        }
×
4762

4763
        srvrLog.Debugf("removing peer %v", p)
1✔
4764

1✔
4765
        // As the peer is now finished, ensure that the TCP connection is
1✔
4766
        // closed and all of its related goroutines have exited.
1✔
4767
        p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
1✔
4768

1✔
4769
        // If this peer had an active persistent connection request, remove it.
1✔
4770
        if p.ConnReq() != nil {
2✔
4771
                s.connMgr.Remove(p.ConnReq().ID())
1✔
4772
        }
1✔
4773

4774
        // Ignore deleting peers if we're shutting down.
4775
        if s.Stopped() {
1✔
4776
                return
×
4777
        }
×
4778

4779
        pKey := p.PubKey()
1✔
4780
        pubSer := pKey[:]
1✔
4781
        pubStr := string(pubSer)
1✔
4782

1✔
4783
        delete(s.peersByPub, pubStr)
1✔
4784

1✔
4785
        if p.Inbound() {
2✔
4786
                delete(s.inboundPeers, pubStr)
1✔
4787
        } else {
2✔
4788
                delete(s.outboundPeers, pubStr)
1✔
4789
        }
1✔
4790

4791
        // Copy the peer's error buffer across to the server if it has any items
4792
        // in it so that we can restore peer errors across connections.
4793
        if p.ErrorBuffer().Total() > 0 {
2✔
4794
                s.peerErrors[pubStr] = p.ErrorBuffer()
1✔
4795
        }
1✔
4796

4797
        // Inform the peer notifier of a peer offline event so that it can be
4798
        // reported to clients listening for peer events.
4799
        var pubKey [33]byte
1✔
4800
        copy(pubKey[:], pubSer)
1✔
4801

1✔
4802
        s.peerNotifier.NotifyPeerOffline(pubKey)
1✔
4803
}
4804

4805
// ConnectToPeer requests that the server connect to a Lightning Network peer
4806
// at the specified address. This function will *block* until either a
4807
// connection is established, or the initial handshake process fails.
4808
//
4809
// NOTE: This function is safe for concurrent access.
4810
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4811
        perm bool, timeout time.Duration) error {
1✔
4812

1✔
4813
        targetPub := string(addr.IdentityKey.SerializeCompressed())
1✔
4814

1✔
4815
        // Acquire mutex, but use explicit unlocking instead of defer for
1✔
4816
        // better granularity.  In certain conditions, this method requires
1✔
4817
        // making an outbound connection to a remote peer, which requires the
1✔
4818
        // lock to be released, and subsequently reacquired.
1✔
4819
        s.mu.Lock()
1✔
4820

1✔
4821
        // Ensure we're not already connected to this peer.
1✔
4822
        peer, err := s.findPeerByPubStr(targetPub)
1✔
4823
        if err == nil {
2✔
4824
                s.mu.Unlock()
1✔
4825
                return &errPeerAlreadyConnected{peer: peer}
1✔
4826
        }
1✔
4827

4828
        // Peer was not found, continue to pursue connection with peer.
4829

4830
        // If there's already a pending connection request for this pubkey,
4831
        // then we ignore this request to ensure we don't create a redundant
4832
        // connection.
4833
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
2✔
4834
                srvrLog.Warnf("Already have %d persistent connection "+
1✔
4835
                        "requests for %v, connecting anyway.", len(reqs), addr)
1✔
4836
        }
1✔
4837

4838
        // If there's not already a pending or active connection to this node,
4839
        // then instruct the connection manager to attempt to establish a
4840
        // persistent connection to the peer.
4841
        srvrLog.Debugf("Connecting to %v", addr)
1✔
4842
        if perm {
2✔
4843
                connReq := &connmgr.ConnReq{
1✔
4844
                        Addr:      addr,
1✔
4845
                        Permanent: true,
1✔
4846
                }
1✔
4847

1✔
4848
                // Since the user requested a permanent connection, we'll set
1✔
4849
                // the entry to true which will tell the server to continue
1✔
4850
                // reconnecting even if the number of channels with this peer is
1✔
4851
                // zero.
1✔
4852
                s.persistentPeers[targetPub] = true
1✔
4853
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
2✔
4854
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
1✔
4855
                }
1✔
4856
                s.persistentConnReqs[targetPub] = append(
1✔
4857
                        s.persistentConnReqs[targetPub], connReq,
1✔
4858
                )
1✔
4859
                s.mu.Unlock()
1✔
4860

1✔
4861
                go s.connMgr.Connect(connReq)
1✔
4862

1✔
4863
                return nil
1✔
4864
        }
4865
        s.mu.Unlock()
1✔
4866

1✔
4867
        // If we're not making a persistent connection, then we'll attempt to
1✔
4868
        // connect to the target peer. If the we can't make the connection, or
1✔
4869
        // the crypto negotiation breaks down, then return an error to the
1✔
4870
        // caller.
1✔
4871
        errChan := make(chan error, 1)
1✔
4872
        s.connectToPeer(addr, errChan, timeout)
1✔
4873

1✔
4874
        select {
1✔
4875
        case err := <-errChan:
1✔
4876
                return err
1✔
4877
        case <-s.quit:
×
4878
                return ErrServerShuttingDown
×
4879
        }
4880
}
4881

4882
// connectToPeer establishes a connection to a remote peer. errChan is used to
4883
// notify the caller if the connection attempt has failed. Otherwise, it will be
4884
// closed.
4885
func (s *server) connectToPeer(addr *lnwire.NetAddress,
4886
        errChan chan<- error, timeout time.Duration) {
1✔
4887

1✔
4888
        conn, err := brontide.Dial(
1✔
4889
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
1✔
4890
        )
1✔
4891
        if err != nil {
2✔
4892
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
1✔
4893
                select {
1✔
4894
                case errChan <- err:
1✔
4895
                case <-s.quit:
×
4896
                }
4897
                return
1✔
4898
        }
4899

4900
        close(errChan)
1✔
4901

1✔
4902
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
1✔
4903
                conn.LocalAddr(), conn.RemoteAddr())
1✔
4904

1✔
4905
        s.OutboundPeerConnected(nil, conn)
1✔
4906
}
4907

4908
// DisconnectPeer sends the request to server to close the connection with peer
4909
// identified by public key.
4910
//
4911
// NOTE: This function is safe for concurrent access.
4912
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
1✔
4913
        pubBytes := pubKey.SerializeCompressed()
1✔
4914
        pubStr := string(pubBytes)
1✔
4915

1✔
4916
        s.mu.Lock()
1✔
4917
        defer s.mu.Unlock()
1✔
4918

1✔
4919
        // Check that were actually connected to this peer. If not, then we'll
1✔
4920
        // exit in an error as we can't disconnect from a peer that we're not
1✔
4921
        // currently connected to.
1✔
4922
        peer, err := s.findPeerByPubStr(pubStr)
1✔
4923
        if err == ErrPeerNotConnected {
2✔
4924
                return fmt.Errorf("peer %x is not connected", pubBytes)
1✔
4925
        }
1✔
4926

4927
        srvrLog.Infof("Disconnecting from %v", peer)
1✔
4928

1✔
4929
        s.cancelConnReqs(pubStr, nil)
1✔
4930

1✔
4931
        // If this peer was formerly a persistent connection, then we'll remove
1✔
4932
        // them from this map so we don't attempt to re-connect after we
1✔
4933
        // disconnect.
1✔
4934
        delete(s.persistentPeers, pubStr)
1✔
4935
        delete(s.persistentPeersBackoff, pubStr)
1✔
4936

1✔
4937
        // Remove the peer by calling Disconnect. Previously this was done with
1✔
4938
        // removePeer, which bypassed the peerTerminationWatcher.
1✔
4939
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
1✔
4940

1✔
4941
        return nil
1✔
4942
}
4943

4944
// OpenChannel sends a request to the server to open a channel to the specified
4945
// peer identified by nodeKey with the passed channel funding parameters.
4946
//
4947
// NOTE: This function is safe for concurrent access.
4948
func (s *server) OpenChannel(
4949
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
1✔
4950

1✔
4951
        // The updateChan will have a buffer of 2, since we expect a ChanPending
1✔
4952
        // + a ChanOpen update, and we want to make sure the funding process is
1✔
4953
        // not blocked if the caller is not reading the updates.
1✔
4954
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
1✔
4955
        req.Err = make(chan error, 1)
1✔
4956

1✔
4957
        // First attempt to locate the target peer to open a channel with, if
1✔
4958
        // we're unable to locate the peer then this request will fail.
1✔
4959
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
1✔
4960
        s.mu.RLock()
1✔
4961
        peer, ok := s.peersByPub[string(pubKeyBytes)]
1✔
4962
        if !ok {
1✔
4963
                s.mu.RUnlock()
×
4964

×
4965
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4966
                return req.Updates, req.Err
×
4967
        }
×
4968
        req.Peer = peer
1✔
4969
        s.mu.RUnlock()
1✔
4970

1✔
4971
        // We'll wait until the peer is active before beginning the channel
1✔
4972
        // opening process.
1✔
4973
        select {
1✔
4974
        case <-peer.ActiveSignal():
1✔
4975
        case <-peer.QuitSignal():
×
4976
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4977
                return req.Updates, req.Err
×
4978
        case <-s.quit:
×
4979
                req.Err <- ErrServerShuttingDown
×
4980
                return req.Updates, req.Err
×
4981
        }
4982

4983
        // If the fee rate wasn't specified at this point we fail the funding
4984
        // because of the missing fee rate information. The caller of the
4985
        // `OpenChannel` method needs to make sure that default values for the
4986
        // fee rate are set beforehand.
4987
        if req.FundingFeePerKw == 0 {
1✔
4988
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
4989
                        "the channel opening transaction")
×
4990

×
4991
                return req.Updates, req.Err
×
4992
        }
×
4993

4994
        // Spawn a goroutine to send the funding workflow request to the funding
4995
        // manager. This allows the server to continue handling queries instead
4996
        // of blocking on this request which is exported as a synchronous
4997
        // request to the outside world.
4998
        go s.fundingMgr.InitFundingWorkflow(req)
1✔
4999

1✔
5000
        return req.Updates, req.Err
1✔
5001
}
5002

5003
// Peers returns a slice of all active peers.
5004
//
5005
// NOTE: This function is safe for concurrent access.
5006
func (s *server) Peers() []*peer.Brontide {
1✔
5007
        s.mu.RLock()
1✔
5008
        defer s.mu.RUnlock()
1✔
5009

1✔
5010
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
1✔
5011
        for _, peer := range s.peersByPub {
2✔
5012
                peers = append(peers, peer)
1✔
5013
        }
1✔
5014

5015
        return peers
1✔
5016
}
5017

5018
// computeNextBackoff uses a truncated exponential backoff to compute the next
5019
// backoff using the value of the exiting backoff. The returned duration is
5020
// randomized in either direction by 1/20 to prevent tight loops from
5021
// stabilizing.
5022
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
1✔
5023
        // Double the current backoff, truncating if it exceeds our maximum.
1✔
5024
        nextBackoff := 2 * currBackoff
1✔
5025
        if nextBackoff > maxBackoff {
2✔
5026
                nextBackoff = maxBackoff
1✔
5027
        }
1✔
5028

5029
        // Using 1/10 of our duration as a margin, compute a random offset to
5030
        // avoid the nodes entering connection cycles.
5031
        margin := nextBackoff / 10
1✔
5032

1✔
5033
        var wiggle big.Int
1✔
5034
        wiggle.SetUint64(uint64(margin))
1✔
5035
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
1✔
5036
                // Randomizing is not mission critical, so we'll just return the
×
5037
                // current backoff.
×
5038
                return nextBackoff
×
5039
        }
×
5040

5041
        // Otherwise add in our wiggle, but subtract out half of the margin so
5042
        // that the backoff can tweaked by 1/20 in either direction.
5043
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
1✔
5044
}
5045

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

5050
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5051
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
1✔
5052
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
1✔
5053
        if err != nil {
1✔
5054
                return nil, err
×
5055
        }
×
5056

5057
        node, err := s.graphDB.FetchLightningNode(vertex)
1✔
5058
        if err != nil {
2✔
5059
                return nil, err
1✔
5060
        }
1✔
5061

5062
        if len(node.Addresses) == 0 {
2✔
5063
                return nil, errNoAdvertisedAddr
1✔
5064
        }
1✔
5065

5066
        return node.Addresses, nil
1✔
5067
}
5068

5069
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5070
// channel update for a target channel.
5071
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5072
        *lnwire.ChannelUpdate1, error) {
1✔
5073

1✔
5074
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
1✔
5075
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
2✔
5076
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
1✔
5077
                if err != nil {
2✔
5078
                        return nil, err
1✔
5079
                }
1✔
5080

5081
                return netann.ExtractChannelUpdate(
1✔
5082
                        ourPubKey[:], info, edge1, edge2,
1✔
5083
                )
1✔
5084
        }
5085
}
5086

5087
// applyChannelUpdate applies the channel update to the different sub-systems of
5088
// the server. The useAlias boolean denotes whether or not to send an alias in
5089
// place of the real SCID.
5090
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5091
        op *wire.OutPoint, useAlias bool) error {
1✔
5092

1✔
5093
        var (
1✔
5094
                peerAlias    *lnwire.ShortChannelID
1✔
5095
                defaultAlias lnwire.ShortChannelID
1✔
5096
        )
1✔
5097

1✔
5098
        chanID := lnwire.NewChanIDFromOutPoint(*op)
1✔
5099

1✔
5100
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
1✔
5101
        // in the ChannelUpdate if it hasn't been announced yet.
1✔
5102
        if useAlias {
2✔
5103
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
1✔
5104
                if foundAlias != defaultAlias {
2✔
5105
                        peerAlias = &foundAlias
1✔
5106
                }
1✔
5107
        }
5108

5109
        errChan := s.authGossiper.ProcessLocalAnnouncement(
1✔
5110
                update, discovery.RemoteAlias(peerAlias),
1✔
5111
        )
1✔
5112
        select {
1✔
5113
        case err := <-errChan:
1✔
5114
                return err
1✔
5115
        case <-s.quit:
×
5116
                return ErrServerShuttingDown
×
5117
        }
5118
}
5119

5120
// SendCustomMessage sends a custom message to the peer with the specified
5121
// pubkey.
5122
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5123
        data []byte) error {
1✔
5124

1✔
5125
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
1✔
5126
        if err != nil {
1✔
5127
                return err
×
5128
        }
×
5129

5130
        // We'll wait until the peer is active.
5131
        select {
1✔
5132
        case <-peer.ActiveSignal():
1✔
5133
        case <-peer.QuitSignal():
×
5134
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5135
        case <-s.quit:
×
5136
                return ErrServerShuttingDown
×
5137
        }
5138

5139
        msg, err := lnwire.NewCustom(msgType, data)
1✔
5140
        if err != nil {
2✔
5141
                return err
1✔
5142
        }
1✔
5143

5144
        // Send the message as low-priority. For now we assume that all
5145
        // application-defined message are low priority.
5146
        return peer.SendMessageLazy(true, msg)
1✔
5147
}
5148

5149
// newSweepPkScriptGen creates closure that generates a new public key script
5150
// which should be used to sweep any funds into the on-chain wallet.
5151
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5152
// (p2wkh) output.
5153
func newSweepPkScriptGen(
5154
        wallet lnwallet.WalletController,
5155
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
1✔
5156

1✔
5157
        return func() fn.Result[lnwallet.AddrWithKey] {
2✔
5158
                sweepAddr, err := wallet.NewAddress(
1✔
5159
                        lnwallet.TaprootPubkey, false,
1✔
5160
                        lnwallet.DefaultAccountName,
1✔
5161
                )
1✔
5162
                if err != nil {
1✔
5163
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5164
                }
×
5165

5166
                addr, err := txscript.PayToAddrScript(sweepAddr)
1✔
5167
                if err != nil {
1✔
5168
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5169
                }
×
5170

5171
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
1✔
5172
                        wallet, netParams, addr,
1✔
5173
                )
1✔
5174
                if err != nil {
1✔
5175
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5176
                }
×
5177

5178
                return fn.Ok(lnwallet.AddrWithKey{
1✔
5179
                        DeliveryAddress: addr,
1✔
5180
                        InternalKey:     internalKeyDesc,
1✔
5181
                })
1✔
5182
        }
5183
}
5184

5185
// shouldPeerBootstrap returns true if we should attempt to perform peer
5186
// bootstrapping to actively seek our peers using the set of active network
5187
// bootstrappers.
5188
func shouldPeerBootstrap(cfg *Config) bool {
7✔
5189
        isSimnet := cfg.Bitcoin.SimNet
7✔
5190
        isSignet := cfg.Bitcoin.SigNet
7✔
5191
        isRegtest := cfg.Bitcoin.RegTest
7✔
5192
        isDevNetwork := isSimnet || isSignet || isRegtest
7✔
5193

7✔
5194
        // TODO(yy): remove the check on simnet/regtest such that the itest is
7✔
5195
        // covering the bootstrapping process.
7✔
5196
        return !cfg.NoNetBootstrap && !isDevNetwork
7✔
5197
}
7✔
5198

5199
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5200
// finished.
5201
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
1✔
5202
        // Get a list of closed channels.
1✔
5203
        channels, err := s.chanStateDB.FetchClosedChannels(false)
1✔
5204
        if err != nil {
1✔
5205
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5206
                return nil
×
5207
        }
×
5208

5209
        // Save the SCIDs in a map.
5210
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
1✔
5211
        for _, c := range channels {
2✔
5212
                // If the channel is not pending, its FC has been finalized.
1✔
5213
                if !c.IsPending {
2✔
5214
                        closedSCIDs[c.ShortChanID] = struct{}{}
1✔
5215
                }
1✔
5216
        }
5217

5218
        // Double check whether the reported closed channel has indeed finished
5219
        // closing.
5220
        //
5221
        // NOTE: There are misalignments regarding when a channel's FC is
5222
        // marked as finalized. We double check the pending channels to make
5223
        // sure the returned SCIDs are indeed terminated.
5224
        //
5225
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5226
        pendings, err := s.chanStateDB.FetchPendingChannels()
1✔
5227
        if err != nil {
1✔
5228
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5229
                return nil
×
5230
        }
×
5231

5232
        for _, c := range pendings {
2✔
5233
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
2✔
5234
                        continue
1✔
5235
                }
5236

5237
                // If the channel is still reported as pending, remove it from
5238
                // the map.
5239
                delete(closedSCIDs, c.ShortChannelID)
×
5240

×
5241
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5242
                        c.ShortChannelID)
×
5243
        }
5244

5245
        return closedSCIDs
1✔
5246
}
5247

5248
// getStartingBeat returns the current beat. This is used during the startup to
5249
// initialize blockbeat consumers.
5250
func (s *server) getStartingBeat() (*chainio.Beat, error) {
1✔
5251
        // beat is the current blockbeat.
1✔
5252
        var beat *chainio.Beat
1✔
5253

1✔
5254
        // We should get a notification with the current best block immediately
1✔
5255
        // by passing a nil block.
1✔
5256
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
1✔
5257
        if err != nil {
1✔
5258
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5259
        }
×
5260
        defer blockEpochs.Cancel()
1✔
5261

1✔
5262
        // We registered for the block epochs with a nil request. The notifier
1✔
5263
        // should send us the current best block immediately. So we need to
1✔
5264
        // wait for it here because we need to know the current best height.
1✔
5265
        select {
1✔
5266
        case bestBlock := <-blockEpochs.Epochs:
1✔
5267
                srvrLog.Infof("Received initial block %v at height %d",
1✔
5268
                        bestBlock.Hash, bestBlock.Height)
1✔
5269

1✔
5270
                // Update the current blockbeat.
1✔
5271
                beat = chainio.NewBeat(*bestBlock)
1✔
5272

5273
        case <-s.quit:
×
5274
                srvrLog.Debug("LND shutting down")
×
5275
        }
5276

5277
        return beat, nil
1✔
5278
}
5279

5280
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5281
// point has an active RBF chan closer.
5282
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5283
        chanPoint wire.OutPoint) bool {
1✔
5284

1✔
5285
        pubBytes := peerPub.SerializeCompressed()
1✔
5286

1✔
5287
        s.mu.RLock()
1✔
5288
        targetPeer, ok := s.peersByPub[string(pubBytes)]
1✔
5289
        s.mu.RUnlock()
1✔
5290
        if !ok {
1✔
NEW
5291
                return false
×
NEW
5292
        }
×
5293

5294
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
1✔
5295
}
5296

5297
// attemptCoopRbfFeeBump attempts to look up the active chan closer for a
5298
// channel given the outpoint. If found, we'll attempt to do a fee bump,
5299
// returning channels used for updates. If the channel isn't currently active
5300
// (p2p connection established), then his function will return an error.
5301
func (s *server) attemptCoopRbfFeeBump(ctx context.Context,
5302
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
5303
        deliveryScript lnwire.DeliveryAddress) (*peer.CoopCloseUpdates, error) {
1✔
5304

1✔
5305
        // First, we'll attempt to look up the channel based on it's
1✔
5306
        // ChannelPoint.
1✔
5307
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
1✔
5308
        if err != nil {
1✔
NEW
5309
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
NEW
5310
        }
×
5311

5312
        // From the channel, we can now get the pubkey of the peer, then use
5313
        // that to eventually get the chan closer.
5314
        peerPub := channel.IdentityPub.SerializeCompressed()
1✔
5315

1✔
5316
        // Now that we have the peer pub, we can look up the peer itself.
1✔
5317
        s.mu.RLock()
1✔
5318
        targetPeer, ok := s.peersByPub[string(peerPub)]
1✔
5319
        s.mu.RUnlock()
1✔
5320
        if !ok {
1✔
NEW
5321
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
NEW
5322
                        "not online", chanPoint)
×
NEW
5323
        }
×
5324

5325
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
1✔
5326
                ctx, chanPoint, feeRate, deliveryScript,
1✔
5327
        )
1✔
5328
        if err != nil {
1✔
NEW
5329
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
NEW
5330
                        "%w", err)
×
NEW
5331
        }
×
5332

5333
        return closeUpdates, nil
1✔
5334
}
5335

5336
// AttemptRBFCloseUpdate attempts to trigger a new RBF iteration for a co-op
5337
// close update. This route it to be used only if the target channel in question
5338
// is no longer active in the link. This can happen when we restart while we
5339
// already have done a single RBF co-op close iteration.
5340
func (s *server) AttemptRBFCloseUpdate(ctx context.Context,
5341
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
5342
        deliveryScript lnwire.DeliveryAddress) (*peer.CoopCloseUpdates, error) {
1✔
5343

1✔
5344
        // If the channel is present in the switch, then the request should flow
1✔
5345
        // through the switch instead.
1✔
5346
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
1✔
5347
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
1✔
NEW
5348
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
NEW
5349
                        "invalid request", chanPoint)
×
NEW
5350
        }
×
5351

5352
        // At this point, we know that the channel isn't present in the link, so
5353
        // we'll check to see if we have an entry in the active chan closer map.
5354
        updates, err := s.attemptCoopRbfFeeBump(
1✔
5355
                ctx, chanPoint, feeRate, deliveryScript,
1✔
5356
        )
1✔
5357
        if err != nil {
1✔
NEW
5358
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
NEW
5359
                        "ChannelPoint(%v)", chanPoint)
×
NEW
5360
        }
×
5361

5362
        return updates, nil
1✔
5363
}
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