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

lightningnetwork / lnd / 16911773184

12 Aug 2025 02:21PM UTC coverage: 57.471% (-9.4%) from 66.9%
16911773184

Pull #10103

github

web-flow
Merge d64a1234d into f3e1f2f35
Pull Request #10103: Rate limit outgoing gossip bandwidth by peer

57 of 77 new or added lines in 5 files covered. (74.03%)

28294 existing lines in 457 files now uncovered.

99110 of 172451 relevant lines covered (57.47%)

1.78 hits per line

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

72.93
/discovery/sync_manager.go
1
package discovery
2

3
import (
4
        "context"
5
        "errors"
6
        "sync"
7
        "sync/atomic"
8
        "time"
9

10
        "github.com/btcsuite/btcd/chaincfg/chainhash"
11
        "github.com/lightningnetwork/lnd/lnpeer"
12
        "github.com/lightningnetwork/lnd/lnwire"
13
        "github.com/lightningnetwork/lnd/routing/route"
14
        "github.com/lightningnetwork/lnd/ticker"
15
        "golang.org/x/time/rate"
16
)
17

18
const (
19
        // DefaultSyncerRotationInterval is the default interval in which we'll
20
        // rotate a single active syncer.
21
        DefaultSyncerRotationInterval = 20 * time.Minute
22

23
        // DefaultHistoricalSyncInterval is the default interval in which we'll
24
        // force a historical sync to ensure we have as much of the public
25
        // network as possible.
26
        DefaultHistoricalSyncInterval = time.Hour
27

28
        // DefaultFilterConcurrency is the default maximum number of concurrent
29
        // gossip filter applications that can be processed.
30
        DefaultFilterConcurrency = 5
31

32
        // DefaultMsgBytesBurst is the allotted burst in bytes we'll permit.
33
        // This is the most that can be sent in a given go. Requests beyond
34
        // this, will block indefinitely. Once tokens (bytes are depleted),
35
        // they'll be refilled at the DefaultMsgBytesPerSecond rate.
36
        DefaultMsgBytesBurst = 2 * 1000 * 1_024
37

38
        // DefaultMsgBytesPerSecond is the max bytes/s we'll permit for outgoing
39
        // messages. Once tokens (bytes) have been taken from the bucket,
40
        // they'll be refilled at this rate.
41
        DefaultMsgBytesPerSecond = 1000 * 1_024
42

43
        // DefaultPeerMsgBytesPerSecond is the max bytes/s we'll permit for
44
        // outgoing messages for a single peer. Once tokens (bytes) have been
45
        // taken from the bucket, they'll be refilled at this rate.
46
        DefaultPeerMsgBytesPerSecond = 50 * 1_024
47

48
        // assumedMsgSize is the assumed size of a message if we can't compute
49
        // its serialized size. This comes out to 1 KB.
50
        assumedMsgSize = 1_024
51
)
52

53
var (
54
        // ErrSyncManagerExiting is an error returned when we attempt to
55
        // start/stop a gossip syncer for a connected/disconnected peer, but the
56
        // SyncManager has already been stopped.
57
        ErrSyncManagerExiting = errors.New("sync manager exiting")
58
)
59

60
// newSyncer in an internal message we'll use within the SyncManager to signal
61
// that we should create a GossipSyncer for a newly connected peer.
62
type newSyncer struct {
63
        // peer is the newly connected peer.
64
        peer lnpeer.Peer
65

66
        // doneChan serves as a signal to the caller that the SyncManager's
67
        // internal state correctly reflects the stale active syncer.
68
        doneChan chan struct{}
69
}
70

71
// staleSyncer is an internal message we'll use within the SyncManager to signal
72
// that a peer has disconnected and its GossipSyncer should be removed.
73
type staleSyncer struct {
74
        // peer is the peer that has disconnected.
75
        peer route.Vertex
76

77
        // doneChan serves as a signal to the caller that the SyncManager's
78
        // internal state correctly reflects the stale active syncer. This is
79
        // needed to ensure we always create a new syncer for a flappy peer
80
        // after they disconnect if they happened to be an active syncer.
81
        doneChan chan struct{}
82
}
83

