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

lightningnetwork / lnd / 13727082033

07 Mar 2025 06:37PM UTC coverage: 58.289% (-10.3%) from 68.615%
13727082033

push

github

web-flow
Merge pull request #9581 from yyforyongyu/fix-TestReconnectSucceed

tor: fix `TestReconnectSucceed`

94454 of 162044 relevant lines covered (58.29%)

1.81 hits per line

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

63.93
/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 {
3✔
155
        return fmt.Sprintf("already connected to peer: %v", e.peer)
3✔
156
}
3✔
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 {
3✔
371
        graphSub, err := s.graphBuilder.SubscribeTopology()
3✔
372
        if err != nil {
3✔
373
                return err
×
374
        }
×
375

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

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

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

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

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

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

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

423
                                        s.mu.Lock()
3✔
424

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

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

439
                                        s.mu.Unlock()
3✔
440

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

447
        return nil
3✔
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) {
3✔
461
        var (
3✔
462
                host string
3✔
463
                port int
3✔
464
        )
3✔
465

3✔
466
        // Split the address into its host and port components.
3✔
467
        h, p, err := net.SplitHostPort(address)
3✔
468
        if err != nil {
3✔
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 {
3✔
474
                // Otherwise, we'll note both the host and ports.
3✔
475
                host = h
3✔
476
                portNum, err := strconv.Atoi(p)
3✔
477
                if err != nil {
3✔
478
                        return nil, err
×
479
                }
×
480
                port = portNum
3✔
481
        }
482

483
        if tor.IsOnionHost(host) {
3✔
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))
3✔
492
        return netCfg.ResolveTCPAddr("tcp", hostPort)
3✔
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) {
3✔
499

3✔
500
        return func(a net.Addr) (net.Conn, error) {
6✔
501
                lnAddr := a.(*lnwire.NetAddress)
3✔
502
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
503
        }
3✔
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) {
3✔
516

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

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

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

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

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

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

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

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

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

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

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

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

579
        //nolint:ll
580
        featureMgr, err := feature.NewManager(feature.Config{
3✔
581
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
3✔
582
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
3✔
583
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
3✔
584
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
3✔
585
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
3✔
586
                NoKeysend:                 !cfg.AcceptKeySend,
3✔
587
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
3✔
588
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
3✔
589
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
3✔
590
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
3✔
591
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
3✔
592
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
3✔
593
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
3✔
594
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
3✔
595
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
3✔
596
        })
3✔
597
        if err != nil {
3✔
598
                return nil, err
×
599
        }
×
600

601
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
602
        registryConfig := invoices.RegistryConfig{
3✔
603
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
604
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
605
                Clock:                       clock.NewDefaultClock(),
3✔
606
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
607
                AcceptAMP:                   cfg.AcceptAMP,
3✔
608
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
609
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
610
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
611
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
612
        }
3✔
613

3✔
614
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
615

3✔
616
        s := &server{
3✔
617
                cfg:            cfg,
3✔
618
                implCfg:        implCfg,
3✔
619
                graphDB:        dbs.GraphDB,
3✔
620
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
621
                addrSource:     addrSource,
3✔
622
                miscDB:         dbs.ChanStateDB,
3✔
623
                invoicesDB:     dbs.InvoiceDB,
3✔
624
                cc:             cc,
3✔
625
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
626
                writePool:      writePool,
3✔
627
                readPool:       readPool,
3✔
628
                chansToRestore: chansToRestore,
3✔
629

3✔
630
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
631
                        cc.ChainNotifier,
3✔
632
                ),
3✔
633
                channelNotifier: channelnotifier.New(
3✔
634
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
635
                ),
3✔
636

3✔
637
                identityECDH:   nodeKeyECDH,
3✔
638
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
639
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
640

3✔
641
                listenAddrs: listenAddrs,
3✔
642

3✔
643
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
644
                // schedule
3✔
645
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
646

3✔
647
                torController: torController,
3✔
648

3✔
649
                persistentPeers:         make(map[string]bool),
3✔
650
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
651
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
652
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
653
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
654
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
655
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
656
                scheduledPeerConnection: make(map[string]func()),
3✔
657
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
658

3✔
659
                peersByPub:                make(map[string]*peer.Brontide),
3✔
660
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
661
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
662
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
663
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
664

3✔
665
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
666

3✔
667
                customMessageServer: subscribe.NewServer(),
3✔
668

3✔
669
                tlsManager: tlsManager,
3✔
670

3✔
671
                featureMgr: featureMgr,
3✔
672
                quit:       make(chan struct{}),
3✔
673
        }
3✔
674

3✔
675
        // Start the low-level services once they are initialized.
3✔
676
        //
3✔
677
        // TODO(yy): break the server startup into four steps,
3✔
678
        // 1. init the low-level services.
3✔
679
        // 2. start the low-level services.
3✔
680
        // 3. init the high-level services.
3✔
681
        // 4. start the high-level services.
3✔
682
        if err := s.startLowLevelServices(); err != nil {
3✔
683
                return nil, err
×
684
        }
×
685

686
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
687
        if err != nil {
3✔
688
                return nil, err
×
689
        }
×
690

691
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
692
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
693
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
694
        )
3✔
695
        s.invoices = invoices.NewRegistry(
3✔
696
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
697
        )
3✔
698

3✔
699
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
700

3✔
701
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
702
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
703

3✔
704
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
705
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
706
                if err != nil {
3✔
707
                        return err
×
708
                }
×
709

710
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
711

3✔
712
                return nil
3✔
713
        }
714

715
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
716
        if err != nil {
3✔
717
                return nil, err
×
718
        }
×
719

720
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
721
                DB:                   dbs.ChanStateDB,
3✔
722
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
723
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
724
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
725
                LocalChannelClose: func(pubKey []byte,
3✔
726
                        request *htlcswitch.ChanClose) {
6✔
727

3✔
728
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
729
                        if err != nil {
3✔
730
                                srvrLog.Errorf("unable to close channel, peer"+
×
731
                                        " with %v id can't be found: %v",
×
732
                                        pubKey, err,
×
733
                                )
×
734
                                return
×
735
                        }
×
736

737
                        peer.HandleLocalCloseChanReqs(request)
3✔
738
                },
739
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
740
                SwitchPackager:         channeldb.NewSwitchPackager(),
741
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
742
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
743
                Notifier:               s.cc.ChainNotifier,
744
                HtlcNotifier:           s.htlcNotifier,
745
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
746
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
747
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
748
                AllowCircularRoute:     cfg.AllowCircularRoute,
749
                RejectHTLC:             cfg.RejectHTLC,
750
                Clock:                  clock.NewDefaultClock(),
751
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
752
                MaxFeeExposure:         thresholdMSats,
753
                SignAliasUpdate:        s.signAliasUpdate,
754
                IsAlias:                aliasmgr.IsAlias,
755
        }, uint32(currentHeight))
756
        if err != nil {
3✔
757
                return nil, err
×
758
        }
×
759
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
3✔
760
                &htlcswitch.InterceptableSwitchConfig{
3✔
761
                        Switch:             s.htlcSwitch,
3✔
762
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
3✔
763
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
3✔
764
                        RequireInterceptor: s.cfg.RequireInterceptor,
3✔
765
                        Notifier:           s.cc.ChainNotifier,
3✔
766
                },
3✔
767
        )
3✔
768
        if err != nil {
3✔
769
                return nil, err
×
770
        }
×
771

772
        s.witnessBeacon = newPreimageBeacon(
3✔
773
                dbs.ChanStateDB.NewWitnessCache(),
3✔
774
                s.interceptableSwitch.ForwardPacket,
3✔
775
        )
3✔
776

3✔
777
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
778
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
779
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
780
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
781
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
782
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
783
                MessageSigner:            s.nodeSigner,
3✔
784
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
785
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
786
                DB:                       s.chanStateDB,
3✔
787
                Graph:                    dbs.GraphDB,
3✔
788
        }
3✔
789

3✔
790
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
791
        if err != nil {
3✔
792
                return nil, err
×
793
        }
×
794
        s.chanStatusMgr = chanStatusMgr
3✔
795

3✔
796
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
797
        // port forwarding for users behind a NAT.
3✔
798
        if cfg.NAT {
3✔
799
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
800

×
801
                discoveryTimeout := time.Duration(10 * time.Second)
×
802

×
803
                ctx, cancel := context.WithTimeout(
×
804
                        context.Background(), discoveryTimeout,
×
805
                )
×
806
                defer cancel()
×
807
                upnp, err := nat.DiscoverUPnP(ctx)
×
808
                if err == nil {
×
809
                        s.natTraversal = upnp
×
810
                } else {
×
811
                        // If we were not able to discover a UPnP enabled device
×
812
                        // on the local network, we'll fall back to attempting
×
813
                        // to discover a NAT-PMP enabled device.
×
814
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
815
                                "device on the local network: %v", err)
×
816

×
817
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
818
                                "enabled device")
×
819

×
820
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
821
                        if err != nil {
×
822
                                err := fmt.Errorf("unable to discover a "+
×
823
                                        "NAT-PMP enabled device on the local "+
×
824
                                        "network: %v", err)
×
825
                                srvrLog.Error(err)
×
826
                                return nil, err
×
827
                        }
×
828

829
                        s.natTraversal = pmp
×
830
                }
831
        }
832

833
        // If we were requested to automatically configure port forwarding,
834
        // we'll use the ports that the server will be listening on.
835
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
3✔
836
        for idx, ip := range cfg.ExternalIPs {
6✔
837
                externalIPStrings[idx] = ip.String()
3✔
838
        }
3✔
839
        if s.natTraversal != nil {
3✔
840
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
841
                for _, listenAddr := range listenAddrs {
×
842
                        // At this point, the listen addresses should have
×
843
                        // already been normalized, so it's safe to ignore the
×
844
                        // errors.
×
845
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
846
                        port, _ := strconv.Atoi(portStr)
×
847

×
848
                        listenPorts = append(listenPorts, uint16(port))
×
849
                }
×
850

851
                ips, err := s.configurePortForwarding(listenPorts...)
×
852
                if err != nil {
×
853
                        srvrLog.Errorf("Unable to automatically set up port "+
×
854
                                "forwarding using %s: %v",
×
855
                                s.natTraversal.Name(), err)
×
856
                } else {
×
857
                        srvrLog.Infof("Automatically set up port forwarding "+
×
858
                                "using %s to advertise external IP",
×
859
                                s.natTraversal.Name())
×
860
                        externalIPStrings = append(externalIPStrings, ips...)
×
861
                }
×
862
        }
863

864
        // If external IP addresses have been specified, add those to the list
865
        // of this server's addresses.
866
        externalIPs, err := lncfg.NormalizeAddresses(
3✔
867
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
868
                cfg.net.ResolveTCPAddr,
3✔
869
        )
3✔
870
        if err != nil {
3✔
871
                return nil, err
×
872
        }
×
873

874
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
3✔
875
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
876

3✔
877
        // We'll now reconstruct a node announcement based on our current
3✔
878
        // configuration so we can send it out as a sort of heart beat within
3✔
879
        // the network.
3✔
880
        //
3✔
881
        // We'll start by parsing the node color from configuration.
3✔
882
        color, err := lncfg.ParseHexColor(cfg.Color)
3✔
883
        if err != nil {
3✔
884
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
885
                return nil, err
×
886
        }
×
887

888
        // If no alias is provided, default to first 10 characters of public
889
        // key.
890
        alias := cfg.Alias
3✔
891
        if alias == "" {
6✔
892
                alias = hex.EncodeToString(serializedPubKey[:10])
3✔
893
        }
3✔
894
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
895
        if err != nil {
3✔
896
                return nil, err
×
897
        }
×
898
        selfNode := &models.LightningNode{
3✔
899
                HaveNodeAnnouncement: true,
3✔
900
                LastUpdate:           time.Now(),
3✔
901
                Addresses:            selfAddrs,
3✔
902
                Alias:                nodeAlias.String(),
3✔
903
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
904
                Color:                color,
3✔
905
        }
3✔
906
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
907

3✔
908
        // Based on the disk representation of the node announcement generated
3✔
909
        // above, we'll generate a node announcement that can go out on the
3✔
910
        // network so we can properly sign it.
3✔
911
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
912
        if err != nil {
3✔
913
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
914
        }
×
915

916
        // With the announcement generated, we'll sign it to properly
917
        // authenticate the message on the network.
918
        authSig, err := netann.SignAnnouncement(
3✔
919
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
3✔
920
        )
3✔
921
        if err != nil {
3✔
922
                return nil, fmt.Errorf("unable to generate signature for "+
×
923
                        "self node announcement: %v", err)
×
924
        }
×
925
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
926
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
927
                selfNode.AuthSigBytes,
3✔
928
        )
3✔
929
        if err != nil {
3✔
930
                return nil, err
×
931
        }
×
932

933
        // Finally, we'll update the representation on disk, and update our
934
        // cached in-memory version as well.
935
        if err := dbs.GraphDB.SetSourceNode(selfNode); err != nil {
3✔
936
                return nil, fmt.Errorf("can't set self node: %w", err)
×
937
        }
×
938
        s.currentNodeAnn = nodeAnn
3✔
939

3✔
940
        // The router will get access to the payment ID sequencer, such that it
3✔
941
        // can generate unique payment IDs.
3✔
942
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
943
        if err != nil {
3✔
944
                return nil, err
×
945
        }
×
946

947
        // Instantiate mission control with config from the sub server.
948
        //
949
        // TODO(joostjager): When we are further in the process of moving to sub
950
        // servers, the mission control instance itself can be moved there too.
951
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
952

3✔
953
        // We only initialize a probability estimator if there's no custom one.
3✔
954
        var estimator routing.Estimator
3✔
955
        if cfg.Estimator != nil {
3✔
956
                estimator = cfg.Estimator
×
957
        } else {
3✔
958
                switch routingConfig.ProbabilityEstimatorType {
3✔
959
                case routing.AprioriEstimatorName:
3✔
960
                        aCfg := routingConfig.AprioriConfig
3✔
961
                        aprioriConfig := routing.AprioriConfig{
3✔
962
                                AprioriHopProbability: aCfg.HopProbability,
3✔
963
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
964
                                AprioriWeight:         aCfg.Weight,
3✔
965
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
966
                        }
3✔
967

3✔
968
                        estimator, err = routing.NewAprioriEstimator(
3✔
969
                                aprioriConfig,
3✔
970
                        )
3✔
971
                        if err != nil {
3✔
972
                                return nil, err
×
973
                        }
×
974

975
                case routing.BimodalEstimatorName:
×
976
                        bCfg := routingConfig.BimodalConfig
×
977
                        bimodalConfig := routing.BimodalConfig{
×
978
                                BimodalNodeWeight: bCfg.NodeWeight,
×
979
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
980
                                        bCfg.Scale,
×
981
                                ),
×
982
                                BimodalDecayTime: bCfg.DecayTime,
×
983
                        }
×
984

×
985
                        estimator, err = routing.NewBimodalEstimator(
×
986
                                bimodalConfig,
×
987
                        )
×
988
                        if err != nil {
×
989
                                return nil, err
×
990
                        }
×
991

992
                default:
×
993
                        return nil, fmt.Errorf("unknown estimator type %v",
×
994
                                routingConfig.ProbabilityEstimatorType)
×
995
                }
996
        }
997

998
        mcCfg := &routing.MissionControlConfig{
3✔
999
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
1000
                Estimator:               estimator,
3✔
1001
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
1002
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
1003
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
1004
        }
3✔
1005

3✔
1006
        s.missionController, err = routing.NewMissionController(
3✔
1007
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
1008
        )
3✔
1009
        if err != nil {
3✔
1010
                return nil, fmt.Errorf("can't create mission control "+
×
1011
                        "manager: %w", err)
×
1012
        }
×
1013
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
1014
                routing.DefaultMissionControlNamespace,
3✔
1015
        )
3✔
1016
        if err != nil {
3✔
1017
                return nil, fmt.Errorf("can't create mission control in the "+
×
1018
                        "default namespace: %w", err)
×
1019
        }
×
1020

1021
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1022
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1023
                int64(routingConfig.AttemptCost),
3✔
1024
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1025
                routingConfig.MinRouteProbability)
3✔
1026

3✔
1027
        pathFindingConfig := routing.PathFindingConfig{
3✔
1028
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1029
                        routingConfig.AttemptCost,
3✔
1030
                ),
3✔
1031
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1032
                MinProbability: routingConfig.MinRouteProbability,
3✔
1033
        }
3✔
1034

3✔
1035
        sourceNode, err := dbs.GraphDB.SourceNode()
3✔
1036
        if err != nil {
3✔
1037
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1038
        }
×
1039
        paymentSessionSource := &routing.SessionSource{
3✔
1040
                GraphSessionFactory: dbs.GraphDB,
3✔
1041
                SourceNode:          sourceNode,
3✔
1042
                MissionControl:      s.defaultMC,
3✔
1043
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1044
                PathFindingConfig:   pathFindingConfig,
3✔
1045
        }
3✔
1046

3✔
1047
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1048

3✔
1049
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1050

3✔
1051
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1052
                cfg.Routing.StrictZombiePruning
3✔
1053

3✔
1054
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1055
                SelfNode:            selfNode.PubKeyBytes,
3✔
1056
                Graph:               dbs.GraphDB,
3✔
1057
                Chain:               cc.ChainIO,
3✔
1058
                ChainView:           cc.ChainView,
3✔
1059
                Notifier:            cc.ChainNotifier,
3✔
1060
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1061
                GraphPruneInterval:  time.Hour,
3✔
1062
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1063
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1064
                StrictZombiePruning: strictPruning,
3✔
1065
                IsAlias:             aliasmgr.IsAlias,
3✔
1066
        })
3✔
1067
        if err != nil {
3✔
1068
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1069
        }
×
1070

1071
        s.chanRouter, err = routing.New(routing.Config{
3✔
1072
                SelfNode:           selfNode.PubKeyBytes,
3✔
1073
                RoutingGraph:       dbs.GraphDB,
3✔
1074
                Chain:              cc.ChainIO,
3✔
1075
                Payer:              s.htlcSwitch,
3✔
1076
                Control:            s.controlTower,
3✔
1077
                MissionControl:     s.defaultMC,
3✔
1078
                SessionSource:      paymentSessionSource,
3✔
1079
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1080
                NextPaymentID:      sequencer.NextID,
3✔
1081
                PathFindingConfig:  pathFindingConfig,
3✔
1082
                Clock:              clock.NewDefaultClock(),
3✔
1083
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1084
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1085
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1086
        })
3✔
1087
        if err != nil {
3✔
1088
                return nil, fmt.Errorf("can't create router: %w", err)
×
1089
        }
×
1090

1091
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1092
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1093
        if err != nil {
3✔
1094
                return nil, err
×
1095
        }
×
1096
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1097
        if err != nil {
3✔
1098
                return nil, err
×
1099
        }
×
1100

1101
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1102

3✔
1103
        s.authGossiper = discovery.New(discovery.Config{
3✔
1104
                Graph:                 s.graphBuilder,
3✔
1105
                ChainIO:               s.cc.ChainIO,
3✔
1106
                Notifier:              s.cc.ChainNotifier,
3✔
1107
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1108
                Broadcast:             s.BroadcastMessage,
3✔
1109
                ChanSeries:            chanSeries,
3✔
1110
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1111
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1112
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1113
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1114
                        error) {
3✔
1115

×
1116
                        return s.genNodeAnnouncement(nil)
×
1117
                },
×
1118
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1119
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1120
                RetransmitTicker:        ticker.New(time.Minute * 30),
1121
                RebroadcastInterval:     time.Hour * 24,
1122
                WaitingProofStore:       waitingProofStore,
1123
                MessageStore:            gossipMessageStore,
1124
                AnnSigner:               s.nodeSigner,
1125
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1126
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1127
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1128
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1129
                MinimumBatchSize:        10,
1130
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1131
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1132
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1133
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1134
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1135
                IsAlias:                 aliasmgr.IsAlias,
1136
                SignAliasUpdate:         s.signAliasUpdate,
1137
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1138
                GetAlias:                s.aliasMgr.GetPeerAlias,
1139
                FindChannel:             s.findChannel,
1140
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1141
                ScidCloser:              scidCloserMan,
1142
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1143
        }, nodeKeyDesc)
1144

1145
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1146
        //nolint:ll
3✔
1147
        s.localChanMgr = &localchans.Manager{
3✔
1148
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1149
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1150
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
3✔
1151
                        *models.ChannelEdgePolicy) error) error {
6✔
1152

3✔
1153
                        return s.graphDB.ForEachNodeChannel(selfVertex,
3✔
1154
                                func(_ kvdb.RTx, c *models.ChannelEdgeInfo,
3✔
1155
                                        e *models.ChannelEdgePolicy,
3✔
1156
                                        _ *models.ChannelEdgePolicy) error {
6✔
1157

3✔
1158
                                        // NOTE: The invoked callback here may
3✔
1159
                                        // receive a nil channel policy.
3✔
1160
                                        return cb(c, e)
3✔
1161
                                },
3✔
1162
                        )
1163
                },
1164
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1165
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1166
                FetchChannel:              s.chanStateDB.FetchChannel,
1167
                AddEdge: func(edge *models.ChannelEdgeInfo) error {
×
1168
                        return s.graphBuilder.AddEdge(edge)
×
1169
                },
×
1170
        }
1171

1172
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1173
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1174
        )
3✔
1175
        if err != nil {
3✔
1176
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1177
                return nil, err
×
1178
        }
×
1179

1180
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1181
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1182
        )
3✔
1183
        if err != nil {
3✔
1184
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1185
                return nil, err
×
1186
        }
×
1187

1188
        aggregator := sweep.NewBudgetAggregator(
3✔
1189
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1190
                s.implCfg.AuxSweeper,
3✔
1191
        )
3✔
1192

3✔
1193
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1194
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1195
                Wallet:     cc.Wallet,
3✔
1196
                Estimator:  cc.FeeEstimator,
3✔
1197
                Notifier:   cc.ChainNotifier,
3✔
1198
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1199
        })
3✔
1200

3✔
1201
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1202
                FeeEstimator: cc.FeeEstimator,
3✔
1203
                GenSweepScript: newSweepPkScriptGen(
3✔
1204
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1205
                ),
3✔
1206
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1207
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1208
                Mempool:              cc.MempoolNotifier,
3✔
1209
                Notifier:             cc.ChainNotifier,
3✔
1210
                Store:                sweeperStore,
3✔
1211
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1212
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1213
                Aggregator:           aggregator,
3✔
1214
                Publisher:            s.txPublisher,
3✔
1215
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1216
        })
3✔
1217

3✔
1218
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1219
                ChainIO:             cc.ChainIO,
3✔
1220
                ConfDepth:           1,
3✔
1221
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1222
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1223
                Notifier:            cc.ChainNotifier,
3✔
1224
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1225
                Store:               utxnStore,
3✔
1226
                SweepInput:          s.sweeper.SweepInput,
3✔
1227
                Budget:              s.cfg.Sweeper.Budget,
3✔
1228
        })
3✔
1229

3✔
1230
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1231
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1232
                closureType contractcourt.ChannelCloseType) {
6✔
1233
                // TODO(conner): Properly respect the update and error channels
3✔
1234
                // returned by CloseLink.
3✔
1235

3✔
1236
                // Instruct the switch to close the channel.  Provide no close out
3✔
1237
                // delivery script or target fee per kw because user input is not
3✔
1238
                // available when the remote peer closes the channel.
3✔
1239
                s.htlcSwitch.CloseLink(chanPoint, closureType, 0, 0, nil)
3✔
1240
        }
3✔
1241

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

3✔
1246
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1247
                &contractcourt.BreachConfig{
3✔
1248
                        CloseLink: closeLink,
3✔
1249
                        DB:        s.chanStateDB,
3✔
1250
                        Estimator: s.cc.FeeEstimator,
3✔
1251
                        GenSweepScript: newSweepPkScriptGen(
3✔
1252
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1253
                        ),
3✔
1254
                        Notifier:           cc.ChainNotifier,
3✔
1255
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1256
                        ContractBreaches:   contractBreaches,
3✔
1257
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1258
                        Store: contractcourt.NewRetributionStore(
3✔
1259
                                dbs.ChanStateDB,
3✔
1260
                        ),
3✔
1261
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1262
                },
3✔
1263
        )
3✔
1264

3✔
1265
        //nolint:ll
3✔
1266
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1267
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1268
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1269
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1270
                NewSweepAddr: func() ([]byte, error) {
3✔
1271
                        addr, err := newSweepPkScriptGen(
×
1272
                                cc.Wallet, netParams,
×
1273
                        )().Unpack()
×
1274
                        if err != nil {
×
1275
                                return nil, err
×
1276
                        }
×
1277

1278
                        return addr.DeliveryAddress, nil
×
1279
                },
1280
                PublishTx: cc.Wallet.PublishTransaction,
1281
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1282
                        for _, msg := range msgs {
6✔
1283
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1284
                                if err != nil {
3✔
1285
                                        return err
×
1286
                                }
×
1287
                        }
1288
                        return nil
3✔
1289
                },
1290
                IncubateOutputs: func(chanPoint wire.OutPoint,
1291
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1292
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1293
                        broadcastHeight uint32,
1294
                        deadlineHeight fn.Option[int32]) error {
3✔
1295

3✔
1296
                        return s.utxoNursery.IncubateOutputs(
3✔
1297
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1298
                                broadcastHeight, deadlineHeight,
3✔
1299
                        )
3✔
1300
                },
3✔
1301
                PreimageDB:   s.witnessBeacon,
1302
                Notifier:     cc.ChainNotifier,
1303
                Mempool:      cc.MempoolNotifier,
1304
                Signer:       cc.Wallet.Cfg.Signer,
1305
                FeeEstimator: cc.FeeEstimator,
1306
                ChainIO:      cc.ChainIO,
1307
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1308
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1309
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1310
                        return nil
3✔
1311
                },
3✔
1312
                IsOurAddress: cc.Wallet.IsOurAddress,
1313
                ContractBreach: func(chanPoint wire.OutPoint,
1314
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1315

3✔
1316
                        // processACK will handle the BreachArbitrator ACKing
3✔
1317
                        // the event.
3✔
1318
                        finalErr := make(chan error, 1)
3✔
1319
                        processACK := func(brarErr error) {
6✔
1320
                                if brarErr != nil {
3✔
1321
                                        finalErr <- brarErr
×
1322
                                        return
×
1323
                                }
×
1324

1325
                                // If the BreachArbitrator successfully handled
1326
                                // the event, we can signal that the handoff
1327
                                // was successful.
1328
                                finalErr <- nil
3✔
1329
                        }
1330

1331
                        event := &contractcourt.ContractBreachEvent{
3✔
1332
                                ChanPoint:         chanPoint,
3✔
1333
                                ProcessACK:        processACK,
3✔
1334
                                BreachRetribution: breachRet,
3✔
1335
                        }
3✔
1336

3✔
1337
                        // Send the contract breach event to the
3✔
1338
                        // BreachArbitrator.
3✔
1339
                        select {
3✔
1340
                        case contractBreaches <- event:
3✔
1341
                        case <-s.quit:
×
1342
                                return ErrServerShuttingDown
×
1343
                        }
1344

1345
                        // We'll wait for a final error to be available from
1346
                        // the BreachArbitrator.
1347
                        select {
3✔
1348
                        case err := <-finalErr:
3✔
1349
                                return err
3✔
1350
                        case <-s.quit:
×
1351
                                return ErrServerShuttingDown
×
1352
                        }
1353
                },
1354
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1355
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1356
                },
3✔
1357
                Sweeper:                       s.sweeper,
1358
                Registry:                      s.invoices,
1359
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1360
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1361
                OnionProcessor:                s.sphinx,
1362
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1363
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1364
                Clock:                         clock.NewDefaultClock(),
1365
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1366
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1367
                HtlcNotifier:                  s.htlcNotifier,
1368
                Budget:                        *s.cfg.Sweeper.Budget,
1369

1370
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1371
                QueryIncomingCircuit: func(
1372
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1373

3✔
1374
                        // Get the circuit map.
3✔
1375
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1376

3✔
1377
                        // Lookup the outgoing circuit.
3✔
1378
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1379
                        if pc == nil {
5✔
1380
                                return nil
2✔
1381
                        }
2✔
1382

1383
                        return &pc.Incoming
3✔
1384
                },
1385
                AuxLeafStore: implCfg.AuxLeafStore,
1386
                AuxSigner:    implCfg.AuxSigner,
1387
                AuxResolver:  implCfg.AuxContractResolver,
1388
        }, dbs.ChanStateDB)
1389

1390
        // Select the configuration and funding parameters for Bitcoin.
1391
        chainCfg := cfg.Bitcoin
3✔
1392
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1393
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1394

3✔
1395
        var chanIDSeed [32]byte
3✔
1396
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1397
                return nil, err
×
1398
        }
×
1399

1400
        // Wrap the DeleteChannelEdges method so that the funding manager can
1401
        // use it without depending on several layers of indirection.
1402
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1403
                *models.ChannelEdgePolicy, error) {
6✔
1404

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

1418
                // Grab our key to find our policy.
1419
                var ourKey [33]byte
3✔
1420
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1421

3✔
1422
                var ourPolicy *models.ChannelEdgePolicy
3✔
1423
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1424
                        ourPolicy = e1
3✔
1425
                } else {
6✔
1426
                        ourPolicy = e2
3✔
1427
                }
3✔
1428

1429
                if ourPolicy == nil {
3✔
1430
                        // Something is wrong, so return an error.
×
1431
                        return nil, fmt.Errorf("we don't have an edge")
×
1432
                }
×
1433

1434
                err = s.graphDB.DeleteChannelEdges(
3✔
1435
                        false, false, scid.ToUint64(),
3✔
1436
                )
3✔
1437
                return ourPolicy, err
3✔
1438
        }
1439

1440
        // For the reservationTimeout and the zombieSweeperInterval different
1441
        // values are set in case we are in a dev environment so enhance test
1442
        // capacilities.
1443
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1444
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1445

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

3✔
1456
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1457
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1458

3✔
1459
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1460
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1461
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1462
        }
3✔
1463

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

3✔
1482
                        return s.genNodeAnnouncement(nil)
3✔
1483
                },
3✔
1484
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1485
                NotifyWhenOnline:     s.NotifyWhenOnline,
1486
                TempChanIDSeed:       chanIDSeed,
1487
                FindChannel:          s.findChannel,
1488
                DefaultRoutingPolicy: cc.RoutingPolicy,
1489
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1490
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1491
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1492
                        // For large channels we increase the number
3✔
1493
                        // of confirmations we require for the
3✔
1494
                        // channel to be considered open. As it is
3✔
1495
                        // always the responder that gets to choose
3✔
1496
                        // value, the pushAmt is value being pushed
3✔
1497
                        // to us. This means we have more to lose
3✔
1498
                        // in the case this gets re-orged out, and
3✔
1499
                        // we will require more confirmations before
3✔
1500
                        // we consider it open.
3✔
1501

3✔
1502
                        // In case the user has explicitly specified
3✔
1503
                        // a default value for the number of
3✔
1504
                        // confirmations, we use it.
3✔
1505
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1506
                        if defaultConf != 0 {
6✔
1507
                                return defaultConf
3✔
1508
                        }
3✔
1509

1510
                        minConf := uint64(3)
×
1511
                        maxConf := uint64(6)
×
1512

×
1513
                        // If this is a wumbo channel, then we'll require the
×
1514
                        // max amount of confirmations.
×
1515
                        if chanAmt > MaxFundingAmount {
×
1516
                                return uint16(maxConf)
×
1517
                        }
×
1518

1519
                        // If not we return a value scaled linearly
1520
                        // between 3 and 6, depending on channel size.
1521
                        // TODO(halseth): Use 1 as minimum?
1522
                        maxChannelSize := uint64(
×
1523
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1524
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1525
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1526
                        if conf < minConf {
×
1527
                                conf = minConf
×
1528
                        }
×
1529
                        if conf > maxConf {
×
1530
                                conf = maxConf
×
1531
                        }
×
1532
                        return uint16(conf)
×
1533
                },
1534
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1535
                        // We scale the remote CSV delay (the time the
3✔
1536
                        // remote have to claim funds in case of a unilateral
3✔
1537
                        // close) linearly from minRemoteDelay blocks
3✔
1538
                        // for small channels, to maxRemoteDelay blocks
3✔
1539
                        // for channels of size MaxFundingAmount.
3✔
1540

3✔
1541
                        // In case the user has explicitly specified
3✔
1542
                        // a default value for the remote delay, we
3✔
1543
                        // use it.
3✔
1544
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1545
                        if defaultDelay > 0 {
6✔
1546
                                return defaultDelay
3✔
1547
                        }
3✔
1548

1549
                        // If this is a wumbo channel, then we'll require the
1550
                        // max value.
1551
                        if chanAmt > MaxFundingAmount {
×
1552
                                return maxRemoteDelay
×
1553
                        }
×
1554

1555
                        // If not we scale according to channel size.
1556
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1557
                                chanAmt / MaxFundingAmount)
×
1558
                        if delay < minRemoteDelay {
×
1559
                                delay = minRemoteDelay
×
1560
                        }
×
1561
                        if delay > maxRemoteDelay {
×
1562
                                delay = maxRemoteDelay
×
1563
                        }
×
1564
                        return delay
×
1565
                },
1566
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1567
                        peerKey *btcec.PublicKey) error {
3✔
1568

3✔
1569
                        // First, we'll mark this new peer as a persistent peer
3✔
1570
                        // for re-connection purposes. If the peer is not yet
3✔
1571
                        // tracked or the user hasn't requested it to be perm,
3✔
1572
                        // we'll set false to prevent the server from continuing
3✔
1573
                        // to connect to this peer even if the number of
3✔
1574
                        // channels with this peer is zero.
3✔
1575
                        s.mu.Lock()
3✔
1576
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1577
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1578
                                s.persistentPeers[pubStr] = false
3✔
1579
                        }
3✔
1580
                        s.mu.Unlock()
3✔
1581

3✔
1582
                        // With that taken care of, we'll send this channel to
3✔
1583
                        // the chain arb so it can react to on-chain events.
3✔
1584
                        return s.chainArb.WatchNewChannel(channel)
3✔
1585
                },
1586
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1587
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1588
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1589
                },
3✔
1590
                RequiredRemoteChanReserve: func(chanAmt,
1591
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1592

3✔
1593
                        // By default, we'll require the remote peer to maintain
3✔
1594
                        // at least 1% of the total channel capacity at all
3✔
1595
                        // times. If this value ends up dipping below the dust
3✔
1596
                        // limit, then we'll use the dust limit itself as the
3✔
1597
                        // reserve as required by BOLT #2.
3✔
1598
                        reserve := chanAmt / 100
3✔
1599
                        if reserve < dustLimit {
6✔
1600
                                reserve = dustLimit
3✔
1601
                        }
3✔
1602

1603
                        return reserve
3✔
1604
                },
1605
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1606
                        // By default, we'll allow the remote peer to fully
3✔
1607
                        // utilize the full bandwidth of the channel, minus our
3✔
1608
                        // required reserve.
3✔
1609
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1610
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1611
                },
3✔
1612
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1613
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1614
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1615
                        }
3✔
1616

1617
                        // By default, we'll permit them to utilize the full
1618
                        // channel bandwidth.
1619
                        return uint16(input.MaxHTLCNumber / 2)
×
1620
                },
1621
                ZombieSweeperInterval:         zombieSweeperInterval,
1622
                ReservationTimeout:            reservationTimeout,
1623
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1624
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1625
                MaxPendingChannels:            cfg.MaxPendingChannels,
1626
                RejectPush:                    cfg.RejectPush,
1627
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1628
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
1629
                OpenChannelPredicate:          chanPredicate,
1630
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
1631
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1632
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1633
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1634
                DeleteAliasEdge:      deleteAliasEdge,
1635
                AliasManager:         s.aliasMgr,
1636
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1637
                AuxFundingController: implCfg.AuxFundingController,
1638
                AuxSigner:            implCfg.AuxSigner,
1639
                AuxResolver:          implCfg.AuxContractResolver,
1640
        })
1641
        if err != nil {
3✔
1642
                return nil, err
×
1643
        }