84
// SyncManagerCfg contains all of the dependencies required for the SyncManager
85
// to carry out its duties.
86
type SyncManagerCfg struct {
87
        // ChainHash is a hash that indicates the specific network of the active
88
        // chain.
89
        ChainHash chainhash.Hash
90

91
        // ChanSeries is an interface that provides access to a time series view
92
        // of the current known channel graph. Each GossipSyncer enabled peer
93
        // will utilize this in order to create and respond to channel graph
94
        // time series queries.
95
        ChanSeries ChannelGraphTimeSeries
96

97
        // NumActiveSyncers is the number of peers for which we should have
98
        // active syncers with. After reaching NumActiveSyncers, any future
99
        // gossip syncers will be passive.
100
        NumActiveSyncers int
101

102
        // NoTimestampQueries will prevent the GossipSyncer from querying
103
        // timestamps of announcement messages from the peer and from responding
104
        // to timestamp queries
105
        NoTimestampQueries bool
106

107
        // RotateTicker is a ticker responsible for notifying the SyncManager
108
        // when it should rotate its active syncers. A single active syncer with
109
        // a chansSynced state will be exchanged for a passive syncer in order
110
        // to ensure we don't keep syncing with the same peers.
111
        RotateTicker ticker.Ticker
112

113
        // HistoricalSyncTicker is a ticker responsible for notifying the
114
        // SyncManager when it should attempt a historical sync with a gossip
115
        // sync peer.
116
        HistoricalSyncTicker ticker.Ticker
117

118
        // IgnoreHistoricalFilters will prevent syncers from replying with
119
        // historical data when the remote peer sets a gossip_timestamp_range.
120
        // This prevents ranges with old start times from causing us to dump the
121
        // graph on connect.
122
        IgnoreHistoricalFilters bool
123

124
        // BestHeight returns the latest height known of the chain.
125
        BestHeight func() uint32
126

127
        // PinnedSyncers is a set of peers that will always transition to
128
        // ActiveSync upon connection. These peers will never transition to
129
        // PassiveSync.
130
        PinnedSyncers PinnedSyncers
131

132
        // IsStillZombieChannel takes the timestamps of the latest channel
133
        // updates for a channel and returns true if the channel should be
134
        // considered a zombie based on these timestamps.
135
        IsStillZombieChannel func(time.Time, time.Time) bool
136

137
        // AllotedMsgBytesPerSecond is the allotted bandwidth rate, expressed in
138
        // bytes/second that the gossip manager can consume. Once we exceed this
139
        // rate, message sending will block until we're below the rate.
140
        AllotedMsgBytesPerSecond uint64
141

142
        // AllotedMsgBytesBurst is the amount of burst bytes we'll permit, if
143
        // we've exceeded the hard upper limit.
144
        AllotedMsgBytesBurst uint64
145

146
        // FilterConcurrency is the maximum number of concurrent gossip filter
147
        // applications that can be processed. If not set, defaults to 5.
148
        FilterConcurrency int
149

150
        // PeerMsgBytesPerSecond is the allotted bandwidth rate, expressed in
151
        // bytes/second that a single gossip syncer can consume. Once we exceed
152
        // this rate, message sending will block until we're below the rate.
153
        PeerMsgBytesPerSecond uint64
154
}
155

156
// SyncManager is a subsystem of the gossiper that manages the gossip syncers
157
// for peers currently connected. When a new peer is connected, the manager will
158
// create its accompanying gossip syncer and determine whether it should have an
159
// ActiveSync or PassiveSync sync type based on how many other gossip syncers
160
// are currently active. Any ActiveSync gossip syncers are started in a
161
// round-robin manner to ensure we're not syncing with multiple peers at the
162
// same time. The first GossipSyncer registered with the SyncManager will
163
// attempt a historical sync to ensure we have as much of the public channel
164
// graph as possible.
165
type SyncManager struct {
166
        // initialHistoricalSyncCompleted serves as a barrier when initializing
167
        // new active GossipSyncers. If 0, the initial historical sync has not
168
        // completed, so we'll defer initializing any active GossipSyncers. If
169
        // 1, then we can transition the GossipSyncer immediately. We set up
170
        // this barrier to ensure we have most of the graph before attempting to
171
        // accept new updates at tip.
172
        //
173
        // NOTE: This must be used atomically.
174
        initialHistoricalSyncCompleted int32
175

176
        start sync.Once
177
        stop  sync.Once
178

179
        cfg SyncManagerCfg
180

181
        // newSyncers is a channel we'll use to process requests to create
182
        // GossipSyncers for newly connected peers.
183
        newSyncers chan *newSyncer
184

185
        // staleSyncers is a channel we'll use to process requests to tear down
186
        // GossipSyncers for disconnected peers.
187
        staleSyncers chan *staleSyncer
188

189
        // syncersMu guards the read and write access to the activeSyncers and
190
        // inactiveSyncers maps below.
191
        syncersMu sync.Mutex
192

193
        // activeSyncers is the set of all syncers for which we are currently
194
        // receiving graph updates from. The number of possible active syncers
195
        // is bounded by NumActiveSyncers.
196
        activeSyncers map[route.Vertex]*GossipSyncer
197

198
        // inactiveSyncers is the set of all syncers for which we are not
199
        // currently receiving new graph updates from.
200
        inactiveSyncers map[route.Vertex]*GossipSyncer
201

202
        // pinnedActiveSyncers is the set of all syncers which are pinned into
203
        // an active sync. Pinned peers performan an initial historical sync on
204
        // each connection and will continue to receive graph updates for the
205
        // duration of the connection.
206
        pinnedActiveSyncers map[route.Vertex]*GossipSyncer
207

208
        // gossipFilterSema contains semaphores for the gossip timestamp
209
        // queries.
210
        gossipFilterSema chan struct{}
211

212
        // rateLimiter dictates the frequency with which we will reply to gossip
213
        // queries from all peers. This is used to delay responses to peers to
214
        // prevent DOS vulnerabilities if they are spamming with an unreasonable
215
        // number of queries.
216
        rateLimiter *rate.Limiter
217

218
        wg   sync.WaitGroup
219
        quit chan struct{}
220
}
221