×
1644

1645
        // Next, we'll assemble the sub-system that will maintain an on-disk
1646
        // static backup of the latest channel state.
1647
        chanNotifier := &channelNotifier{
3✔
1648
                chanNotifier: s.channelNotifier,
3✔
1649
                addrs:        s.addrSource,
3✔
1650
        }
3✔
1651
        backupFile := chanbackup.NewMultiFile(
3✔
1652
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1653
        )
3✔
1654
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1655
                s.chanStateDB, s.addrSource,
3✔
1656
        )
3✔
1657
        if err != nil {
3✔
1658
                return nil, err
×
1659
        }
×
1660
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1661
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1662
        )
3✔
1663
        if err != nil {
3✔
1664
                return nil, err
×
1665
        }
×
1666

1667
        // Assemble a peer notifier which will provide clients with subscriptions
1668
        // to peer online and offline events.
1669
        s.peerNotifier = peernotifier.New()
3✔
1670

3✔
1671
        // Create a channel event store which monitors all open channels.
3✔
1672
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1673
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1674
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1675
                },
3✔
1676
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1677
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1678
                },
3✔
1679
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1680
                Clock:           clock.NewDefaultClock(),
1681
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1682
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1683
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1684
        })
1685

1686
        if cfg.WtClient.Active {
6✔
1687
                policy := wtpolicy.DefaultPolicy()
3✔
1688
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1689

3✔
1690
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1691
                // protocol operations on sat/kw.
3✔
1692
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1693
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1694
                )
3✔
1695

3✔
1696
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1697

3✔
1698
                if err := policy.Validate(); err != nil {
3✔
1699
                        return nil, err
×
1700
                }
×
1701

1702
                // authDial is the wrapper around the btrontide.Dial for the
1703
                // watchtower.
1704
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1705
                        netAddr *lnwire.NetAddress,
3✔
1706
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1707

3✔
1708
                        return brontide.Dial(
3✔
1709
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1710
                        )
3✔
1711
                }
3✔
1712

1713
                // buildBreachRetribution is a call-back that can be used to
1714
                // query the BreachRetribution info and channel type given a
1715
                // channel ID and commitment height.
1716
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1717
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1718
                        channeldb.ChannelType, error) {
6✔
1719

3✔
1720
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1721
                                nil, chanID,
3✔
1722
                        )
3✔
1723
                        if err != nil {
3✔
1724
                                return nil, 0, err
×
1725
                        }
×
1726

1727
                        br, err := lnwallet.NewBreachRetribution(
3✔
1728
                                channel, commitHeight, 0, nil,
3✔
1729
                                implCfg.AuxLeafStore,
3✔
1730
                                implCfg.AuxContractResolver,
3✔
1731
                        )
3✔
1732
                        if err != nil {
3✔
1733
                                return nil, 0, err
×
1734
                        }
×
1735

1736
                        return br, channel.ChanType, nil
3✔
1737
                }
1738

1739
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1740

3✔
1741
                // Copy the policy for legacy channels and set the blob flag
3✔
1742
                // signalling support for anchor channels.
3✔
1743
                anchorPolicy := policy
3✔
1744
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1745

3✔
1746
                // Copy the policy for legacy channels and set the blob flag
3✔
1747
                // signalling support for taproot channels.
3✔
1748
                taprootPolicy := policy
3✔
1749
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1750
                        blob.FlagTaprootChannel,
3✔
1751
                )
3✔
1752

3✔
1753
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1754
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1755
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1756
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1757
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1758
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1759
                                error) {
6✔
1760

3✔
1761
                                return s.channelNotifier.
3✔
1762
                                        SubscribeChannelEvents()
3✔
1763
                        },
3✔
1764
                        Signer: cc.Wallet.Cfg.Signer,
1765
                        NewAddress: func() ([]byte, error) {
3✔
1766
                                addr, err := newSweepPkScriptGen(
3✔
1767
                                        cc.Wallet, netParams,
3✔
1768
                                )().Unpack()
3✔
1769
                                if err != nil {
3✔
1770
                                        return nil, err
×
1771
                                }
×
1772

1773
                                return addr.DeliveryAddress, nil
3✔
1774
                        },
1775
                        SecretKeyRing:      s.cc.KeyRing,
1776
                        Dial:               cfg.net.Dial,
1777
                        AuthDial:           authDial,
1778
                        DB:                 dbs.TowerClientDB,
1779
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1780
                        MinBackoff:         10 * time.Second,
1781
                        MaxBackoff:         5 * time.Minute,
1782
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1783
                }, policy, anchorPolicy, taprootPolicy)
1784
                if err != nil {
3✔
1785
                        return nil, err
×
1786
                }
×
1787
        }
1788

1789
        if len(cfg.ExternalHosts) != 0 {
3✔
1790
                advertisedIPs := make(map[string]struct{})
×
1791
                for _, addr := range s.currentNodeAnn.Addresses {
×
1792
                        advertisedIPs[addr.String()] = struct{}{}
×
1793
                }
×
1794

1795
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1796
                        Hosts:         cfg.ExternalHosts,
×
1797
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1798
                        LookupHost: func(host string) (net.Addr, error) {
×
1799
                                return lncfg.ParseAddressString(
×
1800
                                        host, strconv.Itoa(defaultPeerPort),
×
1801
                                        cfg.net.ResolveTCPAddr,
×
1802
                                )
×
1803
                        },
×
1804
                        AdvertisedIPs: advertisedIPs,
1805
                        AnnounceNewIPs: netann.IPAnnouncer(
1806
                                func(modifier ...netann.NodeAnnModifier) (
1807
                                        lnwire.NodeAnnouncement, error) {
×
1808

×
1809
                                        return s.genNodeAnnouncement(
×
1810
                                                nil, modifier...,
×
1811
                                        )
×
1812
                                }),
×
1813
                })
1814
        }
1815

1816
        // Create liveness monitor.
1817
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1818

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

3✔
1837
        // Finally, register the subsystems in blockbeat.
3✔
1838
        s.registerBlockConsumers()
3✔
1839

3✔
1840
        return s, nil
3✔
1841
}
1842

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

3✔
1848
        switch c := cfg.Estimator.Config().(type) {
3✔
1849
        case routing.AprioriConfig:
3✔
1850
                routerCfg.ProbabilityEstimatorType =
3✔
1851
                        routing.AprioriEstimatorName
3✔
1852

3✔
1853
                targetCfg := routerCfg.AprioriConfig
3✔
1854
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1855
                targetCfg.Weight = c.AprioriWeight
3✔
1856
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1857
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1858

1859
        case routing.BimodalConfig:
3✔
1860
                routerCfg.ProbabilityEstimatorType =
3✔
1861
                        routing.BimodalEstimatorName
3✔
1862

3✔
1863
                targetCfg := routerCfg.BimodalConfig
3✔
1864
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1865
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1866
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1867
        }
1868

1869
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1870
}
1871

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

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

3✔
1897
        data, err := u.DataToSign()
3✔
1898
        if err != nil {
3✔
1899
                return nil, err
×
1900
        }
×
1901

1902
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1903
}
1904

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

3✔
1918
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1919
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1920
                srvrLog.Info("Disabling chain backend checks for " +
×
1921
                        "nochainbackend mode")
×
1922

×
1923
                chainBackendAttempts = 0
×
1924
        }
×
1925

1926
        chainHealthCheck := healthcheck.NewObservation(
3✔
1927
                "chain backend",
3✔
1928
                cc.HealthCheck,
3✔
1929
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1930
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1931
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1932
                chainBackendAttempts,
3✔
1933
        )
3✔
1934

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

1945
                        // If we have more free space than we require,
1946
                        // we return a nil error.
1947
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1948
                                return nil
×
1949
                        }
×
1950

1951
                        return fmt.Errorf("require: %v free space, got: %v",
×
1952
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1953
                                free)
×
1954
                },
1955
                cfg.HealthChecks.DiskCheck.Interval,
1956
                cfg.HealthChecks.DiskCheck.Timeout,
1957
                cfg.HealthChecks.DiskCheck.Backoff,
1958
                cfg.HealthChecks.DiskCheck.Attempts,
1959
        )
1960

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

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

1985
        checks := []*healthcheck.Observation{
3✔
1986
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
1987
        }
3✔
1988

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

2007
        // If remote signing is enabled, add the healthcheck for the remote
2008
        // signing RPC interface.
2009
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2010
                // Because we have two cascading timeouts here, we need to add
3✔
2011
                // some slack to the "outer" one of them in case the "inner"
3✔
2012
                // returns exactly on time.
3✔
2013
                overhead := time.Millisecond * 10
3✔
2014

3✔
2015
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2016
                        "remote signer connection",
3✔
2017
                        rpcwallet.HealthCheck(
3✔
2018
                                s.cfg.RemoteSigner,
3✔
2019

3✔
2020
                                // For the health check we might to be even
3✔
2021
                                // stricter than the initial/normal connect, so
3✔
2022
                                // we use the health check timeout here.
3✔
2023
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2024
                        ),
3✔
2025
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2026
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2027
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2028
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2029
                )
3✔
2030
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2031
        }
3✔
2032

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

×
2051
                                leader, err := leaderElector.IsLeader(
×
2052
                                        timeoutCtx,
×
2053
                                )
×
2054
                                if err != nil {
×
2055
                                        return fmt.Errorf("unable to check if "+
×
2056
                                                "still leader: %v", err)
×
2057
                                }
×
2058

2059
                                if !leader {
×
2060
                                        srvrLog.Debug("Not the current leader")
×
2061
                                        return fmt.Errorf("not the current " +
×
2062
                                                "leader")
×
2063
                                }
×
2064

2065
                                return nil
×
2066
                        },
2067
                        cfg.HealthChecks.LeaderCheck.Interval,
2068
                        cfg.HealthChecks.LeaderCheck.Timeout,
2069
                        cfg.HealthChecks.LeaderCheck.Backoff,
2070
                        cfg.HealthChecks.LeaderCheck.Attempts,
2071
                )
2072

2073
                checks = append(checks, leaderCheck)
×
2074
        }
2075

2076
        // If we have not disabled all of our health checks, we create a
2077
        // liveness monitor with our configured checks.
2078
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2079
                &healthcheck.Config{
3✔
2080
                        Checks:   checks,
3✔
2081
                        Shutdown: srvrLog.Criticalf,
3✔
2082
                },
3✔
2083
        )
3✔
2084
}
2085

2086
// Started returns true if the server has been started, and false otherwise.
2087
// NOTE: This function is safe for concurrent access.
2088
func (s *server) Started() bool {
3✔
2089
        return atomic.LoadInt32(&s.active) != 0
3✔
2090
}
3✔
2091

2092
// cleaner is used to aggregate "cleanup" functions during an operation that
2093
// starts several subsystems. In case one of the subsystem fails to start
2094
// and a proper resource cleanup is required, the "run" method achieves this
2095
// by running all these added "cleanup" functions.
2096
type cleaner []func() error
2097

2098
// add is used to add a cleanup function to be called when
2099
// the run function is executed.
2100
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2101
        return append(c, cleanup)
3✔
2102
}
3✔
2103

2104
// run is used to run all the previousely added cleanup functions.
2105
func (c cleaner) run() {
×
2106
        for i := len(c) - 1; i >= 0; i-- {
×
2107
                if err := c[i](); err != nil {
×
2108
                        srvrLog.Infof("Cleanup failed: %v", err)
×
2109
                }
×
2110
        }
2111
}
2112

2113
// startLowLevelServices starts the low-level services of the server. These
2114
// services must be started successfully before running the main server. The
2115
// services are,
2116
// 1. the chain notifier.
2117
//
2118
// TODO(yy): identify and add more low-level services here.
2119
func (s *server) startLowLevelServices() error {
3✔
2120
        var startErr error
3✔
2121

3✔
2122
        cleanup := cleaner{}
3✔
2123

3✔
2124
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2125
        if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2126
                startErr = err
×
2127
        }
×
2128

2129
        if startErr != nil {
3✔
2130
                cleanup.run()
×
2131
        }
×
2132

2133
        return startErr
3✔
2134
}
2135

2136
// Start starts the main daemon server, all requested listeners, and any helper
2137
// goroutines.
2138
// NOTE: This function is safe for concurrent access.
2139
//
2140
//nolint:funlen
2141
func (s *server) Start() error {
3✔
2142
        // Get the current blockbeat.
3✔
2143
        beat, err := s.getStartingBeat()
3✔
2144
        if err != nil {
3✔
2145
                return err
×
2146
        }
×
2147

2148
        var startErr error
3✔
2149

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

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

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

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

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

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

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

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

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

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

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

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

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

2241
                cleanup = cleanup.add(s.sweeper.Stop)
3✔
2242
                if err := s.sweeper.Start(beat); err != nil {
3✔
2243
                        startErr = err
×
2244
                        return
×
2245
                }
×
2246

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

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

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

2265
                // htlcSwitch must be started before chainArb since the latter
2266
                // relies on htlcSwitch to deliver resolution message upon
2267
                // start.
2268
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2269
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2270
                        startErr = err
×
2271
                        return
×
2272
                }
×
2273

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

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

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

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

2298
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2299
                if err := s.chanRouter.Start(); err != nil {
3✔
2300
                        startErr = err
×
2301
                        return
×
2302
                }
×
2303
                // The authGossiper depends on the chanRouter and therefore
2304
                // should be started after it.
2305
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2306
                if err := s.authGossiper.Start(); err != nil {
3✔
2307
                        startErr = err
×
2308
                        return
×
2309
                }
×
2310

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

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

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

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

2335
                cleanup.add(func() error {
3✔
2336
                        s.missionController.StopStoreTickers()
×
2337
                        return nil
×
2338
                })
×
2339
                s.missionController.RunStoreTickers()
3✔
2340

3✔
2341
                // Before we start the connMgr, we'll check to see if we have
3✔
2342
                // any backups to recover. We do this now as we want to ensure
3✔
2343
                // that have all the information we need to handle channel
3✔
2344
                // recovery _before_ we even accept connections from any peers.
3✔
2345
                chanRestorer := &chanDBRestorer{
3✔
2346
                        db:         s.chanStateDB,
3✔
2347
                        secretKeys: s.cc.KeyRing,
3✔
2348
                        chainArb:   s.chainArb,
3✔
2349
                }
3✔
2350
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2351
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2352
                                s.chansToRestore.PackedSingleChanBackups,
×
2353
                                s.cc.KeyRing, chanRestorer, s,
×
2354
                        )
×
2355
                        if err != nil {
×
2356
                                startErr = fmt.Errorf("unable to unpack single "+
×
2357
                                        "backups: %v", err)
×
2358
                                return
×
2359
                        }
×
2360
                }
2361
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2362
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2363
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2364
                                s.cc.KeyRing, chanRestorer, s,
3✔
2365
                        )
3✔
2366
                        if err != nil {
3✔
2367
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2368
                                        "backup: %v", err)
×
2369
                                return
×
2370
                        }
×
2371
                }
2372

2373
                // chanSubSwapper must be started after the `channelNotifier`
2374
                // because it depends on channel events as a synchronization
2375
                // point.
2376
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2377
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2378
                        startErr = err
×
2379
                        return
×
2380
                }
×
2381

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

2390
                if s.natTraversal != nil {
3✔
2391
                        s.wg.Add(1)
×
2392
                        go s.watchExternalIP()
×
2393
                }
×
2394

2395
                // Start connmgr last to prevent connections before init.
2396
                cleanup = cleanup.add(func() error {
3✔
2397
                        s.connMgr.Stop()
×
2398
                        return nil
×
2399
                })
×
2400
                s.connMgr.Start()
3✔
2401

3✔
2402
                // If peers are specified as a config option, we'll add those
3✔
2403
                // peers first.
3✔
2404
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2405
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2406
                                peerAddrCfg,
3✔
2407
                        )
3✔
2408
                        if err != nil {
3✔
2409
                                startErr = fmt.Errorf("unable to parse peer "+
×
2410
                                        "pubkey from config: %v", err)
×
2411
                                return
×
2412
                        }
×
2413
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2414
                        if err != nil {
3✔
2415
                                startErr = fmt.Errorf("unable to parse peer "+
×
2416
                                        "address provided as a config option: "+
×
2417
                                        "%v", err)
×
2418
                                return
×
2419
                        }
×
2420

2421
                        peerAddr := &lnwire.NetAddress{
3✔
2422
                                IdentityKey: parsedPubkey,
3✔
2423
                                Address:     addr,
3✔
2424
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2425
                        }
3✔
2426

3✔
2427
                        err = s.ConnectToPeer(
3✔
2428
                                peerAddr, true,
3✔
2429
                                s.cfg.ConnectionTimeout,
3✔
2430
                        )
3✔
2431
                        if err != nil {
3✔
2432
                                startErr = fmt.Errorf("unable to connect to "+
×
2433
                                        "peer address provided as a config "+
×
2434
                                        "option: %v", err)
×
2435
                                return
×
2436
                        }
×
2437
                }
2438

2439
                // Subscribe to NodeAnnouncements that advertise new addresses
2440
                // our persistent peers.
2441
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2442
                        startErr = err
×
2443
                        return
×
2444
                }
×
2445

2446
                // With all the relevant sub-systems started, we'll now attempt
2447
                // to establish persistent connections to our direct channel
2448
                // collaborators within the network. Before doing so however,
2449
                // we'll prune our set of link nodes found within the database
2450
                // to ensure we don't reconnect to any nodes we no longer have
2451
                // open channels with.
2452
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2453
                        startErr = err
×
2454
                        return
×
2455
                }
×
2456
                if err := s.establishPersistentConnections(); err != nil {
3✔
2457
                        startErr = err
×
2458
                        return
×
2459
                }
×
2460

2461
                // setSeedList is a helper function that turns multiple DNS seed
2462
                // server tuples from the command line or config file into the
2463
                // data structure we need and does a basic formal sanity check
2464
                // in the process.
2465
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2466
                        if len(tuples) == 0 {
×
2467
                                return
×
2468
                        }
×
2469

2470
                        result := make([][2]string, len(tuples))
×
2471
                        for idx, tuple := range tuples {
×
2472
                                tuple = strings.TrimSpace(tuple)
×
2473
                                if len(tuple) == 0 {
×
2474
                                        return
×
2475
                                }
×
2476

2477
                                servers := strings.Split(tuple, ",")
×
2478
                                if len(servers) > 2 || len(servers) == 0 {
×
2479
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2480
                                                "seed tuple: %v", servers)
×
2481
                                        return
×
2482
                                }
×
2483

2484
                                copy(result[idx][:], servers)
×
2485
                        }
2486

2487
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2488
                }
2489

2490
                // Let users overwrite the DNS seed nodes. We only allow them
2491
                // for bitcoin mainnet/testnet/signet.
2492
                if s.cfg.Bitcoin.MainNet {
3✔
2493
                        setSeedList(
×
2494
                                s.cfg.Bitcoin.DNSSeeds,
×
2495
                                chainreg.BitcoinMainnetGenesis,
×
2496
                        )
×
2497
                }
×
2498
                if s.cfg.Bitcoin.TestNet3 {
3✔
2499
                        setSeedList(
×
2500
                                s.cfg.Bitcoin.DNSSeeds,
×
2501
                                chainreg.BitcoinTestnetGenesis,
×
2502
                        )
×
2503
                }
×
2504
                if s.cfg.Bitcoin.SigNet {
3✔
2505
                        setSeedList(
×
2506
                                s.cfg.Bitcoin.DNSSeeds,
×
2507
                                chainreg.BitcoinSignetGenesis,
×
2508
                        )
×
2509
                }
×
2510

2511
                // If network bootstrapping hasn't been disabled, then we'll
2512
                // configure the set of active bootstrappers, and launch a
2513
                // dedicated goroutine to maintain a set of persistent
2514
                // connections.
2515
                if shouldPeerBootstrap(s.cfg) {
3✔
2516
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2517
                        if err != nil {
×
2518
                                startErr = err
×
2519
                                return
×
2520
                        }
×
2521

2522
                        s.wg.Add(1)
×
2523
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2524
                } else {
3✔
2525
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2526
                }
3✔
2527

2528
                // Start the blockbeat after all other subsystems have been
2529
                // started so they are ready to receive new blocks.
2530
                cleanup = cleanup.add(func() error {
3✔
2531
                        s.blockbeatDispatcher.Stop()
×
2532
                        return nil
×
2533
                })
×
2534
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2535
                        startErr = err
×
2536
                        return
×
2537
                }
×
2538

2539
                // Set the active flag now that we've completed the full
2540
                // startup.
2541
                atomic.StoreInt32(&s.active, 1)
3✔
2542
        })
2543

2544
        if startErr != nil {
3✔
2545
                cleanup.run()
×
2546
        }
×
2547
        return startErr
3✔
2548
}
2549

2550
// Stop gracefully shutsdown the main daemon server. This function will signal
2551
// any active goroutines, or helper objects to exit, then blocks until they've
2552
// all successfully exited. Additionally, any/all listeners are closed.
2553
// NOTE: This function is safe for concurrent access.
2554
func (s *server) Stop() error {
3✔
2555
        s.stop.Do(func() {
6✔
2556
                atomic.StoreInt32(&s.stopping, 1)
3✔
2557

3✔
2558
                close(s.quit)
3✔
2559

3✔
2560
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2561
                s.connMgr.Stop()
3✔
2562

3✔
2563
                // Stop dispatching blocks to other systems immediately.
3✔
2564
                s.blockbeatDispatcher.Stop()
3✔
2565

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

2625
                // Update channel.backup file. Make sure to do it before
2626
                // stopping chanSubSwapper.
2627
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2628
                        s.chanStateDB, s.addrSource,
3✔
2629
                )
3✔
2630
                if err != nil {
3✔
2631
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2632
                                err)
×
2633
                } else {
3✔
2634
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2635
                        if err != nil {
6✔
2636
                                srvrLog.Warnf("Manual update of channel "+
3✔
2637
                                        "backup failed: %v", err)
3✔
2638
                        }
3✔
2639
                }
2640

2641
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2642
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2643
                }
×
2644
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2645
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2646
                }
×
2647
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2648
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2649
                                err)
×
2650
                }
×
2651
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2652
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2653
                                err)
×
2654
                }
×
2655
                s.missionController.StopStoreTickers()
3✔
2656

3✔
2657
                // Disconnect from each active peers to ensure that
3✔
2658
                // peerTerminationWatchers signal completion to each peer.
3✔
2659
                for _, peer := range s.Peers() {
6✔
2660
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2661
                        if err != nil {
3✔
2662
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2663
                                        "received error: %v", peer.IdentityKey(),
×
2664
                                        err,
×
2665
                                )
×
2666
                        }
×
2667
                }
2668

2669
                // Now that all connections have been torn down, stop the tower
2670
                // client which will reliably flush all queued states to the
2671
                // tower. If this is halted for any reason, the force quit timer
2672
                // will kick in and abort to allow this method to return.
2673
                if s.towerClientMgr != nil {
6✔
2674
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2675
                                srvrLog.Warnf("Unable to shut down tower "+
×
2676
                                        "client manager: %v", err)
×
2677
                        }
×
2678
                }
2679

2680
                if s.hostAnn != nil {
3✔
2681
                        if err := s.hostAnn.Stop(); err != nil {
×
2682
                                srvrLog.Warnf("unable to shut down host "+
×
2683
                                        "annoucner: %v", err)
×
2684
                        }
×
2685
                }
2686

2687
                if s.livenessMonitor != nil {
6✔
2688
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2689
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2690
                                        "monitor: %v", err)
×
2691
                        }
×
2692
                }
2693

2694
                // Wait for all lingering goroutines to quit.
2695
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2696
                s.wg.Wait()
3✔
2697

3✔
2698
                srvrLog.Debug("Stopping buffer pools...")
3✔
2699
                s.sigPool.Stop()
3✔
2700
                s.writePool.Stop()
3✔
2701
                s.readPool.Stop()
3✔
2702
        })
2703

2704
        return nil
3✔
2705
}
2706

2707
// Stopped returns true if the server has been instructed to shutdown.
2708
// NOTE: This function is safe for concurrent access.
2709
func (s *server) Stopped() bool {
3✔
2710
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2711
}
3✔
2712

2713
// configurePortForwarding attempts to set up port forwarding for the different
2714
// ports that the server will be listening on.
2715
//
2716
// NOTE: This should only be used when using some kind of NAT traversal to
2717
// automatically set up forwarding rules.
2718
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2719
        ip, err := s.natTraversal.ExternalIP()
×
2720
        if err != nil {
×
2721
                return nil, err
×
2722
        }
×
2723
        s.lastDetectedIP = ip
×
2724

×
2725
        externalIPs := make([]string, 0, len(ports))
×
2726
        for _, port := range ports {
×
2727
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2728
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2729
                        continue
×
2730
                }
2731

2732
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2733
                externalIPs = append(externalIPs, hostIP)
×
2734
        }
2735

2736
        return externalIPs, nil
×
2737
}
2738

2739
// removePortForwarding attempts to clear the forwarding rules for the different
2740
// ports the server is currently listening on.
2741
//
2742
// NOTE: This should only be used when using some kind of NAT traversal to
2743
// automatically set up forwarding rules.
2744
func (s *server) removePortForwarding() {
×
2745
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2746
        for _, port := range forwardedPorts {
×
2747
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2748
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2749
                                "port %d: %v", port, err)
×
2750
                }
×
2751
        }
2752
}
2753

2754
// watchExternalIP continuously checks for an updated external IP address every
2755
// 15 minutes. Once a new IP address has been detected, it will automatically
2756
// handle port forwarding rules and send updated node announcements to the
2757
// currently connected peers.
2758
//
2759
// NOTE: This MUST be run as a goroutine.
2760
func (s *server) watchExternalIP() {
×
2761
        defer s.wg.Done()
×
2762

×
2763
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2764
        // up by the server.
×
2765
        defer s.removePortForwarding()
×
2766

×
2767
        // Keep track of the external IPs set by the user to avoid replacing
×
2768
        // them when detecting a new IP.
×
2769
        ipsSetByUser := make(map[string]struct{})
×
2770
        for _, ip := range s.cfg.ExternalIPs {
×
2771
                ipsSetByUser[ip.String()] = struct{}{}
×
2772
        }
×
2773

2774
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2775

×
2776
        ticker := time.NewTicker(15 * time.Minute)
×
2777
        defer ticker.Stop()
×
2778
out:
×
2779
        for {
×
2780
                select {
×
2781
                case <-ticker.C:
×
2782
                        // We'll start off by making sure a new IP address has
×
2783
                        // been detected.
×
2784
                        ip, err := s.natTraversal.ExternalIP()
×
2785
                        if err != nil {
×
2786
                                srvrLog.Debugf("Unable to retrieve the "+
×
2787
                                        "external IP address: %v", err)
×
2788
                                continue
×
2789
                        }
2790

2791
                        // Periodically renew the NAT port forwarding.
2792
                        for _, port := range forwardedPorts {
×
2793
                                err := s.natTraversal.AddPortMapping(port)
×
2794
                                if err != nil {
×
2795
                                        srvrLog.Warnf("Unable to automatically "+
×
2796
                                                "re-create port forwarding using %s: %v",
×
2797
                                                s.natTraversal.Name(), err)
×
2798
                                } else {
×
2799
                                        srvrLog.Debugf("Automatically re-created "+
×
2800
                                                "forwarding for port %d using %s to "+
×
2801
                                                "advertise external IP",
×
2802
                                                port, s.natTraversal.Name())
×
2803
                                }
×
2804
                        }
2805

2806
                        if ip.Equal(s.lastDetectedIP) {
×
2807
                                continue
×
2808
                        }
2809

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

×
2812
                        // Next, we'll craft the new addresses that will be
×
2813
                        // included in the new node announcement and advertised
×
2814
                        // to the network. Each address will consist of the new
×
2815
                        // IP detected and one of the currently advertised
×
2816
                        // ports.
×
2817
                        var newAddrs []net.Addr
×
2818
                        for _, port := range forwardedPorts {
×
2819
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2820
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2821
                                if err != nil {
×
2822
                                        srvrLog.Debugf("Unable to resolve "+
×
2823
                                                "host %v: %v", addr, err)
×
2824
                                        continue
×
2825
                                }
2826

2827
                                newAddrs = append(newAddrs, addr)
×
2828
                        }
2829

2830
                        // Skip the update if we weren't able to resolve any of
2831
                        // the new addresses.
2832
                        if len(newAddrs) == 0 {
×
2833
                                srvrLog.Debug("Skipping node announcement " +
×
2834
                                        "update due to not being able to " +
×
2835
                                        "resolve any new addresses")
×
2836
                                continue
×
2837
                        }
2838

2839
                        // Now, we'll need to update the addresses in our node's
2840
                        // announcement in order to propagate the update
2841
                        // throughout the network. We'll only include addresses
2842
                        // that have a different IP from the previous one, as
2843
                        // the previous IP is no longer valid.
2844
                        currentNodeAnn := s.getNodeAnnouncement()
×
2845

×
2846
                        for _, addr := range currentNodeAnn.Addresses {
×
2847
                                host, _, err := net.SplitHostPort(addr.String())
×
2848
                                if err != nil {
×
2849
                                        srvrLog.Debugf("Unable to determine "+
×
2850
                                                "host from address %v: %v",
×
2851
                                                addr, err)
×
2852
                                        continue
×
2853
                                }
2854

2855
                                // We'll also make sure to include external IPs
2856
                                // set manually by the user.
2857
                                _, setByUser := ipsSetByUser[addr.String()]
×
2858
                                if setByUser || host != s.lastDetectedIP.String() {
×
2859
                                        newAddrs = append(newAddrs, addr)
×
2860
                                }
×
2861
                        }
2862

2863
                        // Then, we'll generate a new timestamped node
2864
                        // announcement with the updated addresses and broadcast
2865
                        // it to our peers.
2866
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2867
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2868
                        )
×
2869
                        if err != nil {
×
2870
                                srvrLog.Debugf("Unable to generate new node "+
×
2871
                                        "announcement: %v", err)
×
2872
                                continue
×
2873
                        }
2874

2875
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2876
                        if err != nil {
×
2877
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2878
                                        "announcement to peers: %v", err)
×
2879
                                continue
×
2880
                        }
2881

2882
                        // Finally, update the last IP seen to the current one.
2883
                        s.lastDetectedIP = ip
×
2884
                case <-s.quit:
×
2885
                        break out
×
2886
                }
2887
        }
2888
}
2889

2890
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2891
// based on the server, and currently active bootstrap mechanisms as defined
2892
// within the current configuration.
2893
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2894
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2895

×
2896
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2897

×
2898
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2899
        // this can be used by default if we've already partially seeded the
×
2900
        // network.
×
2901
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2902
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2903
        if err != nil {
×
2904
                return nil, err
×
2905
        }
×
2906
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2907

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

×
2913
                // If we have a set of DNS seeds for this chain, then we'll add
×
2914
                // it as an additional bootstrapping source.
×
2915
                if ok {
×
2916
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2917
                                "seeds: %v", dnsSeeds)
×
2918

×
2919
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2920
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2921
                        )
×
2922
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2923
                }
×
2924
        }
2925

2926
        return bootStrappers, nil
×
2927
}
2928

2929
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2930
// needs to ignore, which is made of three parts,
2931
//   - the node itself needs to be skipped as it doesn't make sense to connect
2932
//     to itself.
2933
//   - the peers that already have connections with, as in s.peersByPub.
2934
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2935
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2936
        s.mu.RLock()
×
2937
        defer s.mu.RUnlock()
×
2938

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

×
2941
        // We should ignore ourselves from bootstrapping.
×
2942
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2943
        ignore[selfKey] = struct{}{}
×
2944

×
2945
        // Ignore all connected peers.
×
2946
        for _, peer := range s.peersByPub {
×
2947
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2948
                ignore[nID] = struct{}{}
×
2949
        }
×
2950

2951
        // Ignore all persistent peers as they have a dedicated reconnecting
2952
        // process.
2953
        for pubKeyStr := range s.persistentPeers {
×
2954
                var nID autopilot.NodeID
×
2955
                copy(nID[:], []byte(pubKeyStr))
×
2956
                ignore[nID] = struct{}{}
×
2957
        }
×
2958

2959
        return ignore
×
2960
}
2961

2962
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2963
// and maintain a target minimum number of outbound connections. With this
2964
// invariant, we ensure that our node is connected to a diverse set of peers
2965
// and that nodes newly joining the network receive an up to date network view
2966
// as soon as possible.
2967
func (s *server) peerBootstrapper(numTargetPeers uint32,
2968
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2969

×
2970
        defer s.wg.Done()
×
2971

×
2972
        // Before we continue, init the ignore peers map.
×
2973
        ignoreList := s.createBootstrapIgnorePeers()
×
2974

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

×
2979
        // Once done, we'll attempt to maintain our target minimum number of
×
2980
        // peers.
×
2981
        //
×
2982
        // We'll use a 15 second backoff, and double the time every time an
×
2983
        // epoch fails up to a ceiling.
×
2984
        backOff := time.Second * 15
×
2985

×
2986
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2987
        // see if we've reached our minimum number of peers.
×
2988
        sampleTicker := time.NewTicker(backOff)
×
2989
        defer sampleTicker.Stop()
×
2990

×
2991
        // We'll use the number of attempts and errors to determine if we need
×
2992
        // to increase the time between discovery epochs.
×
2993
        var epochErrors uint32 // To be used atomically.
×
2994
        var epochAttempts uint32
×
2995

×
2996
        for {
×
2997
                select {
×
2998
                // The ticker has just woken us up, so we'll need to check if
2999
                // we need to attempt to connect our to any more peers.
3000
                case <-sampleTicker.C:
×
3001
                        // Obtain the current number of peers, so we can gauge
×
3002
                        // if we need to sample more peers or not.
×
3003
                        s.mu.RLock()
×
3004
                        numActivePeers := uint32(len(s.peersByPub))
×
3005
                        s.mu.RUnlock()
×
3006

×
3007
                        // If we have enough peers, then we can loop back
×
3008
                        // around to the next round as we're done here.
×
3009
                        if numActivePeers >= numTargetPeers {
×
3010
                                continue
×
3011
                        }
3012

3013
                        // If all of our attempts failed during this last back
3014
                        // off period, then will increase our backoff to 5
3015
                        // minute ceiling to avoid an excessive number of
3016
                        // queries
3017
                        //
3018
                        // TODO(roasbeef): add reverse policy too?
3019

3020
                        if epochAttempts > 0 &&
×
3021
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3022

×
3023
                                sampleTicker.Stop()
×
3024

×
3025
                                backOff *= 2
×
3026
                                if backOff > bootstrapBackOffCeiling {
×
3027
                                        backOff = bootstrapBackOffCeiling
×
3028
                                }
×
3029

3030
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3031
                                        "%v", backOff)
×
3032
                                sampleTicker = time.NewTicker(backOff)
×
3033
                                continue
×
3034
                        }
3035

3036
                        atomic.StoreUint32(&epochErrors, 0)
×
3037
                        epochAttempts = 0
×
3038

×
3039
                        // Since we know need more peers, we'll compute the
×
3040
                        // exact number we need to reach our threshold.
×
3041
                        numNeeded := numTargetPeers - numActivePeers
×
3042

×
3043
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3044
                                "peers", numNeeded)
×
3045

×
3046
                        // With the number of peers we need calculated, we'll
×
3047
                        // query the network bootstrappers to sample a set of
×
3048
                        // random addrs for us.
×
3049
                        //
×
3050
                        // Before we continue, get a copy of the ignore peers
×
3051
                        // map.
×
3052
                        ignoreList = s.createBootstrapIgnorePeers()
×
3053

×
3054
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3055
                                ignoreList, numNeeded*2, bootstrappers...,
×
3056
                        )
×
3057
                        if err != nil {
×
3058
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3059
                                        "peers: %v", err)
×
3060
                                continue
×
3061
                        }
3062

3063
                        // Finally, we'll launch a new goroutine for each
3064
                        // prospective peer candidates.