222
// newSyncManager constructs a new SyncManager backed by the given config.
223
func newSyncManager(cfg *SyncManagerCfg) *SyncManager {
3✔
224

3✔
225
        filterConcurrency := cfg.FilterConcurrency
3✔
226
        if filterConcurrency == 0 {
3✔
UNCOV
227
                filterConcurrency = DefaultFilterConcurrency
×
UNCOV
228
        }
×
229

230
        filterSema := make(chan struct{}, filterConcurrency)
3✔
231
        for i := 0; i < filterConcurrency; i++ {
6✔
232
                filterSema <- struct{}{}
3✔
233
        }
3✔
234

235
        bytesPerSecond := cfg.AllotedMsgBytesPerSecond
3✔
236
        if bytesPerSecond == 0 {
3✔
UNCOV
237
                bytesPerSecond = DefaultMsgBytesPerSecond
×
UNCOV
238
        }
×
239

240
        bytesBurst := cfg.AllotedMsgBytesBurst
3✔
241
        if bytesBurst == 0 {
3✔
UNCOV
242
                bytesBurst = DefaultMsgBytesBurst
×
UNCOV
243
        }
×
244

245
        // We'll use this rate limiter to limit our total outbound bandwidth for
246
        // gossip queries peers.
247
        rateLimiter := rate.NewLimiter(
3✔
248
                rate.Limit(bytesPerSecond), int(bytesBurst),
3✔
249
        )
3✔
250

3✔
251
        return &SyncManager{
3✔
252
                cfg:          *cfg,
3✔
253
                rateLimiter:  rateLimiter,
3✔
254
                newSyncers:   make(chan *newSyncer),
3✔
255
                staleSyncers: make(chan *staleSyncer),
3✔
256
                activeSyncers: make(
3✔
257
                        map[route.Vertex]*GossipSyncer, cfg.NumActiveSyncers,
3✔
258
                ),
3✔
259
                inactiveSyncers: make(map[route.Vertex]*GossipSyncer),
3✔
260
                pinnedActiveSyncers: make(
3✔
261
                        map[route.Vertex]*GossipSyncer, len(cfg.PinnedSyncers),
3✔
262
                ),
3✔
263
                gossipFilterSema: filterSema,
3✔
264
                quit:             make(chan struct{}),
3✔
265
        }
3✔
266
}
267

268
// Start starts the SyncManager in order to properly carry out its duties.
269
func (m *SyncManager) Start() {
3✔
270
        m.start.Do(func() {
6✔
271
                m.wg.Add(1)
3✔
272
                go m.syncerHandler()
3✔
273
        })
3✔
274
}
275

276
// Stop stops the SyncManager from performing its duties.
277
func (m *SyncManager) Stop() {
3✔
278
        m.stop.Do(func() {
6✔
279
                log.Debugf("SyncManager is stopping")
3✔
280
                defer log.Debugf("SyncManager stopped")
3✔
281

3✔
282
                close(m.quit)
3✔
283
                m.wg.Wait()
3✔
284

3✔
285
                for _, syncer := range m.inactiveSyncers {
5✔
286
                        syncer.Stop()
2✔
287
                }
2✔
288
                for _, syncer := range m.activeSyncers {
6✔
289
                        syncer.Stop()
3✔
290
                }
3✔
291
        })
292
}
293

294
// syncerHandler is the SyncManager's main event loop responsible for:
295
//
296
// 1. Creating and tearing down GossipSyncers for connected/disconnected peers.
297

298
// 2. Finding new peers to receive graph updates from to ensure we don't only
299
//    receive them from the same set of peers.
300