3065
                        for _, addr := range peerAddrs {
×
3066
                                epochAttempts++
×
3067

×
3068
                                go func(a *lnwire.NetAddress) {
×
3069
                                        // TODO(roasbeef): can do AS, subnet,
×
3070
                                        // country diversity, etc
×
3071
                                        errChan := make(chan error, 1)
×
3072
                                        s.connectToPeer(
×
3073
                                                a, errChan,
×
3074
                                                s.cfg.ConnectionTimeout,
×
3075
                                        )
×
3076
                                        select {
×
3077
                                        case err := <-errChan:
×
3078
                                                if err == nil {
×
3079
                                                        return
×
3080
                                                }
×
3081

3082
                                                srvrLog.Errorf("Unable to "+
×
3083
                                                        "connect to %v: %v",
×
3084
                                                        a, err)
×
3085
                                                atomic.AddUint32(&epochErrors, 1)
×
3086
                                        case <-s.quit:
×
3087
                                        }
3088
                                }(addr)
3089
                        }
3090
                case <-s.quit:
×
3091
                        return
×
3092
                }
3093
        }
3094
}
3095

3096
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3097
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3098
// query back off each time we encounter a failure.
3099
const bootstrapBackOffCeiling = time.Minute * 5
3100

3101
// initialPeerBootstrap attempts to continuously connect to peers on startup
3102
// until the target number of peers has been reached. This ensures that nodes
3103
// receive an up to date network view as soon as possible.
3104
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
3105
        numTargetPeers uint32,
3106
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3107

×
3108
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3109
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3110

×
3111
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3112
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3113
        var delaySignal <-chan time.Time
×
3114
        delayTime := time.Second * 2
×
3115

×
3116
        // As want to be more aggressive, we'll use a lower back off celling
×
3117
        // then the main peer bootstrap logic.
×
3118
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3119

×
3120
        for attempts := 0; ; attempts++ {
×
3121
                // Check if the server has been requested to shut down in order
×
3122
                // to prevent blocking.
×
3123
                if s.Stopped() {
×
3124
                        return
×
3125
                }
×
3126

3127
                // We can exit our aggressive initial peer bootstrapping stage
3128
                // if we've reached out target number of peers.
3129
                s.mu.RLock()
×
3130
                numActivePeers := uint32(len(s.peersByPub))
×
3131
                s.mu.RUnlock()
×
3132

×
3133
                if numActivePeers >= numTargetPeers {
×
3134
                        return
×
3135
                }
×
3136

3137
                if attempts > 0 {
×
3138
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3139
                                "bootstrap peers (attempt #%v)", delayTime,
×
3140
                                attempts)
×
3141

×
3142
                        // We've completed at least one iterating and haven't
×
3143
                        // finished, so we'll start to insert a delay period
×
3144
                        // between each attempt.
×
3145
                        delaySignal = time.After(delayTime)
×
3146
                        select {
×
3147
                        case <-delaySignal:
×
3148
                        case <-s.quit:
×
3149
                                return
×
3150
                        }
3151

3152
                        // After our delay, we'll double the time we wait up to
3153
                        // the max back off period.
3154
                        delayTime *= 2
×
3155
                        if delayTime > backOffCeiling {
×
3156
                                delayTime = backOffCeiling
×
3157
                        }
×
3158
                }
3159

3160
                // Otherwise, we'll request for the remaining number of peers
3161
                // in order to reach our target.
3162
                peersNeeded := numTargetPeers - numActivePeers
×
3163
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3164
                        ignore, peersNeeded, bootstrappers...,
×
3165
                )
×
3166
                if err != nil {
×
3167
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3168
                                "peers: %v", err)
×
3169
                        continue
×
3170
                }
3171

3172
                // Then, we'll attempt to establish a connection to the
3173
                // different peer addresses retrieved by our bootstrappers.
3174
                var wg sync.WaitGroup
×
3175
                for _, bootstrapAddr := range bootstrapAddrs {
×
3176
                        wg.Add(1)
×
3177
                        go func(addr *lnwire.NetAddress) {
×
3178
                                defer wg.Done()
×
3179

×
3180
                                errChan := make(chan error, 1)
×
3181
                                go s.connectToPeer(
×
3182
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3183
                                )
×
3184

×
3185
                                // We'll only allow this connection attempt to
×
3186
                                // take up to 3 seconds. This allows us to move
×
3187
                                // quickly by discarding peers that are slowing
×
3188
                                // us down.
×
3189
                                select {
×
3190
                                case err := <-errChan:
×
3191
                                        if err == nil {
×
3192
                                                return
×
3193
                                        }
×
3194
                                        srvrLog.Errorf("Unable to connect to "+
×
3195
                                                "%v: %v", addr, err)
×
3196
                                // TODO: tune timeout? 3 seconds might be *too*
3197
                                // aggressive but works well.
3198
                                case <-time.After(3 * time.Second):
×
3199
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3200
                                                "to not establishing a "+
×
3201
                                                "connection within 3 seconds",
×
3202
                                                addr)
×
3203
                                case <-s.quit:
×
3204
                                }
3205
                        }(bootstrapAddr)
3206
                }
3207

3208
                wg.Wait()
×
3209
        }
3210
}
3211

3212
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3213
// order to listen for inbound connections over Tor.
3214
func (s *server) createNewHiddenService() error {
×
3215
        // Determine the different ports the server is listening on. The onion
×
3216
        // service's virtual port will map to these ports and one will be picked
×
3217
        // at random when the onion service is being accessed.
×
3218
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3219
        for _, listenAddr := range s.listenAddrs {
×
3220
                port := listenAddr.(*net.TCPAddr).Port
×
3221
                listenPorts = append(listenPorts, port)
×
3222
        }
×
3223

3224
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3225
        if err != nil {
×
3226
                return err
×
3227
        }
×
3228

3229
        // Once the port mapping has been set, we can go ahead and automatically
3230
        // create our onion service. The service's private key will be saved to
3231
        // disk in order to regain access to this service when restarting `lnd`.
3232
        onionCfg := tor.AddOnionConfig{
×
3233
                VirtualPort: defaultPeerPort,
×
3234
                TargetPorts: listenPorts,
×
3235
                Store: tor.NewOnionFile(
×
3236
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3237
                        encrypter,
×
3238
                ),
×
3239
        }
×
3240

×
3241
        switch {
×
3242
        case s.cfg.Tor.V2:
×
3243
                onionCfg.Type = tor.V2
×
3244
        case s.cfg.Tor.V3:
×
3245
                onionCfg.Type = tor.V3
×
3246
        }
3247

3248
        addr, err := s.torController.AddOnion(onionCfg)
×
3249
        if err != nil {
×
3250
                return err
×
3251
        }
×
3252

3253
        // Now that the onion service has been created, we'll add the onion
3254
        // address it can be reached at to our list of advertised addresses.
3255
        newNodeAnn, err := s.genNodeAnnouncement(
×
3256
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3257
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3258
                },
×
3259
        )
3260
        if err != nil {
×
3261
                return fmt.Errorf("unable to generate new node "+
×
3262
                        "announcement: %v", err)
×
3263
        }
×
3264

3265
        // Finally, we'll update the on-disk version of our announcement so it
3266
        // will eventually propagate to nodes in the network.
3267
        selfNode := &models.LightningNode{
×
3268
                HaveNodeAnnouncement: true,
×
3269
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3270
                Addresses:            newNodeAnn.Addresses,
×
3271
                Alias:                newNodeAnn.Alias.String(),
×
3272
                Features: lnwire.NewFeatureVector(
×
3273
                        newNodeAnn.Features, lnwire.Features,
×
3274
                ),
×
3275
                Color:        newNodeAnn.RGBColor,
×
3276
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3277
        }
×
3278
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3279
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3280
                return fmt.Errorf("can't set self node: %w", err)
×
3281
        }
×
3282

3283
        return nil
×
3284
}
3285

3286
// findChannel finds a channel given a public key and ChannelID. It is an
3287
// optimization that is quicker than seeking for a channel given only the
3288
// ChannelID.
3289
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3290
        *channeldb.OpenChannel, error) {
3✔
3291

3✔
3292
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3293
        if err != nil {
3✔
3294
                return nil, err
×
3295
        }
×
3296

3297
        for _, channel := range nodeChans {
6✔
3298
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3299
                        return channel, nil
3✔
3300
                }
3✔
3301
        }
3302

3303
        return nil, fmt.Errorf("unable to find channel")
3✔
3304
}
3305

3306
// getNodeAnnouncement fetches the current, fully signed node announcement.
3307
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3308
        s.mu.Lock()
3✔
3309
        defer s.mu.Unlock()
3✔
3310

3✔
3311
        return *s.currentNodeAnn
3✔
3312
}
3✔
3313

3314
// genNodeAnnouncement generates and returns the current fully signed node
3315
// announcement. The time stamp of the announcement will be updated in order
3316
// to ensure it propagates through the network.
3317
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3318
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3319

3✔
3320
        s.mu.Lock()
3✔
3321
        defer s.mu.Unlock()
3✔
3322

3✔
3323
        // First, try to update our feature manager with the updated set of
3✔
3324
        // features.
3✔
3325
        if features != nil {
6✔
3326
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3327
                        feature.SetNodeAnn: features,
3✔
3328
                }
3✔
3329
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3330
                if err != nil {
6✔
3331
                        return lnwire.NodeAnnouncement{}, err
3✔
3332
                }
3✔
3333

3334
                // If we could successfully update our feature manager, add
3335
                // an update modifier to include these new features to our
3336
                // set.
3337
                modifiers = append(
3✔
3338
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3339
                )
3✔
3340
        }
3341

3342
        // Always update the timestamp when refreshing to ensure the update
3343
        // propagates.
3344
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3345

3✔
3346
        // Apply the requested changes to the node announcement.
3✔
3347
        for _, modifier := range modifiers {
6✔
3348
                modifier(s.currentNodeAnn)
3✔
3349
        }
3✔
3350

3351
        // Sign a new update after applying all of the passed modifiers.
3352
        err := netann.SignNodeAnnouncement(
3✔
3353
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
3✔
3354
        )
3✔
3355
        if err != nil {
3✔
3356
                return lnwire.NodeAnnouncement{}, err
×
3357
        }
×
3358

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

3362
// updateAndBroadcastSelfNode generates a new node announcement
3363
// applying the giving modifiers and updating the time stamp
3364
// to ensure it propagates through the network. Then it broadcasts
3365
// it to the network.
3366
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
3367
        modifiers ...netann.NodeAnnModifier) error {
3✔
3368

3✔
3369
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3370
        if err != nil {
6✔
3371
                return fmt.Errorf("unable to generate new node "+
3✔
3372
                        "announcement: %v", err)
3✔
3373
        }
3✔
3374

3375
        // Update the on-disk version of our announcement.
3376
        // Load and modify self node istead of creating anew instance so we
3377
        // don't risk overwriting any existing values.
3378
        selfNode, err := s.graphDB.SourceNode()
3✔
3379
        if err != nil {
3✔
3380
                return fmt.Errorf("unable to get current source node: %w", err)
×
3381
        }
×
3382

3383
        selfNode.HaveNodeAnnouncement = true
3✔
3384
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3385
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3386
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3387
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3388
        selfNode.Color = newNodeAnn.RGBColor
3✔
3389
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3390

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

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

3397
        // Finally, propagate it to the nodes in the network.
3398
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3399
        if err != nil {
3✔
3400
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3401
                        "announcement to peers: %v", err)
×
3402
                return err
×
3403
        }
×
3404

3405
        return nil
3✔
3406
}
3407

3408
type nodeAddresses struct {
3409
        pubKey    *btcec.PublicKey
3410
        addresses []net.Addr
3411
}
3412

3413
// establishPersistentConnections attempts to establish persistent connections
3414
// to all our direct channel collaborators. In order to promote liveness of our
3415
// active channels, we instruct the connection manager to attempt to establish
3416
// and maintain persistent connections to all our direct channel counterparties.
3417
func (s *server) establishPersistentConnections() error {
3✔
3418
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3419
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3420
        // since other PubKey forms can't be compared.
3✔
3421
        nodeAddrsMap := map[string]*nodeAddresses{}
3✔
3422

3✔
3423
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3424
        // attempt to connect to based on our set of previous connections. Set
3✔
3425
        // the reconnection port to the default peer port.
3✔
3426
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3427
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3428
                return err
×
3429
        }
×
3430
        for _, node := range linkNodes {
6✔
3431
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3432
                nodeAddrs := &nodeAddresses{
3✔
3433
                        pubKey:    node.IdentityPub,
3✔
3434
                        addresses: node.Addresses,
3✔
3435
                }
3✔
3436
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3437
        }
3✔
3438

3439
        // After checking our previous connections for addresses to connect to,
3440
        // iterate through the nodes in our channel graph to find addresses
3441
        // that have been added via NodeAnnouncement messages.
3442
        sourceNode, err := s.graphDB.SourceNode()
3✔
3443
        if err != nil {
3✔
3444
                return err
×
3445
        }
×
3446

3447
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3448
        // each of the nodes.
3449
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
3✔
3450
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
3✔
3451
                tx kvdb.RTx,
3✔
3452
                chanInfo *models.ChannelEdgeInfo,
3✔
3453
                policy, _ *models.ChannelEdgePolicy) error {
6✔
3454

3✔
3455
                // If the remote party has announced the channel to us, but we
3✔
3456
                // haven't yet, then we won't have a policy. However, we don't
3✔
3457
                // need this to connect to the peer, so we'll log it and move on.
3✔
3458
                if policy == nil {
3✔
3459
                        srvrLog.Warnf("No channel policy found for "+
×
3460
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3461
                }
×
3462

3463
                // We'll now fetch the peer opposite from us within this
3464
                // channel so we can queue up a direct connection to them.
3465
                channelPeer, err := s.graphDB.FetchOtherNode(
3✔
3466
                        tx, chanInfo, selfPub,
3✔
3467
                )
3✔
3468
                if err != nil {
3✔
3469
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3470
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3471
                                err)
×
3472
                }
×
3473

3474
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3475

3✔
3476
                // Add all unique addresses from channel
3✔
3477
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3478
                // connect to for this peer.
3✔
3479
                addrSet := make(map[string]net.Addr)
3✔
3480
                for _, addr := range channelPeer.Addresses {
6✔
3481
                        switch addr.(type) {
3✔
3482
                        case *net.TCPAddr:
3✔
3483
                                addrSet[addr.String()] = addr
3✔
3484

3485
                        // We'll only attempt to connect to Tor addresses if Tor
3486
                        // outbound support is enabled.
3487
                        case *tor.OnionAddr:
×
3488
                                if s.cfg.Tor.Active {
×
3489
                                        addrSet[addr.String()] = addr
×
3490
                                }
×
3491
                        }
3492
                }
3493

3494
                // If this peer is also recorded as a link node, we'll add any
3495
                // additional addresses that have not already been selected.
3496
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3497
                if ok {
6✔
3498
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3499
                                switch lnAddress.(type) {
3✔
3500
                                case *net.TCPAddr:
3✔
3501
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3502

3503
                                // We'll only attempt to connect to Tor
3504
                                // addresses if Tor outbound support is enabled.
3505
                                case *tor.OnionAddr:
×
3506
                                        if s.cfg.Tor.Active {
×
3507
                                                addrSet[lnAddress.String()] = lnAddress
×
3508
                                        }
×
3509
                                }
3510
                        }
3511
                }
3512

3513
                // Construct a slice of the deduped addresses.
3514
                var addrs []net.Addr
3✔
3515
                for _, addr := range addrSet {
6✔
3516
                        addrs = append(addrs, addr)
3✔
3517
                }
3✔
3518

3519
                n := &nodeAddresses{
3✔
3520
                        addresses: addrs,
3✔
3521
                }
3✔
3522
                n.pubKey, err = channelPeer.PubKey()
3✔
3523
                if err != nil {
3✔
3524
                        return err
×
3525
                }
×
3526

3527
                nodeAddrsMap[pubStr] = n
3✔
3528
                return nil
3✔
3529
        })
3530
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
3✔
3531
                return err
×
3532
        }
×
3533

3534
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3535
                len(nodeAddrsMap))
3✔
3536

3✔
3537
        // Acquire and hold server lock until all persistent connection requests
3✔
3538
        // have been recorded and sent to the connection manager.
3✔
3539
        s.mu.Lock()
3✔
3540
        defer s.mu.Unlock()
3✔
3541

3✔
3542
        // Iterate through the combined list of addresses from prior links and
3✔
3543
        // node announcements and attempt to reconnect to each node.
3✔
3544
        var numOutboundConns int
3✔
3545
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3546
                // Add this peer to the set of peers we should maintain a
3✔
3547
                // persistent connection with. We set the value to false to
3✔
3548
                // indicate that we should not continue to reconnect if the
3✔
3549
                // number of channels returns to zero, since this peer has not
3✔
3550
                // been requested as perm by the user.
3✔
3551
                s.persistentPeers[pubStr] = false
3✔
3552
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3553
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3554
                }
3✔
3555

3556
                for _, address := range nodeAddr.addresses {
6✔
3557
                        // Create a wrapper address which couples the IP and
3✔
3558
                        // the pubkey so the brontide authenticated connection
3✔
3559
                        // can be established.
3✔
3560
                        lnAddr := &lnwire.NetAddress{
3✔
3561
                                IdentityKey: nodeAddr.pubKey,
3✔
3562
                                Address:     address,
3✔
3563
                        }
3✔
3564

3✔
3565
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3566
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3567
                }
3✔
3568

3569
                // We'll connect to the first 10 peers immediately, then
3570
                // randomly stagger any remaining connections if the
3571
                // stagger initial reconnect flag is set. This ensures
3572
                // that mobile nodes or nodes with a small number of
3573
                // channels obtain connectivity quickly, but larger
3574
                // nodes are able to disperse the costs of connecting to
3575
                // all peers at once.
3576
                if numOutboundConns < numInstantInitReconnect ||
3✔
3577
                        !s.cfg.StaggerInitialReconnect {
6✔
3578

3✔
3579
                        go s.connectToPersistentPeer(pubStr)
3✔
3580
                } else {
3✔
3581
                        go s.delayInitialReconnect(pubStr)
×
3582
                }
×
3583

3584
                numOutboundConns++
3✔
3585
        }
3586

3587
        return nil
3✔
3588
}
3589

3590
// delayInitialReconnect will attempt a reconnection to the given peer after
3591
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3592
//
3593
// NOTE: This method MUST be run as a goroutine.
3594
func (s *server) delayInitialReconnect(pubStr string) {
×
3595
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3596
        select {
×
3597
        case <-time.After(delay):
×
3598
                s.connectToPersistentPeer(pubStr)
×
3599
        case <-s.quit:
×
3600
        }
3601
}
3602

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

3✔
3609
        s.mu.Lock()
3✔
3610
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3611
                delete(s.persistentPeers, pubKeyStr)
3✔
3612
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3613
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3614
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3615
                s.mu.Unlock()
3✔
3616

3✔
3617
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3618
                        "peer has no open channels", compressedPubKey)
3✔
3619

3✔
3620
                return
3✔
3621
        }
3✔
3622
        s.mu.Unlock()
3✔
3623
}
3624

3625
// BroadcastMessage sends a request to the server to broadcast a set of
3626
// messages to all peers other than the one specified by the `skips` parameter.
3627
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3628
// the target peers.
3629
//
3630
// NOTE: This function is safe for concurrent access.
3631
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3632
        msgs ...lnwire.Message) error {
3✔
3633

3✔
3634
        // Filter out peers found in the skips map. We synchronize access to
3✔
3635
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3636
        // exact set of peers present at the time of invocation.
3✔
3637
        s.mu.RLock()
3✔
3638
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3639
        for pubStr, sPeer := range s.peersByPub {
6✔
3640
                if skips != nil {
6✔
3641
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3642
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3643
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3644
                                continue
3✔
3645
                        }
3646
                }
3647

3648
                peers = append(peers, sPeer)
3✔
3649
        }
3650
        s.mu.RUnlock()
3✔
3651

3✔
3652
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3653
        // all messages to each of peers.
3✔
3654
        var wg sync.WaitGroup
3✔
3655
        for _, sPeer := range peers {
6✔
3656
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3657
                        sPeer.PubKey())
3✔
3658

3✔
3659
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3660
                wg.Add(1)
3✔
3661
                s.wg.Add(1)
3✔
3662
                go func(p lnpeer.Peer) {
6✔
3663
                        defer s.wg.Done()
3✔
3664
                        defer wg.Done()
3✔
3665

3✔
3666
                        p.SendMessageLazy(false, msgs...)
3✔
3667
                }(sPeer)
3✔
3668
        }
3669

3670
        // Wait for all messages to have been dispatched before returning to
3671
        // caller.
3672
        wg.Wait()
3✔
3673

3✔
3674
        return nil
3✔
3675
}
3676

3677
// NotifyWhenOnline can be called by other subsystems to get notified when a
3678
// particular peer comes online. The peer itself is sent across the peerChan.
3679
//
3680
// NOTE: This function is safe for concurrent access.
3681
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3682
        peerChan chan<- lnpeer.Peer) {
3✔
3683

3✔
3684
        s.mu.Lock()
3✔
3685

3✔
3686
        // Compute the target peer's identifier.
3✔
3687
        pubStr := string(peerKey[:])
3✔
3688

3✔
3689
        // Check if peer is connected.
3✔
3690
        peer, ok := s.peersByPub[pubStr]
3✔
3691
        if ok {
6✔
3692
                // Unlock here so that the mutex isn't held while we are
3✔
3693
                // waiting for the peer to become active.
3✔
3694
                s.mu.Unlock()
3✔
3695

3✔
3696
                // Wait until the peer signals that it is actually active
3✔
3697
                // rather than only in the server's maps.
3✔
3698
                select {
3✔
3699
                case <-peer.ActiveSignal():
3✔
3700
                case <-peer.QuitSignal():
×
3701
                        // The peer quit, so we'll add the channel to the slice
×
3702
                        // and return.
×
3703
                        s.mu.Lock()
×
3704
                        s.peerConnectedListeners[pubStr] = append(
×
3705
                                s.peerConnectedListeners[pubStr], peerChan,
×
3706
                        )
×
3707
                        s.mu.Unlock()
×
3708
                        return
×
3709
                }
3710

3711
                // Connected, can return early.
3712
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3713

3✔
3714
                select {
3✔
3715
                case peerChan <- peer:
3✔
3716
                case <-s.quit:
1✔
3717
                }
3718

3719
                return
3✔
3720
        }
3721

3722
        // Not connected, store this listener such that it can be notified when
3723
        // the peer comes online.
3724
        s.peerConnectedListeners[pubStr] = append(
3✔
3725
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3726
        )
3✔
3727
        s.mu.Unlock()
3✔
3728
}
3729

3730
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3731
// the given public key has been disconnected. The notification is signaled by
3732
// closing the channel returned.
3733
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3734
        s.mu.Lock()
3✔
3735
        defer s.mu.Unlock()
3✔
3736

3✔
3737
        c := make(chan struct{})
3✔
3738

3✔
3739
        // If the peer is already offline, we can immediately trigger the
3✔
3740
        // notification.
3✔
3741
        peerPubKeyStr := string(peerPubKey[:])
3✔
3742
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3743
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3744
                close(c)
×
3745
                return c
×
3746
        }
×
3747

3748
        // Otherwise, the peer is online, so we'll keep track of the channel to
3749
        // trigger the notification once the server detects the peer
3750
        // disconnects.
3751
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3752
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3753
        )
3✔
3754

3✔
3755
        return c
3✔
3756
}
3757

3758
// FindPeer will return the peer that corresponds to the passed in public key.
3759
// This function is used by the funding manager, allowing it to update the
3760
// daemon's local representation of the remote peer.
3761
//
3762
// NOTE: This function is safe for concurrent access.
3763
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3764
        s.mu.RLock()
3✔
3765
        defer s.mu.RUnlock()
3✔
3766

3✔
3767
        pubStr := string(peerKey.SerializeCompressed())
3✔
3768

3✔
3769
        return s.findPeerByPubStr(pubStr)
3✔
3770
}
3✔
3771

3772
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3773
// which should be a string representation of the peer's serialized, compressed
3774
// public key.
3775
//
3776
// NOTE: This function is safe for concurrent access.
3777
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3778
        s.mu.RLock()
3✔
3779
        defer s.mu.RUnlock()
3✔
3780

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

3784
// findPeerByPubStr is an internal method that retrieves the specified peer from
3785
// the server's internal state using.
3786
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3787
        peer, ok := s.peersByPub[pubStr]
3✔
3788
        if !ok {
6✔
3789
                return nil, ErrPeerNotConnected
3✔
3790
        }
3✔
3791

3792
        return peer, nil
3✔
3793
}
3794

3795
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3796
// exponential backoff. If no previous backoff was known, the default is
3797
// returned.
3798
func (s *server) nextPeerBackoff(pubStr string,
3799
        startTime time.Time) time.Duration {
3✔
3800

3✔
3801
        // Now, determine the appropriate backoff to use for the retry.
3✔
3802
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3803
        if !ok {
6✔
3804
                // If an existing backoff was unknown, use the default.
3✔
3805
                return s.cfg.MinBackoff
3✔
3806
        }
3✔
3807

3808
        // If the peer failed to start properly, we'll just use the previous
3809
        // backoff to compute the subsequent randomized exponential backoff
3810
        // duration. This will roughly double on average.
3811
        if startTime.IsZero() {
3✔
3812
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3813
        }
×
3814

3815
        // The peer succeeded in starting. If the connection didn't last long
3816
        // enough to be considered stable, we'll continue to back off retries
3817
        // with this peer.
3818
        connDuration := time.Since(startTime)
3✔
3819
        if connDuration < defaultStableConnDuration {
6✔
3820
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3821
        }
3✔
3822

3823
        // The peer succeed in starting and this was stable peer, so we'll
3824
        // reduce the timeout duration by the length of the connection after
3825
        // applying randomized exponential backoff. We'll only apply this in the
3826
        // case that:
3827
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3828
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3829
        if relaxedBackoff > s.cfg.MinBackoff {
×
3830
                return relaxedBackoff
×
3831
        }
×
3832

3833
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3834
        // the stable connection lasted much longer than our previous backoff.
3835
        // To reward such good behavior, we'll reconnect after the default
3836
        // timeout.
3837
        return s.cfg.MinBackoff
×
3838
}
3839

3840
// shouldDropLocalConnection determines if our local connection to a remote peer
3841
// should be dropped in the case of concurrent connection establishment. In
3842
// order to deterministically decide which connection should be dropped, we'll
3843
// utilize the ordering of the local and remote public key. If we didn't use
3844
// such a tie breaker, then we risk _both_ connections erroneously being
3845
// dropped.
3846
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3847
        localPubBytes := local.SerializeCompressed()
×
3848
        remotePubPbytes := remote.SerializeCompressed()
×
3849

×
3850
        // The connection that comes from the node with a "smaller" pubkey
×
3851
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3852
        // should drop our established connection.
×
3853
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3854
}
×
3855

3856
// InboundPeerConnected initializes a new peer in response to a new inbound
3857
// connection.
3858
//
3859
// NOTE: This function is safe for concurrent access.
3860
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3861
        // Exit early if we have already been instructed to shutdown, this
3✔
3862
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3863
        if s.Stopped() {
3✔
3864
                return
×
3865
        }
×
3866

3867
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3868
        pubSer := nodePub.SerializeCompressed()
3✔
3869
        pubStr := string(pubSer)
3✔
3870

3✔
3871
        var pubBytes [33]byte
3✔
3872
        copy(pubBytes[:], pubSer)
3✔
3873

3✔
3874
        s.mu.Lock()
3✔
3875
        defer s.mu.Unlock()
3✔
3876

3✔
3877
        // If the remote node's public key is banned, drop the connection.
3✔
3878
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
3✔
3879
        if dcErr != nil {
3✔
3880
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3881
                        "peer: %v", dcErr)
×
3882
                conn.Close()
×
3883

×
3884
                return
×
3885
        }
×
3886

3887
        if shouldDc {
3✔
3888
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3889
                        "banned.", pubSer)
×
3890

×
3891
                conn.Close()
×
3892

×
3893
                return
×
3894
        }
×
3895

3896
        // If we already have an outbound connection to this peer, then ignore
3897
        // this new connection.
3898
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
3899
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3900
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3901
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3902

3✔
3903
                conn.Close()
3✔
3904
                return
3✔
3905
        }
3✔
3906

3907
        // If we already have a valid connection that is scheduled to take
3908
        // precedence once the prior peer has finished disconnecting, we'll
3909
        // ignore this connection.
3910
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
3911
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3912
                        "scheduled", conn.RemoteAddr(), p)
×
3913
                conn.Close()
×
3914
                return
×
3915
        }
×
3916

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

3✔
3919
        // Check to see if we already have a connection with this peer. If so,
3✔
3920
        // we may need to drop our existing connection. This prevents us from
3✔
3921
        // having duplicate connections to the same peer. We forgo adding a
3✔
3922
        // default case as we expect these to be the only error values returned
3✔
3923
        // from findPeerByPubStr.
3✔
3924
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
3925
        switch err {
3✔
3926
        case ErrPeerNotConnected:
3✔
3927
                // We were unable to locate an existing connection with the
3✔
3928
                // target peer, proceed to connect.
3✔
3929
                s.cancelConnReqs(pubStr, nil)
3✔
3930
                s.peerConnected(conn, nil, true)
3✔
3931

3932
        case nil:
×
3933
                // We already have a connection with the incoming peer. If the
×
3934
                // connection we've already established should be kept and is
×
3935
                // not of the same type of the new connection (inbound), then
×
3936
                // we'll close out the new connection s.t there's only a single
×
3937
                // connection between us.
×
3938
                localPub := s.identityECDH.PubKey()
×
3939
                if !connectedPeer.Inbound() &&
×
3940
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3941

×
3942
                        srvrLog.Warnf("Received inbound connection from "+
×
3943
                                "peer %v, but already have outbound "+
×
3944
                                "connection, dropping conn", connectedPeer)
×
3945
                        conn.Close()
×
3946
                        return
×
3947
                }
×
3948

3949
                // Otherwise, if we should drop the connection, then we'll
3950
                // disconnect our already connected peer.
3951
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3952
                        connectedPeer)
×
3953

×
3954
                s.cancelConnReqs(pubStr, nil)
×
3955

×
3956
                // Remove the current peer from the server's internal state and
×
3957
                // signal that the peer termination watcher does not need to
×
3958
                // execute for this peer.
×
3959
                s.removePeer(connectedPeer)
×
3960
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3961
                s.scheduledPeerConnection[pubStr] = func() {
×
3962
                        s.peerConnected(conn, nil, true)
×
3963
                }
×
3964
        }
3965
}
3966

3967
// OutboundPeerConnected initializes a new peer in response to a new outbound
3968
// connection.
3969
// NOTE: This function is safe for concurrent access.
3970
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
3971
        // Exit early if we have already been instructed to shutdown, this
3✔
3972
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3973
        if s.Stopped() {
3✔
3974
                return
×
3975
        }
×
3976

3977
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3978
        pubSer := nodePub.SerializeCompressed()
3✔
3979
        pubStr := string(pubSer)
3✔
3980

3✔
3981
        var pubBytes [33]byte
3✔
3982
        copy(pubBytes[:], pubSer)
3✔
3983

3✔
3984
        s.mu.Lock()
3✔
3985
        defer s.mu.Unlock()
3✔
3986

3✔
3987
        // If the remote node's public key is banned, drop the connection.
3✔
3988
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
3✔
3989
        if dcErr != nil {
3✔
3990
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3991
                        "peer: %v", dcErr)
×
3992
                conn.Close()
×
3993

×
3994
                return
×
3995
        }
×
3996

3997
        if shouldDc {
3✔
3998
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3999
                        "banned.", pubSer)
×
4000

×
4001
                if connReq != nil {
×
4002
                        s.connMgr.Remove(connReq.ID())
×
4003
                }
×
4004

4005
                conn.Close()
×
4006

×
4007
                return
×
4008
        }
4009

4010
        // If we already have an inbound connection to this peer, then ignore
4011
        // this new connection.
4012
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4013
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4014
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4015
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4016

3✔
4017
                if connReq != nil {
6✔
4018
                        s.connMgr.Remove(connReq.ID())
3✔
4019
                }
3✔
4020
                conn.Close()
3✔
4021
                return
3✔
4022
        }
4023
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4024
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4025
                s.connMgr.Remove(connReq.ID())
×
4026
                conn.Close()
×
4027
                return
×
4028
        }
×
4029

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

×
4036
                if connReq != nil {
×
4037
                        s.connMgr.Remove(connReq.ID())
×
4038
                }
×
4039

4040
                conn.Close()
×
4041
                return
×
4042
        }
4043

4044
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
3✔
4045
                conn.RemoteAddr())
3✔
4046

3✔
4047
        if connReq != nil {
6✔
4048
                // A successful connection was returned by the connmgr.
3✔
4049
                // Immediately cancel all pending requests, excluding the
3✔
4050
                // outbound connection we just established.
3✔
4051
                ignore := connReq.ID()
3✔
4052
                s.cancelConnReqs(pubStr, &ignore)
3✔
4053
        } else {
6✔
4054
                // This was a successful connection made by some other
3✔
4055
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4056
                s.cancelConnReqs(pubStr, nil)
3✔
4057
        }
3✔
4058

4059
        // If we already have a connection with this peer, decide whether or not
4060
        // we need to drop the stale connection. We forgo adding a default case
4061
        // as we expect these to be the only error values returned from
4062
        // findPeerByPubStr.
4063
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4064
        switch err {
3✔
4065
        case ErrPeerNotConnected:
3✔
4066
                // We were unable to locate an existing connection with the
3✔
4067
                // target peer, proceed to connect.
3✔
4068
                s.peerConnected(conn, connReq, false)
3✔
4069

4070
        case nil:
×
4071
                // We already have a connection with the incoming peer. If the
×
4072
                // connection we've already established should be kept and is
×
4073
                // not of the same type of the new connection (outbound), then
×
4074
                // we'll close out the new connection s.t there's only a single
×
4075
                // connection between us.
×
4076
                localPub := s.identityECDH.PubKey()
×
4077
                if connectedPeer.Inbound() &&
×
4078
                        shouldDropLocalConnection(localPub, nodePub) {
×
4079

×
4080
                        srvrLog.Warnf("Established outbound connection to "+
×
4081
                                "peer %v, but already have inbound "+
×
4082
                                "connection, dropping conn", connectedPeer)
×
4083
                        if connReq != nil {
×
4084
                                s.connMgr.Remove(connReq.ID())
×
4085
                        }
×
4086
                        conn.Close()
×
4087
                        return
×
4088
                }
4089

4090
                // Otherwise, _their_ connection should be dropped. So we'll
4091
                // disconnect the peer and send the now obsolete peer to the
4092
                // server for garbage collection.
4093
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4094
                        connectedPeer)
×
4095

×
4096
                // Remove the current peer from the server's internal state and
×
4097
                // signal that the peer termination watcher does not need to
×
4098
                // execute for this peer.
×
4099
                s.removePeer(connectedPeer)
×
4100
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4101
                s.scheduledPeerConnection[pubStr] = func() {
×
4102
                        s.peerConnected(conn, connReq, false)
×
4103
                }
×
4104
        }
4105
}
4106

4107
// UnassignedConnID is the default connection ID that a request can have before
4108
// it actually is submitted to the connmgr.
4109
// TODO(conner): move into connmgr package, or better, add connmgr method for
4110
// generating atomic IDs
4111
const UnassignedConnID uint64 = 0
4112

4113
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4114
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4115
// Afterwards, each connection request removed from the connmgr. The caller can
4116
// optionally specify a connection ID to ignore, which prevents us from
4117
// canceling a successful request. All persistent connreqs for the provided
4118
// pubkey are discarded after the operationjw.
4119
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4120
        // First, cancel any lingering persistent retry attempts, which will
3✔
4121
        // prevent retries for any with backoffs that are still maturing.
3✔
4122
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4123
                close(cancelChan)
3✔
4124
                delete(s.persistentRetryCancels, pubStr)
3✔
4125
        }
3✔
4126

4127
        // Next, check to see if we have any outstanding persistent connection
4128
        // requests to this peer. If so, then we'll remove all of these
4129
        // connection requests, and also delete the entry from the map.
4130
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4131
        if !ok {
6✔
4132
                return
3✔
4133
        }
3✔
4134