301
//  3. Finding new peers to force a historical sync with to ensure we have as
302
//     much of the public network as possible.
303
//
304
// NOTE: This must be run as a goroutine.
305
func (m *SyncManager) syncerHandler() {
3✔
306
        defer m.wg.Done()
3✔
307

3✔
308
        m.cfg.RotateTicker.Resume()
3✔
309
        defer m.cfg.RotateTicker.Stop()
3✔
310

3✔
311
        defer m.cfg.HistoricalSyncTicker.Stop()
3✔
312

3✔
313
        var (
3✔
314
                // initialHistoricalSyncer is the syncer we are currently
3✔
315
                // performing an initial historical sync with.
3✔
316
                initialHistoricalSyncer *GossipSyncer
3✔
317

3✔
318
                // initialHistoricalSyncSignal is a signal that will fire once
3✔
319
                // the initial historical sync has been completed. This is
3✔
320
                // crucial to ensure that another historical sync isn't
3✔
321
                // attempted just because the initialHistoricalSyncer was
3✔
322
                // disconnected.
3✔
323
                initialHistoricalSyncSignal chan struct{}
3✔
324
        )
3✔
325

3✔
326
        setInitialHistoricalSyncer := func(s *GossipSyncer) {
6✔
327
                initialHistoricalSyncer = s
3✔
328
                initialHistoricalSyncSignal = s.ResetSyncedSignal()
3✔
329

3✔
330
                // Restart the timer for our new historical sync peer. This will
3✔
331
                // ensure that all initial syncers receive an equivalent
3✔
332
                // duration before attempting the next sync. Without doing so we
3✔
333
                // might attempt two historical sync back to back if a peer
3✔
334
                // disconnects just before the ticker fires.
3✔
335
                m.cfg.HistoricalSyncTicker.Pause()
3✔
336
                m.cfg.HistoricalSyncTicker.Resume()
3✔
337
        }
3✔
338

339
        for {
6✔
340
                select {
3✔
341
                // A new peer has been connected, so we'll create its
342
                // accompanying GossipSyncer.
343
                case newSyncer := <-m.newSyncers:
3✔
344
                        // If we already have a syncer, then we'll exit early as
3✔
345
                        // we don't want to override it.
3✔
346
                        if _, ok := m.GossipSyncer(newSyncer.peer.PubKey()); ok {
3✔
347
                                close(newSyncer.doneChan)
×
348
                                continue
×
349
                        }
350

351
                        s := m.createGossipSyncer(newSyncer.peer)
3✔
352

3✔
353
                        isPinnedSyncer := m.isPinnedSyncer(s)
3✔
354

3✔
355
                        // attemptHistoricalSync determines whether we should
3✔
356
                        // attempt an initial historical sync when a new peer
3✔
357
                        // connects.
3✔
358
                        attemptHistoricalSync := false
3✔
359

3✔
360
                        m.syncersMu.Lock()
3✔
361
                        switch {
3✔
362
                        // For pinned syncers, we will immediately transition
363
                        // the peer into an active (pinned) sync state.
364
                        case isPinnedSyncer:
3✔
365
                                attemptHistoricalSync = true
3✔
366
                                s.setSyncType(PinnedSync)
3✔
367
                                s.setSyncState(syncerIdle)
3✔
368
                                m.pinnedActiveSyncers[s.cfg.peerPub] = s
3✔
369

370
                        // Regardless of whether the initial historical sync
371
                        // has completed, we'll re-trigger a historical sync if
372
                        // we no longer have any syncers. This might be
373
                        // necessary if we lost all our peers at one point, and
374
                        // now we finally have one again.
375
                        case len(m.activeSyncers) == 0 &&
376
                                len(m.inactiveSyncers) == 0:
3✔
377

3✔
378
                                attemptHistoricalSync =
3✔
379
                                        m.cfg.NumActiveSyncers > 0
3✔
380
                                fallthrough
3✔
381

382
                        // If we've exceeded our total number of active syncers,
383
                        // we'll initialize this GossipSyncer as passive.
384
                        case len(m.activeSyncers) >= m.cfg.NumActiveSyncers:
3✔
385
                                fallthrough
3✔
386

387
                        // If the initial historical sync has yet to complete,
388
                        // then we'll declare it as passive and attempt to
389
                        // transition it when the initial historical sync
390
                        // completes.
391
                        case !m.IsGraphSynced():
3✔
392
                                s.setSyncType(PassiveSync)
3✔
393
                                m.inactiveSyncers[s.cfg.peerPub] = s
3✔
394

395
                        // The initial historical sync has completed, so we can
396
                        // immediately start the GossipSyncer as active.
397
                        default:
3✔
398
                                s.setSyncType(ActiveSync)
3✔
399
                                m.activeSyncers[s.cfg.peerPub] = s
3✔
400
                        }
401
                        m.syncersMu.Unlock()
3✔
402

3✔
403
                        s.Start()
3✔
404

3✔
405
                        // Once we create the GossipSyncer, we'll signal to the
3✔
406
                        // caller that they can proceed since the SyncManager's
3✔
407
                        // internal state has been updated.
3✔
408
                        close(newSyncer.doneChan)
3✔
409

3✔
410
                        // We'll force a historical sync with the first peer we
3✔
411
                        // connect to, to ensure we get as much of the graph as
3✔
412
                        // possible.
3✔
413
                        if !attemptHistoricalSync {
6✔
414
                                continue
3✔
415
                        }
416

417
                        log.Debugf("Attempting initial historical sync with "+
3✔
418
                                "GossipSyncer(%x)", s.cfg.peerPub)
3✔
419

3✔
420
                        if err := s.historicalSync(); err != nil {
3✔
421
                                log.Errorf("Unable to attempt initial "+
×
422
                                        "historical sync with "+
×
423
                                        "GossipSyncer(%x): %v", s.cfg.peerPub,
×
424
                                        err)
×
425
                                continue
×
426
                        }
427

428
                        // Once the historical sync has started, we'll get a
429
                        // keep track of the corresponding syncer to properly
430
                        // handle disconnects. We'll also use a signal to know
431
                        // when the historical sync completed.
432
                        if !isPinnedSyncer {
6✔
433
                                setInitialHistoricalSyncer(s)
3✔
434
                        }
3✔
435

436
                // An existing peer has disconnected, so we'll tear down its
437
                // corresponding GossipSyncer.
438
                case staleSyncer := <-m.staleSyncers:
3✔
439
                        // Once the corresponding GossipSyncer has been stopped
3✔
440
                        // and removed, we'll signal to the caller that they can
3✔
441
                        // proceed since the SyncManager's internal state has
3✔
442
                        // been updated.
3✔
443
                        m.removeGossipSyncer(staleSyncer.peer)
3✔
444
                        close(staleSyncer.doneChan)
3✔
445

3✔
446
                        // If we don't have an initialHistoricalSyncer, or we do
3✔
447
                        // but it is not the peer being disconnected, then we
3✔
448
                        // have nothing left to do and can proceed.
3✔
449
                        switch {
3✔
450
                        case initialHistoricalSyncer == nil:
3✔
451
                                fallthrough
3✔
452
                        case staleSyncer.peer != initialHistoricalSyncer.cfg.peerPub:
3✔
453
                                fallthrough
3✔
454
                        case m.cfg.NumActiveSyncers == 0:
3✔
455
                                continue
3✔
456
                        }
457

458
                        // Otherwise, our initialHistoricalSyncer corresponds to
459
                        // the peer being disconnected, so we'll have to find a
460
                        // replacement.
UNCOV
461
                        log.Debug("Finding replacement for initial " +
×
UNCOV
462
                                "historical sync")
×
UNCOV
463

×
UNCOV
464
                        s := m.forceHistoricalSync()
×
UNCOV
465
                        if s == nil {
×
466
                                log.Debug("No eligible replacement found " +
×
467
                                        "for initial historical sync")
×
468
                                continue
×
469
                        }
470

UNCOV
471
                        log.Debugf("Replaced initial historical "+
×
UNCOV
472
                                "GossipSyncer(%v) with GossipSyncer(%x)",
×
UNCOV
473
                                staleSyncer.peer, s.cfg.peerPub)
×
UNCOV
474

×
UNCOV
475
                        setInitialHistoricalSyncer(s)
×
476

477
                // Our initial historical sync signal has completed, so we'll
478
                // nil all of the relevant fields as they're no longer needed.
479
                case <-initialHistoricalSyncSignal:
3✔
480
                        initialHistoricalSyncer = nil
3✔
481
                        initialHistoricalSyncSignal = nil
3✔
482

3✔
483
                        log.Debug("Initial historical sync completed")
3✔
484

3✔
485
                        // With the initial historical sync complete, we can
3✔
486
                        // begin receiving new graph updates at tip. We'll
3✔
487
                        // determine whether we can have any more active
3✔
488
                        // GossipSyncers. If we do, we'll randomly select some
3✔
489
                        // that are currently passive to transition.
3✔
490
                        m.syncersMu.Lock()
3✔
491
                        numActiveLeft := m.cfg.NumActiveSyncers - len(m.activeSyncers)
3✔
492
                        if numActiveLeft <= 0 {
3✔
493
                                m.syncersMu.Unlock()
×
494
                                continue
×
495
                        }
496

497
                        // We may not even have enough inactive syncers to be
498
                        // transitted. In that case, we will transit all the
499
                        // inactive syncers.
500
                        if len(m.inactiveSyncers) < numActiveLeft {
6✔
501
                                numActiveLeft = len(m.inactiveSyncers)
3✔
502
                        }
3✔
503

504
                        log.Debugf("Attempting to transition %v passive "+
3✔
505
                                "GossipSyncers to active", numActiveLeft)
3✔
506

3✔
507
                        for i := 0; i < numActiveLeft; i++ {
6✔
508
                                chooseRandomSyncer(
3✔
509
                                        m.inactiveSyncers, m.transitionPassiveSyncer,
3✔
510
                                )
3✔
511
                        }
3✔
512

513
                        m.syncersMu.Unlock()
3✔
514

515
                // Our RotateTicker has ticked, so we'll attempt to rotate a
516
                // single active syncer with a passive one.
UNCOV
517
                case <-m.cfg.RotateTicker.Ticks():
×
UNCOV
518
                        m.rotateActiveSyncerCandidate()
×
519

520
                // Our HistoricalSyncTicker has ticked, so we'll randomly select
521
                // a peer and force a historical sync with them.
UNCOV
522
                case <-m.cfg.HistoricalSyncTicker.Ticks():
×
UNCOV
523
                        // To be extra cautious, gate the forceHistoricalSync
×
UNCOV
524
                        // call such that it can only execute if we are
×
UNCOV
525
                        // configured to have a non-zero number of sync peers.
×
UNCOV
526
                        // This way even if the historical sync ticker manages
×
UNCOV
527
                        // to tick we can be sure that a historical sync won't
×
UNCOV
528
                        // accidentally begin.
×
UNCOV
529
                        if m.cfg.NumActiveSyncers == 0 {
×
UNCOV
530
                                continue
×
531
                        }
532

533
                        // If we don't have a syncer available we have nothing
534
                        // to do.
UNCOV
535
                        s := m.forceHistoricalSync()
×
UNCOV
536
                        if s == nil {
×
537
                                continue
×
538
                        }
539

540
                        // If we've already completed a historical sync, we'll
541
                        // skip setting the initial historical syncer.
UNCOV
542
                        if m.IsGraphSynced() {
×
543
                                continue
×
544
                        }
545

546
                        // Otherwise, we'll track the peer we've performed a
547
                        // historical sync with in order to handle the case
548
                        // where our previous historical sync peer did not
549
                        // respond to our queries and we haven't ingested as
550
                        // much of the graph as we should.
UNCOV
551
                        setInitialHistoricalSyncer(s)
×
552

553
                case <-m.quit:
3✔
554
                        return
3✔
555
                }
556
        }
557
}
558

559
// isPinnedSyncer returns true if the passed GossipSyncer is one of our pinned
560
// sync peers.
561
func (m *SyncManager) isPinnedSyncer(s *GossipSyncer) bool {
3✔
562
        _, isPinnedSyncer := m.cfg.PinnedSyncers[s.cfg.peerPub]
3✔
563
        return isPinnedSyncer
3✔
564
}
3✔
565

566
// deriveRateLimitReservation will take the current message and derive a
567
// reservation that can be used to wait on the rate limiter.
568
func deriveRateLimitReservation(rl *rate.Limiter,
569
        msg lnwire.Message) (*rate.Reservation, error) {
3✔
570

3✔
571
        var (
3✔
572
                msgSize uint32
3✔
573
                err     error
3✔
574
        )
3✔
575

3✔
576
        // Figure out the serialized size of the message. If we can't easily
3✔
577
        // compute it, then we'll used the assumed msg size.
3✔
578
        if sMsg, ok := msg.(lnwire.SizeableMessage); ok {
6✔
579
                msgSize, err = sMsg.SerializedSize()
3✔
580
                if err != nil {
3✔
UNCOV
581
                        return nil, err
×
UNCOV
582
                }
×
583
        } else {
×
584
                log.Warnf("Unable to compute serialized size of %T", msg)
×
585

×
586
                msgSize = assumedMsgSize
×
587
        }
×
588

589
        return rl.ReserveN(time.Now(), int(msgSize)), nil
3✔
590
}
591