4135
        for _, connReq := range connReqs {
6✔
4136
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4137

3✔
4138
                // Atomically capture the current request identifier.
3✔
4139
                connID := connReq.ID()
3✔
4140

3✔
4141
                // Skip any zero IDs, this indicates the request has not
3✔
4142
                // yet been schedule.
3✔
4143
                if connID == UnassignedConnID {
3✔
4144
                        continue
×
4145
                }
4146

4147
                // Skip a particular connection ID if instructed.
4148
                if skip != nil && connID == *skip {
6✔
4149
                        continue
3✔
4150
                }
4151

4152
                s.connMgr.Remove(connID)
3✔
4153
        }
4154

4155
        delete(s.persistentConnReqs, pubStr)
3✔
4156
}
4157

4158
// handleCustomMessage dispatches an incoming custom peers message to
4159
// subscribers.
4160
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4161
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4162
                peer, msg.Type)
3✔
4163

3✔
4164
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4165
                Peer: peer,
3✔
4166
                Msg:  msg,
3✔
4167
        })
3✔
4168
}
3✔
4169

4170
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4171
// messages.
4172
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4173
        return s.customMessageServer.Subscribe()
3✔
4174
}
3✔
4175

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

3✔
4183
        brontideConn := conn.(*brontide.Conn)
3✔
4184
        addr := conn.RemoteAddr()
3✔
4185
        pubKey := brontideConn.RemotePub()
3✔
4186

3✔
4187
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4188
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4189

3✔
4190
        peerAddr := &lnwire.NetAddress{
3✔
4191
                IdentityKey: pubKey,
3✔
4192
                Address:     addr,
3✔
4193
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4194
        }
3✔
4195

3✔
4196
        // With the brontide connection established, we'll now craft the feature
3✔
4197
        // vectors to advertise to the remote node.
3✔
4198
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4199
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4200

3✔
4201
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4202
        // found, create a fresh buffer.
3✔
4203
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4204
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4205
        if !ok {
6✔
4206
                var err error
3✔
4207
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4208
                if err != nil {
3✔
4209
                        srvrLog.Errorf("unable to create peer %v", err)
×
4210
                        return
×
4211
                }
×
4212
        }
4213

4214
        // If we directly set the peer.Config TowerClient member to the
4215
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4216
        // the peer.Config's TowerClient member will not evaluate to nil even
4217
        // though the underlying value is nil. To avoid this gotcha which can
4218
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4219
        // TowerClient if needed.
4220
        var towerClient wtclient.ClientManager
3✔
4221
        if s.towerClientMgr != nil {
6✔
4222
                towerClient = s.towerClientMgr
3✔
4223
        }
3✔
4224

4225
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4226
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4227

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

3✔
4271
                        return s.genNodeAnnouncement(nil)
3✔
4272
                },
3✔
4273

4274
                PongBuf: s.pongBuf,
4275

4276
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4277

4278
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4279

4280
                FundingManager: s.fundingMgr,
4281

4282
                Hodl:                    s.cfg.Hodl,
4283
                UnsafeReplay:            s.cfg.UnsafeReplay,
4284
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4285
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4286
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4287
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4288
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4289
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4290
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4291
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4292
                HandleCustomMessage:    s.handleCustomMessage,
4293
                GetAliases:             s.aliasMgr.GetAliases,
4294
                RequestAlias:           s.aliasMgr.RequestAlias,
4295
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4296
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4297
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4298
                MaxFeeExposure:         thresholdMSats,
4299
                Quit:                   s.quit,
4300
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4301
                AuxSigner:              s.implCfg.AuxSigner,
4302
                MsgRouter:              s.implCfg.MsgRouter,
4303
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4304
                AuxResolver:            s.implCfg.AuxContractResolver,
4305
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4306
                ShouldFwdExpEndorsement: func() bool {
3✔
4307
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4308
                                return false
3✔
4309
                        }
3✔
4310

4311
                        return clock.NewDefaultClock().Now().Before(
3✔
4312
                                EndorsementExperimentEnd,
3✔
4313
                        )
3✔
4314
                },
4315
        }
4316

4317
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4318
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4319

3✔
4320
        p := peer.NewBrontide(pCfg)
3✔
4321

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

3✔
4325
        s.addPeer(p)
3✔
4326

3✔
4327
        // Once we have successfully added the peer to the server, we can
3✔
4328
        // delete the previous error buffer from the server's map of error
3✔
4329
        // buffers.
3✔
4330
        delete(s.peerErrors, pkStr)
3✔
4331

3✔
4332
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4333
        // includes sending and receiving Init messages, which would be a DOS
3✔
4334
        // vector if we held the server's mutex throughout the procedure.
3✔
4335
        s.wg.Add(1)
3✔
4336
        go s.peerInitializer(p)
3✔
4337
}
4338

4339
// addPeer adds the passed peer to the server's global state of all active
4340
// peers.
4341
func (s *server) addPeer(p *peer.Brontide) {
3✔
4342
        if p == nil {
3✔
4343
                return
×
4344
        }
×
4345

4346
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4347

3✔
4348
        // Ignore new peers if we're shutting down.
3✔
4349
        if s.Stopped() {
3✔
4350
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4351
                        pubBytes)
×
4352
                p.Disconnect(ErrServerShuttingDown)
×
4353

×
4354
                return
×
4355
        }
×
4356

4357
        // Track the new peer in our indexes so we can quickly look it up either
4358
        // according to its public key, or its peer ID.
4359
        // TODO(roasbeef): pipe all requests through to the
4360
        // queryHandler/peerManager
4361

4362
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4363
        // be human-readable.
4364
        pubStr := string(pubBytes)
3✔
4365

3✔
4366
        s.peersByPub[pubStr] = p
3✔
4367

3✔
4368
        if p.Inbound() {
6✔
4369
                s.inboundPeers[pubStr] = p
3✔
4370
        } else {
6✔
4371
                s.outboundPeers[pubStr] = p
3✔
4372
        }
3✔
4373

4374
        // Inform the peer notifier of a peer online event so that it can be reported
4375
        // to clients listening for peer events.
4376
        var pubKey [33]byte
3✔
4377
        copy(pubKey[:], pubBytes)
3✔
4378

3✔
4379
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4380
}
4381

4382
// peerInitializer asynchronously starts a newly connected peer after it has
4383
// been added to the server's peer map. This method sets up a
4384
// peerTerminationWatcher for the given peer, and ensures that it executes even
4385
// if the peer failed to start. In the event of a successful connection, this
4386
// method reads the negotiated, local feature-bits and spawns the appropriate
4387
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4388
// be signaled of the new peer once the method returns.
4389
//
4390
// NOTE: This MUST be launched as a goroutine.
4391
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4392
        defer s.wg.Done()
3✔
4393

3✔
4394
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4395

3✔
4396
        // Avoid initializing peers while the server is exiting.
3✔
4397
        if s.Stopped() {
3✔
4398
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4399
                        pubBytes)
×
4400
                return
×
4401
        }
×
4402

4403
        // Create a channel that will be used to signal a successful start of
4404
        // the link. This prevents the peer termination watcher from beginning
4405
        // its duty too early.
4406
        ready := make(chan struct{})
3✔
4407

3✔
4408
        // Before starting the peer, launch a goroutine to watch for the
3✔
4409
        // unexpected termination of this peer, which will ensure all resources
3✔
4410
        // are properly cleaned up, and re-establish persistent connections when
3✔
4411
        // necessary. The peer termination watcher will be short circuited if
3✔
4412
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4413
        // that the server has already handled the removal of this peer.
3✔
4414
        s.wg.Add(1)
3✔
4415
        go s.peerTerminationWatcher(p, ready)
3✔
4416

3✔
4417
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4418
        // will unblock the peerTerminationWatcher.
3✔
4419
        if err := p.Start(); err != nil {
3✔
4420
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
4421

×
4422
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
4423
                return
×
4424
        }
×
4425

4426
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4427
        // was successful, and to begin watching the peer's wait group.
4428
        close(ready)
3✔
4429

3✔
4430
        s.mu.Lock()
3✔
4431
        defer s.mu.Unlock()
3✔
4432

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

3✔
4436
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4437
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4438
        pubStr := string(pubBytes)
3✔
4439
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4440
                select {
3✔
4441
                case peerChan <- p:
3✔
4442
                case <-s.quit:
×
4443
                        return
×
4444
                }
4445
        }
4446
        delete(s.peerConnectedListeners, pubStr)
3✔
4447
}
4448

4449
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4450
// and then cleans up all resources allocated to the peer, notifies relevant
4451
// sub-systems of its demise, and finally handles re-connecting to the peer if
4452
// it's persistent. If the server intentionally disconnects a peer, it should
4453
// have a corresponding entry in the ignorePeerTermination map which will cause
4454
// the cleanup routine to exit early. The passed `ready` chan is used to
4455
// synchronize when WaitForDisconnect should begin watching on the peer's
4456
// waitgroup. The ready chan should only be signaled if the peer starts
4457
// successfully, otherwise the peer should be disconnected instead.
4458
//
4459
// NOTE: This MUST be launched as a goroutine.
4460
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4461
        defer s.wg.Done()
3✔
4462

3✔
4463
        p.WaitForDisconnect(ready)
3✔
4464

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

3✔
4467
        // If the server is exiting then we can bail out early ourselves as all
3✔
4468
        // the other sub-systems will already be shutting down.
3✔
4469
        if s.Stopped() {
6✔
4470
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
3✔
4471
                return
3✔
4472
        }
3✔
4473

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

3✔
4480
        pubKey := p.IdentityKey()
3✔
4481

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

3✔
4486
        // Tell the switch to remove all links associated with this peer.
3✔
4487
        // Passing nil as the target link indicates that all links associated
3✔
4488
        // with this interface should be closed.
3✔
4489
        //
3✔
4490
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4491
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4492
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4493
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4494
        }
×
4495

4496
        for _, link := range links {
6✔
4497
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4498
        }
3✔
4499

4500
        s.mu.Lock()
3✔
4501
        defer s.mu.Unlock()
3✔
4502

3✔
4503
        // If there were any notification requests for when this peer
3✔
4504
        // disconnected, we can trigger them now.
3✔
4505
        srvrLog.Debugf("Notifying that peer %v is offline", p)
3✔
4506
        pubStr := string(pubKey.SerializeCompressed())
3✔
4507
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4508
                close(offlineChan)
3✔
4509
        }
3✔
4510
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4511

3✔
4512
        // If the server has already removed this peer, we can short circuit the
3✔
4513
        // peer termination watcher and skip cleanup.
3✔
4514
        if _, ok := s.ignorePeerTermination[p]; ok {
3✔
4515
                delete(s.ignorePeerTermination, p)
×
4516

×
4517
                pubKey := p.PubKey()
×
4518
                pubStr := string(pubKey[:])
×
4519

×
4520
                // If a connection callback is present, we'll go ahead and
×
4521
                // execute it now that previous peer has fully disconnected. If
×
4522
                // the callback is not present, this likely implies the peer was
×
4523
                // purposefully disconnected via RPC, and that no reconnect
×
4524
                // should be attempted.
×
4525
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4526
                if ok {
×
4527
                        delete(s.scheduledPeerConnection, pubStr)
×
4528
                        connCallback()
×
4529
                }
×
4530
                return
×
4531
        }
4532

4533
        // First, cleanup any remaining state the server has regarding the peer
4534
        // in question.
4535
        s.removePeer(p)
3✔
4536

3✔
4537
        // Next, check to see if this is a persistent peer or not.
3✔
4538
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4539
                return
3✔
4540
        }
3✔
4541

4542
        // Get the last address that we used to connect to the peer.
4543
        addrs := []net.Addr{
3✔
4544
                p.NetAddress().Address,
3✔
4545
        }
3✔
4546

3✔
4547
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4548
        // reconnection purposes.
3✔
4549
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
3✔
4550
        switch {
3✔
4551
        // We found advertised addresses, so use them.
4552
        case err == nil:
3✔
4553
                addrs = advertisedAddrs
3✔
4554

4555
        // The peer doesn't have an advertised address.
4556
        case err == errNoAdvertisedAddr:
3✔
4557
                // If it is an outbound peer then we fall back to the existing
3✔
4558
                // peer address.
3✔
4559
                if !p.Inbound() {
6✔
4560
                        break
3✔
4561
                }
4562

4563
                // Fall back to the existing peer address if
4564
                // we're not accepting connections over Tor.
4565
                if s.torController == nil {
6✔
4566
                        break
3✔
4567
                }
4568

4569
                // If we are, the peer's address won't be known
4570
                // to us (we'll see a private address, which is
4571
                // the address used by our onion service to dial
4572
                // to lnd), so we don't have enough information
4573
                // to attempt a reconnect.
4574
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4575
                        "to inbound peer %v without "+
×
4576
                        "advertised address", p)
×
4577
                return
×
4578

4579
        // We came across an error retrieving an advertised
4580
        // address, log it, and fall back to the existing peer
4581
        // address.
4582
        default:
3✔
4583
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4584
                        "address for node %x: %v", p.PubKey(),
3✔
4585
                        err)
3✔
4586
        }
4587

4588
        // Make an easy lookup map so that we can check if an address
4589
        // is already in the address list that we have stored for this peer.
4590
        existingAddrs := make(map[string]bool)
3✔
4591
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4592
                existingAddrs[addr.String()] = true
3✔
4593
        }
3✔
4594

4595
        // Add any missing addresses for this peer to persistentPeerAddr.
4596
        for _, addr := range addrs {
6✔
4597
                if existingAddrs[addr.String()] {
3✔
4598
                        continue
×
4599
                }
4600

4601
                s.persistentPeerAddrs[pubStr] = append(
3✔
4602
                        s.persistentPeerAddrs[pubStr],
3✔
4603
                        &lnwire.NetAddress{
3✔
4604
                                IdentityKey: p.IdentityKey(),
3✔
4605
                                Address:     addr,
3✔
4606
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4607
                        },
3✔
4608
                )
3✔
4609
        }
4610

4611
        // Record the computed backoff in the backoff map.
4612
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4613
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4614

3✔
4615
        // Initialize a retry canceller for this peer if one does not
3✔
4616
        // exist.
3✔
4617
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4618
        if !ok {
6✔
4619
                cancelChan = make(chan struct{})
3✔
4620
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4621
        }
3✔
4622

4623
        // We choose not to wait group this go routine since the Connect
4624
        // call can stall for arbitrarily long if we shutdown while an
4625
        // outbound connection attempt is being made.
4626
        go func() {
6✔
4627
                srvrLog.Debugf("Scheduling connection re-establishment to "+
3✔
4628
                        "persistent peer %x in %s",
3✔
4629
                        p.IdentityKey().SerializeCompressed(), backoff)
3✔
4630

3✔
4631
                select {
3✔
4632
                case <-time.After(backoff):
3✔
4633
                case <-cancelChan:
3✔
4634
                        return
3✔
4635
                case <-s.quit:
3✔
4636
                        return
3✔
4637
                }
4638

4639
                srvrLog.Debugf("Attempting to re-establish persistent "+
3✔
4640
                        "connection to peer %x",
3✔
4641
                        p.IdentityKey().SerializeCompressed())
3✔
4642

3✔
4643
                s.connectToPersistentPeer(pubStr)
3✔
4644
        }()
4645
}
4646

4647
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4648
// to connect to the peer. It creates connection requests if there are
4649
// currently none for a given address and it removes old connection requests
4650
// if the associated address is no longer in the latest address list for the
4651
// peer.
4652
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4653
        s.mu.Lock()
3✔
4654
        defer s.mu.Unlock()
3✔
4655

3✔
4656
        // Create an easy lookup map of the addresses we have stored for the
3✔
4657
        // peer. We will remove entries from this map if we have existing
3✔
4658
        // connection requests for the associated address and then any leftover
3✔
4659
        // entries will indicate which addresses we should create new
3✔
4660
        // connection requests for.
3✔
4661
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4662
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4663
                addrMap[addr.String()] = addr
3✔
4664
        }
3✔
4665

4666
        // Go through each of the existing connection requests and
4667
        // check if they correspond to the latest set of addresses. If
4668
        // there is a connection requests that does not use one of the latest
4669
        // advertised addresses then remove that connection request.
4670
        var updatedConnReqs []*connmgr.ConnReq
3✔
4671
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4672
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4673

3✔
4674
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4675
                // If the existing connection request is using one of the
4676
                // latest advertised addresses for the peer then we add it to
4677
                // updatedConnReqs and remove the associated address from
4678
                // addrMap so that we don't recreate this connReq later on.
4679
                case true:
×
4680
                        updatedConnReqs = append(
×
4681
                                updatedConnReqs, connReq,
×
4682
                        )
×
4683
                        delete(addrMap, lnAddr)
×
4684

4685
                // If the existing connection request is using an address that
4686
                // is not one of the latest advertised addresses for the peer
4687
                // then we remove the connecting request from the connection
4688
                // manager.
4689
                case false:
3✔
4690
                        srvrLog.Info(
3✔
4691
                                "Removing conn req:", connReq.Addr.String(),
3✔
4692
                        )
3✔
4693
                        s.connMgr.Remove(connReq.ID())
3✔
4694
                }
4695
        }
4696

4697
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4698

3✔
4699
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4700
        if !ok {
6✔
4701
                cancelChan = make(chan struct{})
3✔
4702
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4703
        }
3✔
4704

4705
        // Any addresses left in addrMap are new ones that we have not made
4706
        // connection requests for. So create new connection requests for those.
4707
        // If there is more than one address in the address map, stagger the
4708
        // creation of the connection requests for those.
4709
        go func() {
6✔
4710
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4711
                defer ticker.Stop()
3✔
4712

3✔
4713
                for _, addr := range addrMap {
6✔
4714
                        // Send the persistent connection request to the
3✔
4715
                        // connection manager, saving the request itself so we
3✔
4716
                        // can cancel/restart the process as needed.
3✔
4717
                        connReq := &connmgr.ConnReq{
3✔
4718
                                Addr:      addr,
3✔
4719
                                Permanent: true,
3✔
4720
                        }
3✔
4721

3✔
4722
                        s.mu.Lock()
3✔
4723
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4724
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4725
                        )
3✔
4726
                        s.mu.Unlock()
3✔
4727

3✔
4728
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4729
                                "channel peer %v", addr)