592
// waitMsgDelay takes a delay, and waits until it has finished.
593
func waitMsgDelay(ctx context.Context, peerPub [33]byte,
594
        limitReservation *rate.Reservation, quit <-chan struct{}) error {
3✔
595

3✔
596
        // If we've already replied a handful of times, we will start to delay
3✔
597
        // responses back to the remote peer. This can help prevent DOS attacks
3✔
598
        // where the remote peer spams us endlessly.
3✔
599
        //
3✔
600
        // We skip checking for reservation.OK() here, as during config
3✔
601
        // validation, we ensure that the burst is enough for a single message
3✔
602
        // to be sent.
3✔
603
        delay := limitReservation.Delay()
3✔
604
        if delay > 0 {
3✔
605
                log.Debugf("GossipSyncer(%x): rate limiting gossip replies, "+
×
606
                        "responding in %s", peerPub, delay)
×
607

×
608
                select {
×
609
                case <-time.After(delay):
×
610

611
                case <-ctx.Done():
×
612
                        limitReservation.Cancel()
×
613

×
614
                        return ErrGossipSyncerExiting
×
615

NEW
616
                case <-quit:
×
617
                        limitReservation.Cancel()
×
618

×
619
                        return ErrGossipSyncerExiting
×
620
                }
621
        }
622

623
        return nil
3✔
624
}
625

626
// maybeRateLimitMsg takes a message, and may wait a period of time to rate
627
// limit the msg.
628
func maybeRateLimitMsg(ctx context.Context, rl *rate.Limiter, peerPub [33]byte,
629
        msg lnwire.Message, quit <-chan struct{}) error {
3✔
630

3✔
631
        delay, err := deriveRateLimitReservation(rl, msg)
3✔
632
        if err != nil {
3✔
633
                return nil
×
634
        }
×
635

636
        return waitMsgDelay(ctx, peerPub, delay, quit)
3✔
637
}
638

639
// sendMessages sends a set of messages to the remote peer.
640
func (m *SyncManager) sendMessages(ctx context.Context, sync bool,
641
        peer lnpeer.Peer, nodeID route.Vertex, msgs ...lnwire.Message) error {
3✔
642

3✔
643
        for _, msg := range msgs {
6✔
644
                err := maybeRateLimitMsg(
3✔
645
                        ctx, m.rateLimiter, nodeID, msg, m.quit,
3✔
646
                )
3✔
647
                if err != nil {
3✔
648
                        return err
×
649
                }
×
650

651
                if err := peer.SendMessageLazy(sync, msg); err != nil {
3✔
652
                        return err
×
653
                }
×
654
        }
655

656
        return nil
3✔
657
}
658

659
// createGossipSyncer creates the GossipSyncer for a newly connected peer.
660
func (m *SyncManager) createGossipSyncer(peer lnpeer.Peer) *GossipSyncer {
3✔
661
        nodeID := route.Vertex(peer.PubKey())
3✔
662
        log.Infof("Creating new GossipSyncer for peer=%x", nodeID[:])
3✔
663

3✔
664
        encoding := lnwire.EncodingSortedPlain
3✔
665
        s := newGossipSyncer(gossipSyncerCfg{
3✔
666
                chainHash:     m.cfg.ChainHash,
3✔
667
                peerPub:       nodeID,
3✔
668
                channelSeries: m.cfg.ChanSeries,
3✔
669
                encodingType:  encoding,
3✔
670
                chunkSize:     encodingTypeToChunkSize[encoding],
3✔
671
                batchSize:     requestBatchSize,
3✔
672
                sendMsg: func(ctx context.Context, sync bool,
3✔
673
                        msgs ...lnwire.Message) error {
6✔
674

3✔
675
                        return m.sendMessages(ctx, sync, peer, nodeID, msgs...)
3✔
676
                },
3✔
677
                ignoreHistoricalFilters:  m.cfg.IgnoreHistoricalFilters,
678
                bestHeight:               m.cfg.BestHeight,
679
                markGraphSynced:          m.markGraphSynced,
680
                maxQueryChanRangeReplies: maxQueryChanRangeReplies,
681
                noTimestampQueryOption:   m.cfg.NoTimestampQueries,
682
                isStillZombieChannel:     m.cfg.IsStillZombieChannel,
683
                msgBytesPerSecond:        m.cfg.PeerMsgBytesPerSecond,
684
        }, m.gossipFilterSema)
685

686
        // Gossip syncers are initialized by default in a PassiveSync type
687
        // and chansSynced state so that they can reply to any peer queries or
688
        // handle any sync transitions.
689
        s.setSyncState(chansSynced)
3✔
690
        s.setSyncType(PassiveSync)
3✔
691

3✔
692
        log.Debugf("Created new GossipSyncer[state=%s type=%s] for peer=%x",
3✔
693
                s.syncState(), s.SyncType(), peer.PubKey())
3✔
694

3✔
695
        return s
3✔
696
}
697

698
// removeGossipSyncer removes all internal references to the disconnected peer's
699
// GossipSyncer and stops it. In the event of an active GossipSyncer being
700
// disconnected, a passive GossipSyncer, if any, will take its place.
701
func (m *SyncManager) removeGossipSyncer(peer route.Vertex) {
3✔
702
        m.syncersMu.Lock()
3✔
703
        defer m.syncersMu.Unlock()
3✔
704

3✔
705
        s, ok := m.gossipSyncer(peer)
3✔
706
        if !ok {
6✔
707
                return
3✔
708
        }
3✔
709

710
        log.Infof("Removing GossipSyncer for peer=%v", peer)
3✔
711

3✔
712
        // We'll stop the GossipSyncer for the disconnected peer in a goroutine
3✔
713
        // to prevent blocking the SyncManager.
3✔
714
        go s.Stop()
3✔
715

3✔
716
        // If it's a non-active syncer, then we can just exit now.
3✔
717
        if _, ok := m.inactiveSyncers[peer]; ok {
6✔
718
                delete(m.inactiveSyncers, peer)
3✔
719
                return
3✔
720
        }
3✔
721

722
        // If it's a pinned syncer, then we can just exit as this doesn't
723
        // affect our active syncer count.
724
        if _, ok := m.pinnedActiveSyncers[peer]; ok {
6✔
725
                delete(m.pinnedActiveSyncers, peer)
3✔
726
                return
3✔
727
        }
3✔
728

729
        // Otherwise, we'll need find a new one to replace it, if any.
730
        delete(m.activeSyncers, peer)
3✔
731
        newActiveSyncer := chooseRandomSyncer(
3✔
732
                m.inactiveSyncers, m.transitionPassiveSyncer,
3✔
733
        )
3✔
734
        if newActiveSyncer == nil {
6✔
735
                return
3✔
736
        }
3✔
737

738
        log.Debugf("Replaced active GossipSyncer(%v) with GossipSyncer(%x)",
1✔
739
                peer, newActiveSyncer.cfg.peerPub)
1✔
740
}
741