3✔
4730

3✔
4731
                        go s.connMgr.Connect(connReq)
3✔
4732

3✔
4733
                        select {
3✔
4734
                        case <-s.quit:
3✔
4735
                                return
3✔
4736
                        case <-cancelChan:
3✔
4737
                                return
3✔
4738
                        case <-ticker.C:
3✔
4739
                        }
4740
                }
4741
        }()
4742
}
4743

4744
// removePeer removes the passed peer from the server's state of all active
4745
// peers.
4746
func (s *server) removePeer(p *peer.Brontide) {
3✔
4747
        if p == nil {
3✔
4748
                return
×
4749
        }
×
4750

4751
        srvrLog.Debugf("removing peer %v", p)
3✔
4752

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

3✔
4757
        // If this peer had an active persistent connection request, remove it.
3✔
4758
        if p.ConnReq() != nil {
6✔
4759
                s.connMgr.Remove(p.ConnReq().ID())
3✔
4760
        }
3✔
4761

4762
        // Ignore deleting peers if we're shutting down.
4763
        if s.Stopped() {
3✔
4764
                return
×
4765
        }
×
4766

4767
        pKey := p.PubKey()
3✔
4768
        pubSer := pKey[:]
3✔
4769
        pubStr := string(pubSer)
3✔
4770

3✔
4771
        delete(s.peersByPub, pubStr)
3✔
4772

3✔
4773
        if p.Inbound() {
6✔
4774
                delete(s.inboundPeers, pubStr)
3✔
4775
        } else {
6✔
4776
                delete(s.outboundPeers, pubStr)
3✔
4777
        }
3✔
4778

4779
        // Copy the peer's error buffer across to the server if it has any items
4780
        // in it so that we can restore peer errors across connections.
4781
        if p.ErrorBuffer().Total() > 0 {
6✔
4782
                s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4783
        }
3✔
4784

4785
        // Inform the peer notifier of a peer offline event so that it can be
4786
        // reported to clients listening for peer events.
4787
        var pubKey [33]byte
3✔
4788
        copy(pubKey[:], pubSer)
3✔
4789

3✔
4790
        s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4791
}
4792

4793
// ConnectToPeer requests that the server connect to a Lightning Network peer
4794
// at the specified address. This function will *block* until either a
4795
// connection is established, or the initial handshake process fails.
4796
//
4797
// NOTE: This function is safe for concurrent access.
4798
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4799
        perm bool, timeout time.Duration) error {
3✔
4800

3✔
4801
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4802

3✔
4803
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4804
        // better granularity.  In certain conditions, this method requires
3✔
4805
        // making an outbound connection to a remote peer, which requires the
3✔
4806
        // lock to be released, and subsequently reacquired.
3✔
4807
        s.mu.Lock()
3✔
4808

3✔
4809
        // Ensure we're not already connected to this peer.
3✔
4810
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4811
        if err == nil {
6✔
4812
                s.mu.Unlock()
3✔
4813
                return &errPeerAlreadyConnected{peer: peer}
3✔
4814
        }
3✔
4815

4816
        // Peer was not found, continue to pursue connection with peer.
4817

4818
        // If there's already a pending connection request for this pubkey,
4819
        // then we ignore this request to ensure we don't create a redundant
4820
        // connection.
4821
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
4822
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
4823
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
4824
        }
3✔
4825

4826
        // If there's not already a pending or active connection to this node,
4827
        // then instruct the connection manager to attempt to establish a
4828
        // persistent connection to the peer.
4829
        srvrLog.Debugf("Connecting to %v", addr)
3✔
4830
        if perm {
6✔
4831
                connReq := &connmgr.ConnReq{
3✔
4832
                        Addr:      addr,
3✔
4833
                        Permanent: true,
3✔
4834
                }
3✔
4835

3✔
4836
                // Since the user requested a permanent connection, we'll set
3✔
4837
                // the entry to true which will tell the server to continue
3✔
4838
                // reconnecting even if the number of channels with this peer is
3✔
4839
                // zero.
3✔
4840
                s.persistentPeers[targetPub] = true
3✔
4841
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
4842
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
4843
                }
3✔
4844
                s.persistentConnReqs[targetPub] = append(
3✔
4845
                        s.persistentConnReqs[targetPub], connReq,
3✔
4846
                )
3✔
4847
                s.mu.Unlock()
3✔
4848

3✔
4849
                go s.connMgr.Connect(connReq)
3✔
4850

3✔
4851
                return nil
3✔
4852
        }
4853
        s.mu.Unlock()
3✔
4854

3✔
4855
        // If we're not making a persistent connection, then we'll attempt to
3✔
4856
        // connect to the target peer. If the we can't make the connection, or
3✔
4857
        // the crypto negotiation breaks down, then return an error to the
3✔
4858
        // caller.
3✔
4859
        errChan := make(chan error, 1)
3✔
4860
        s.connectToPeer(addr, errChan, timeout)
3✔
4861

3✔
4862
        select {
3✔
4863
        case err := <-errChan:
3✔
4864
                return err
3✔
4865
        case <-s.quit:
×
4866
                return ErrServerShuttingDown
×
4867
        }
4868
}
4869

4870
// connectToPeer establishes a connection to a remote peer. errChan is used to
4871
// notify the caller if the connection attempt has failed. Otherwise, it will be
4872
// closed.
4873
func (s *server) connectToPeer(addr *lnwire.NetAddress,
4874
        errChan chan<- error, timeout time.Duration) {
3✔
4875

3✔
4876
        conn, err := brontide.Dial(
3✔
4877
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
4878
        )
3✔
4879
        if err != nil {
6✔
4880
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
4881
                select {
3✔
4882
                case errChan <- err:
3✔
4883
                case <-s.quit:
×
4884
                }
4885
                return
3✔
4886
        }
4887

4888
        close(errChan)
3✔
4889

3✔
4890
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
4891
                conn.LocalAddr(), conn.RemoteAddr())
3✔
4892

3✔
4893
        s.OutboundPeerConnected(nil, conn)
3✔
4894
}
4895

4896
// DisconnectPeer sends the request to server to close the connection with peer
4897
// identified by public key.
4898
//
4899
// NOTE: This function is safe for concurrent access.
4900
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
4901
        pubBytes := pubKey.SerializeCompressed()
3✔
4902
        pubStr := string(pubBytes)
3✔
4903

3✔
4904
        s.mu.Lock()
3✔
4905
        defer s.mu.Unlock()
3✔
4906

3✔
4907
        // Check that were actually connected to this peer. If not, then we'll
3✔
4908
        // exit in an error as we can't disconnect from a peer that we're not
3✔
4909
        // currently connected to.
3✔
4910
        peer, err := s.findPeerByPubStr(pubStr)
3✔
4911
        if err == ErrPeerNotConnected {
6✔
4912
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
4913
        }
3✔
4914

4915
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
4916

3✔
4917
        s.cancelConnReqs(pubStr, nil)
3✔
4918

3✔
4919
        // If this peer was formerly a persistent connection, then we'll remove
3✔
4920
        // them from this map so we don't attempt to re-connect after we
3✔
4921
        // disconnect.
3✔
4922
        delete(s.persistentPeers, pubStr)
3✔
4923
        delete(s.persistentPeersBackoff, pubStr)
3✔
4924

3✔
4925
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
4926
        // removePeer, which bypassed the peerTerminationWatcher.
3✔
4927
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
4928

3✔
4929
        return nil
3✔
4930
}
4931

4932
// OpenChannel sends a request to the server to open a channel to the specified
4933
// peer identified by nodeKey with the passed channel funding parameters.
4934
//
4935
// NOTE: This function is safe for concurrent access.
4936
func (s *server) OpenChannel(
4937
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
4938

3✔
4939
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
4940
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
4941
        // not blocked if the caller is not reading the updates.
3✔
4942
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
4943
        req.Err = make(chan error, 1)
3✔
4944

3✔
4945
        // First attempt to locate the target peer to open a channel with, if
3✔
4946
        // we're unable to locate the peer then this request will fail.
3✔
4947
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
4948
        s.mu.RLock()
3✔
4949
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
4950
        if !ok {
3✔
4951
                s.mu.RUnlock()
×
4952

×
4953
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4954
                return req.Updates, req.Err
×
4955
        }
×
4956
        req.Peer = peer
3✔
4957
        s.mu.RUnlock()
3✔
4958

3✔
4959
        // We'll wait until the peer is active before beginning the channel
3✔
4960
        // opening process.
3✔
4961
        select {
3✔
4962
        case <-peer.ActiveSignal():
3✔
4963
        case <-peer.QuitSignal():
×
4964
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4965
                return req.Updates, req.Err
×
4966
        case <-s.quit:
×
4967
                req.Err <- ErrServerShuttingDown
×
4968
                return req.Updates, req.Err
×
4969
        }
4970

4971
        // If the fee rate wasn't specified at this point we fail the funding
4972
        // because of the missing fee rate information. The caller of the
4973
        // `OpenChannel` method needs to make sure that default values for the
4974
        // fee rate are set beforehand.
4975
        if req.FundingFeePerKw == 0 {
3✔
4976
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
4977
                        "the channel opening transaction")
×
4978

×
4979
                return req.Updates, req.Err
×
4980
        }
×
4981

4982
        // Spawn a goroutine to send the funding workflow request to the funding
4983
        // manager. This allows the server to continue handling queries instead
4984
        // of blocking on this request which is exported as a synchronous
4985
        // request to the outside world.
4986
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
4987

3✔
4988
        return req.Updates, req.Err
3✔
4989
}
4990

4991
// Peers returns a slice of all active peers.
4992
//
4993
// NOTE: This function is safe for concurrent access.
4994
func (s *server) Peers() []*peer.Brontide {
3✔
4995
        s.mu.RLock()
3✔
4996
        defer s.mu.RUnlock()
3✔
4997

3✔
4998
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
4999
        for _, peer := range s.peersByPub {
6✔
5000
                peers = append(peers, peer)
3✔
5001
        }
3✔
5002

5003
        return peers
3✔
5004
}
5005

5006
// computeNextBackoff uses a truncated exponential backoff to compute the next
5007
// backoff using the value of the exiting backoff. The returned duration is
5008
// randomized in either direction by 1/20 to prevent tight loops from
5009
// stabilizing.
5010
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5011
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5012
        nextBackoff := 2 * currBackoff
3✔
5013
        if nextBackoff > maxBackoff {
6✔
5014
                nextBackoff = maxBackoff
3✔
5015
        }
3✔
5016

5017
        // Using 1/10 of our duration as a margin, compute a random offset to
5018
        // avoid the nodes entering connection cycles.
5019
        margin := nextBackoff / 10
3✔
5020

3✔
5021
        var wiggle big.Int
3✔
5022
        wiggle.SetUint64(uint64(margin))
3✔
5023
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5024
                // Randomizing is not mission critical, so we'll just return the
×
5025
                // current backoff.
×
5026
                return nextBackoff
×
5027
        }
×
5028

5029
        // Otherwise add in our wiggle, but subtract out half of the margin so
5030
        // that the backoff can tweaked by 1/20 in either direction.
5031
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5032
}
5033

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

5038
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5039
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
5040
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5041
        if err != nil {
3✔
5042
                return nil, err
×
5043
        }
×
5044

5045
        node, err := s.graphDB.FetchLightningNode(vertex)
3✔
5046
        if err != nil {
6✔
5047
                return nil, err
3✔
5048
        }
3✔
5049

5050
        if len(node.Addresses) == 0 {
6✔
5051
                return nil, errNoAdvertisedAddr
3✔
5052
        }
3✔
5053

5054
        return node.Addresses, nil
3✔
5055
}
5056

5057
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5058
// channel update for a target channel.
5059
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5060
        *lnwire.ChannelUpdate1, error) {
3✔
5061

3✔
5062
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5063
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5064
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5065
                if err != nil {
6✔
5066
                        return nil, err
3✔
5067
                }
3✔
5068

5069
                return netann.ExtractChannelUpdate(
3✔
5070
                        ourPubKey[:], info, edge1, edge2,
3✔
5071
                )
3✔
5072
        }
5073
}
5074

5075
// applyChannelUpdate applies the channel update to the different sub-systems of
5076
// the server. The useAlias boolean denotes whether or not to send an alias in
5077
// place of the real SCID.
5078
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5079
        op *wire.OutPoint, useAlias bool) error {
3✔
5080

3✔
5081
        var (
3✔
5082
                peerAlias    *lnwire.ShortChannelID
3✔
5083
                defaultAlias lnwire.ShortChannelID
3✔
5084
        )
3✔
5085

3✔
5086
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5087

3✔
5088
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5089
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5090
        if useAlias {
6✔
5091
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5092
                if foundAlias != defaultAlias {
6✔
5093
                        peerAlias = &foundAlias
3✔
5094
                }
3✔
5095
        }
5096

5097
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5098
                update, discovery.RemoteAlias(peerAlias),
3✔
5099
        )
3✔
5100
        select {
3✔
5101
        case err := <-errChan:
3✔
5102
                return err
3✔
5103
        case <-s.quit:
×
5104
                return ErrServerShuttingDown
×
5105
        }
5106
}
5107

5108
// SendCustomMessage sends a custom message to the peer with the specified
5109
// pubkey.
5110
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5111
        data []byte) error {
3✔
5112

3✔
5113
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5114
        if err != nil {
3✔
5115
                return err
×
5116
        }
×
5117

5118
        // We'll wait until the peer is active.
5119
        select {
3✔
5120
        case <-peer.ActiveSignal():
3✔
5121
        case <-peer.QuitSignal():
×
5122
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5123
        case <-s.quit:
×
5124
                return ErrServerShuttingDown
×
5125
        }
5126

5127
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5128
        if err != nil {
6✔
5129
                return err
3✔
5130
        }
3✔
5131

5132
        // Send the message as low-priority. For now we assume that all
5133
        // application-defined message are low priority.
5134
        return peer.SendMessageLazy(true, msg)
3✔
5135
}
5136

5137
// newSweepPkScriptGen creates closure that generates a new public key script
5138
// which should be used to sweep any funds into the on-chain wallet.
5139
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5140
// (p2wkh) output.
5141
func newSweepPkScriptGen(
5142
        wallet lnwallet.WalletController,
5143
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5144

3✔
5145
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5146
                sweepAddr, err := wallet.NewAddress(
3✔
5147
                        lnwallet.TaprootPubkey, false,
3✔
5148
                        lnwallet.DefaultAccountName,
3✔
5149
                )
3✔
5150
                if err != nil {
3✔
5151
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5152
                }
×
5153

5154
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5155
                if err != nil {
3✔
5156
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5157
                }
×
5158

5159
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5160
                        wallet, netParams, addr,
3✔
5161
                )
3✔
5162
                if err != nil {
3✔
5163
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5164
                }
×
5165

5166
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5167
                        DeliveryAddress: addr,
3✔
5168
                        InternalKey:     internalKeyDesc,
3✔
5169
                })
3✔
5170
        }
5171
}
5172

5173
// shouldPeerBootstrap returns true if we should attempt to perform peer
5174
// bootstrapping to actively seek our peers using the set of active network
5175
// bootstrappers.
5176
func shouldPeerBootstrap(cfg *Config) bool {
3✔
5177
        isSimnet := cfg.Bitcoin.SimNet
3✔
5178
        isSignet := cfg.Bitcoin.SigNet
3✔
5179
        isRegtest := cfg.Bitcoin.RegTest
3✔
5180
        isDevNetwork := isSimnet || isSignet || isRegtest
3✔
5181

3✔
5182
        // TODO(yy): remove the check on simnet/regtest such that the itest is
3✔
5183
        // covering the bootstrapping process.
3✔
5184
        return !cfg.NoNetBootstrap && !isDevNetwork
3✔
5185
}
3✔
5186

5187
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5188
// finished.
5189
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5190
        // Get a list of closed channels.
3✔
5191
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5192
        if err != nil {
3✔
5193
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5194
                return nil
×
5195
        }
×
5196

5197
        // Save the SCIDs in a map.
5198
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5199
        for _, c := range channels {
6✔
5200
                // If the channel is not pending, its FC has been finalized.
3✔
5201
                if !c.IsPending {
6✔
5202
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5203
                }
3✔
5204
        }
5205

5206
        // Double check whether the reported closed channel has indeed finished
5207
        // closing.
5208
        //
5209
        // NOTE: There are misalignments regarding when a channel's FC is
5210
        // marked as finalized. We double check the pending channels to make
5211
        // sure the returned SCIDs are indeed terminated.
5212
        //
5213
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5214
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5215
        if err != nil {
3✔
5216
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5217
                return nil
×
5218
        }
×
5219

5220
        for _, c := range pendings {
6✔
5221
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5222
                        continue
3✔
5223
                }
5224

5225
                // If the channel is still reported as pending, remove it from
5226
                // the map.
5227
                delete(closedSCIDs, c.ShortChannelID)
×
5228

×
5229
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5230
                        c.ShortChannelID)
×
5231
        }
5232

5233
        return closedSCIDs
3✔
5234
}
5235

5236
// getStartingBeat returns the current beat. This is used during the startup to
5237
// initialize blockbeat consumers.
5238
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5239
        // beat is the current blockbeat.
3✔
5240
        var beat *chainio.Beat
3✔
5241

3✔
5242
        // We should get a notification with the current best block immediately
3✔
5243
        // by passing a nil block.
3✔
5244
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5245
        if err != nil {
3✔
5246
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5247
        }
×
5248
        defer blockEpochs.Cancel()
3✔
5249

3✔
5250
        // We registered for the block epochs with a nil request. The notifier
3✔
5251
        // should send us the current best block immediately. So we need to
3✔
5252
        // wait for it here because we need to know the current best height.
3✔
5253
        select {
3✔
5254
        case bestBlock := <-blockEpochs.Epochs:
3✔
5255
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5256
                        bestBlock.Hash, bestBlock.Height)
3✔
5257

3✔
5258
                // Update the current blockbeat.
3✔
5259
                beat = chainio.NewBeat(*bestBlock)
3✔
5260

5261
        case <-s.quit:
×
5262
                srvrLog.Debug("LND shutting down")
×
5263
        }
5264

5265
        return beat, nil
3✔
5266
}
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