742
// rotateActiveSyncerCandidate rotates a single active syncer. In order to
743
// achieve this, the active syncer must be in a chansSynced state in order to
744
// process the sync transition.
UNCOV
745
func (m *SyncManager) rotateActiveSyncerCandidate() {
×
UNCOV
746
        m.syncersMu.Lock()
×
UNCOV
747
        defer m.syncersMu.Unlock()
×
UNCOV
748

×
UNCOV
749
        // If we couldn't find an eligible active syncer to rotate, we can
×
UNCOV
750
        // return early.
×
UNCOV
751
        activeSyncer := chooseRandomSyncer(m.activeSyncers, nil)
×
UNCOV
752
        if activeSyncer == nil {
×
753
                log.Debug("No eligible active syncer to rotate")
×
754
                return
×
755
        }
×
756

757
        // Similarly, if we don't have a candidate to rotate with, we can return
758
        // early as well.
UNCOV
759
        candidate := chooseRandomSyncer(m.inactiveSyncers, nil)
×
UNCOV
760
        if candidate == nil {
×
UNCOV
761
                log.Debug("No eligible candidate to rotate active syncer")
×
UNCOV
762
                return
×
UNCOV
763
        }
×
764

765
        // Otherwise, we'll attempt to transition each syncer to their
766
        // respective new sync type.
UNCOV
767
        log.Debugf("Rotating active GossipSyncer(%x) with GossipSyncer(%x)",
×
UNCOV
768
                activeSyncer.cfg.peerPub, candidate.cfg.peerPub)
×
UNCOV
769

×
UNCOV
770
        if err := m.transitionActiveSyncer(activeSyncer); err != nil {
×
771
                log.Errorf("Unable to transition active GossipSyncer(%x): %v",
×
772
                        activeSyncer.cfg.peerPub, err)
×
773
                return
×
774
        }
×
775

UNCOV
776
        if err := m.transitionPassiveSyncer(candidate); err != nil {
×
777
                log.Errorf("Unable to transition passive GossipSyncer(%x): %v",
×
778
                        activeSyncer.cfg.peerPub, err)
×
779
                return
×
780
        }
×
781
}
782

783
// transitionActiveSyncer transitions an active syncer to a passive one.
784
//
785
// NOTE: This must be called with the syncersMu lock held.
UNCOV
786
func (m *SyncManager) transitionActiveSyncer(s *GossipSyncer) error {
×
UNCOV
787
        log.Debugf("Transitioning active GossipSyncer(%x) to passive",
×
UNCOV
788
                s.cfg.peerPub)
×
UNCOV
789

×
UNCOV
790
        if err := s.ProcessSyncTransition(PassiveSync); err != nil {
×
791
                return err
×
792
        }
×
793

UNCOV
794
        delete(m.activeSyncers, s.cfg.peerPub)
×
UNCOV
795
        m.inactiveSyncers[s.cfg.peerPub] = s
×
UNCOV
796

×
UNCOV
797
        return nil
×
798
}
799

800
// transitionPassiveSyncer transitions a passive syncer to an active one.
801
//
802
// NOTE: This must be called with the syncersMu lock held.
803
func (m *SyncManager) transitionPassiveSyncer(s *GossipSyncer) error {
3✔
804
        log.Debugf("Transitioning passive GossipSyncer(%x) to active",
3✔
805
                s.cfg.peerPub)
3✔
806

3✔
807
        if err := s.ProcessSyncTransition(ActiveSync); err != nil {
3✔
808
                return err
×
809
        }
×
810

811
        delete(m.inactiveSyncers, s.cfg.peerPub)
3✔
812
        m.activeSyncers[s.cfg.peerPub] = s
3✔
813

3✔
814
        return nil
3✔
815
}
816

817
// forceHistoricalSync chooses a syncer with a remote peer at random and forces
818
// a historical sync with it.
UNCOV
819
func (m *SyncManager) forceHistoricalSync() *GossipSyncer {
×
UNCOV
820
        m.syncersMu.Lock()
×
UNCOV
821
        defer m.syncersMu.Unlock()
×
UNCOV
822

×
UNCOV
823
        // We'll sample from both sets of active and inactive syncers in the
×
UNCOV
824
        // event that we don't have any inactive syncers.
×
UNCOV
825
        return chooseRandomSyncer(m.gossipSyncers(), func(s *GossipSyncer) error {
×
UNCOV
826
                return s.historicalSync()
×
UNCOV
827
        })
×
828
}
829

830
// chooseRandomSyncer iterates through the set of syncers given and returns the
831
// first one which was able to successfully perform the action enclosed in the
832
// function closure.
833
//
834
// NOTE: It's possible for a nil value to be returned if there are no eligible
835
// candidate syncers.
836
func chooseRandomSyncer(syncers map[route.Vertex]*GossipSyncer,
837
        action func(*GossipSyncer) error) *GossipSyncer {
3✔
838

3✔
839
        for _, s := range syncers {
6✔
840
                // Only syncers in a chansSynced state are viable for sync
3✔
841
                // transitions, so skip any that aren't.
3✔
842
                if s.syncState() != chansSynced {
3✔
UNCOV
843
                        continue
×
844
                }
845

846
                if action != nil {
6✔
847
                        if err := action(s); err != nil {
3✔
848
                                log.Debugf("Skipping eligible candidate "+
×
849
                                        "GossipSyncer(%x): %v", s.cfg.peerPub,
×
850
                                        err)
×
851
                                continue
×
852
                        }
853
                }
854

855
                return s
3✔
856
        }
857

858
        return nil
3✔
859
}
860

861
// InitSyncState is called by outside sub-systems when a connection is
862
// established to a new peer that understands how to perform channel range
863
// queries. We'll allocate a new GossipSyncer for it, and start any goroutines
864
// needed to handle new queries. The first GossipSyncer registered with the
865
// SyncManager will attempt a historical sync to ensure we have as much of the
866
// public channel graph as possible.
867
//
868
// TODO(wilmer): Only mark as ActiveSync if this isn't a channel peer.
869
func (m *SyncManager) InitSyncState(peer lnpeer.Peer) error {
3✔
870
        done := make(chan struct{})
3✔
871

3✔
872
        select {
3✔
873
        case m.newSyncers <- &newSyncer{
874
                peer:     peer,
875
                doneChan: done,
876
        }:
3✔
877
        case <-m.quit:
×
878
                return ErrSyncManagerExiting
×
879
        }
880

881
        select {
3✔
882
        case <-done:
3✔
883
                return nil
3✔
884
        case <-m.quit:
×
885
                return ErrSyncManagerExiting
×
886
        }
887
}
888

889
// PruneSyncState is called by outside sub-systems once a peer that we were
890
// previously connected to has been disconnected. In this case we can stop the
891
// existing GossipSyncer assigned to the peer and free up resources.
892
func (m *SyncManager) PruneSyncState(peer route.Vertex) {
3✔
893
        done := make(chan struct{})
3✔
894

3✔
895
        // We avoid returning an error when the SyncManager is stopped since the
3✔
896
        // GossipSyncer will be stopped then anyway.
3✔
897
        select {
3✔
898
        case m.staleSyncers <- &staleSyncer{
899
                peer:     peer,
900
                doneChan: done,
901
        }:
3✔
902
        case <-m.quit:
×
903
                return
×
904
        }
905

906
        select {
3✔
907
        case <-done:
3✔
908
        case <-m.quit:
×
909
        }
910
}
911

912
// GossipSyncer returns the associated gossip syncer of a peer. The boolean
913
// returned signals whether there exists a gossip syncer for the peer.
914
func (m *SyncManager) GossipSyncer(peer route.Vertex) (*GossipSyncer, bool) {
3✔
915
        m.syncersMu.Lock()
3✔
916
        defer m.syncersMu.Unlock()
3✔
917
        return m.gossipSyncer(peer)
3✔
918
}
3✔
919

920
// gossipSyncer returns the associated gossip syncer of a peer. The boolean
921
// returned signals whether there exists a gossip syncer for the peer.
922
func (m *SyncManager) gossipSyncer(peer route.Vertex) (*GossipSyncer, bool) {
3✔
923
        syncer, ok := m.inactiveSyncers[peer]
3✔
924
        if ok {
6✔
925
                return syncer, true
3✔
926
        }
3✔
927
        syncer, ok = m.activeSyncers[peer]
3✔
928
        if ok {
6✔
929
                return syncer, true
3✔
930
        }
3✔
931
        syncer, ok = m.pinnedActiveSyncers[peer]
3✔
932
        if ok {
6✔
933
                return syncer, true
3✔
934
        }
3✔
935
        return nil, false
3✔
936
}
937

938
// GossipSyncers returns all of the currently initialized gossip syncers.
939
func (m *SyncManager) GossipSyncers() map[route.Vertex]*GossipSyncer {
3✔
940
        m.syncersMu.Lock()
3✔
941
        defer m.syncersMu.Unlock()
3✔
942
        return m.gossipSyncers()
3✔
943
}
3✔
944

945
// gossipSyncers returns all of the currently initialized gossip syncers.
946
func (m *SyncManager) gossipSyncers() map[route.Vertex]*GossipSyncer {
3✔
947
        numSyncers := len(m.inactiveSyncers) + len(m.activeSyncers)
3✔
948
        syncers := make(map[route.Vertex]*GossipSyncer, numSyncers)
3✔
949

3✔
950
        for _, syncer := range m.inactiveSyncers {
6✔
951
                syncers[syncer.cfg.peerPub] = syncer
3✔
952
        }
3✔
953
        for _, syncer := range m.activeSyncers {
6✔
954
                syncers[syncer.cfg.peerPub] = syncer
3✔
955
        }
3✔
956

957
        return syncers
3✔
958
}
959

960
// markGraphSynced allows us to report that the initial historical sync has
961
// completed.
962
func (m *SyncManager) markGraphSynced() {
3✔
963
        atomic.StoreInt32(&m.initialHistoricalSyncCompleted, 1)
3✔
964
}
3✔
965

966
// IsGraphSynced determines whether we've completed our initial historical sync.
967
// The initial historical sync is done to ensure we've ingested as much of the
968
// public graph as possible.
969
func (m *SyncManager) IsGraphSynced() bool {
3✔
970
        return atomic.LoadInt32(&m.initialHistoricalSyncCompleted) == 1
3✔
971
}
3✔
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