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

lightningnetwork / lnd / 13593508312

28 Feb 2025 05:41PM UTC coverage: 58.287% (-10.4%) from 68.65%
13593508312

Pull #9458

github

web-flow
Merge d40067c0c into f1182e433
Pull Request #9458: multi+server.go: add initial permissions for some peers

346 of 548 new or added lines in 10 files covered. (63.14%)

27412 existing lines in 442 files now uncovered.

94709 of 162488 relevant lines covered (58.29%)

1.81 hits per line

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

73.88
/discovery/syncer.go
1
package discovery
2

3
import (
4
        "errors"
5
        "fmt"
6
        "math"
7
        "math/rand"
8
        "sort"
9
        "sync"
10
        "sync/atomic"
11
        "time"
12

13
        "github.com/btcsuite/btcd/chaincfg/chainhash"
14
        "github.com/lightningnetwork/lnd/graph"
15
        graphdb "github.com/lightningnetwork/lnd/graph/db"
16
        "github.com/lightningnetwork/lnd/lnpeer"
17
        "github.com/lightningnetwork/lnd/lnwire"
18
        "golang.org/x/time/rate"
19
)
20

21
// SyncerType encapsulates the different types of syncing mechanisms for a
22
// gossip syncer.
23
type SyncerType uint8
24

25
const (
26
        // ActiveSync denotes that a gossip syncer:
27
        //
28
        // 1. Should not attempt to synchronize with the remote peer for
29
        //    missing channels.
30
        // 2. Should respond to queries from the remote peer.
31
        // 3. Should receive new updates from the remote peer.
32
        //
33
        // They are started in a chansSynced state in order to accomplish their
34
        // responsibilities above.
35
        ActiveSync SyncerType = iota
36

37
        // PassiveSync denotes that a gossip syncer:
38
        //
39
        // 1. Should not attempt to synchronize with the remote peer for
40
        //    missing channels.
41
        // 2. Should respond to queries from the remote peer.
42
        // 3. Should not receive new updates from the remote peer.
43
        //
44
        // They are started in a chansSynced state in order to accomplish their
45
        // responsibilities above.
46
        PassiveSync
47

48
        // PinnedSync denotes an ActiveSync that doesn't count towards the
49
        // default active syncer limits and is always active throughout the
50
        // duration of the peer's connection. Each pinned syncer will begin by
51
        // performing a historical sync to ensure we are well synchronized with
52
        // their routing table.
53
        PinnedSync
54
)
55

56
// String returns a human readable string describing the target SyncerType.
57
func (t SyncerType) String() string {
3✔
58
        switch t {
3✔
59
        case ActiveSync:
3✔
60
                return "ActiveSync"
3✔
61
        case PassiveSync:
3✔
62
                return "PassiveSync"
3✔
63
        case PinnedSync:
3✔
64
                return "PinnedSync"
3✔
65
        default:
×
66
                return fmt.Sprintf("unknown sync type %d", t)
×
67
        }
68
}
69

70
// IsActiveSync returns true if the SyncerType should set a GossipTimestampRange
71
// allowing new gossip messages to be received from the peer.
72
func (t SyncerType) IsActiveSync() bool {
3✔
73
        switch t {
3✔
74
        case ActiveSync, PinnedSync:
3✔
75
                return true
3✔
76
        default:
3✔
77
                return false
3✔
78
        }
79
}
80

81
// syncerState is an enum that represents the current state of the GossipSyncer.
82
// As the syncer is a state machine, we'll gate our actions based off of the
83
// current state and the next incoming message.
84
type syncerState uint32
85

86
const (
87
        // syncingChans is the default state of the GossipSyncer. We start in
88
        // this state when a new peer first connects and we don't yet know if
89
        // we're fully synchronized.
90
        syncingChans syncerState = iota
91

92
        // waitingQueryRangeReply is the second main phase of the GossipSyncer.
93
        // We enter this state after we send out our first QueryChannelRange
94
        // reply. We'll stay in this state until the remote party sends us a
95
        // ReplyShortChanIDsEnd message that indicates they've responded to our
96
        // query entirely. After this state, we'll transition to
97
        // waitingQueryChanReply after we send out requests for all the new
98
        // chan ID's to us.
99
        waitingQueryRangeReply
100

101
        // queryNewChannels is the third main phase of the GossipSyncer.  In
102
        // this phase we'll send out all of our QueryShortChanIDs messages in
103
        // response to the new channels that we don't yet know about.
104
        queryNewChannels
105

106
        // waitingQueryChanReply is the fourth main phase of the GossipSyncer.
107
        // We enter this phase once we've sent off a query chink to the remote
108
        // peer.  We'll stay in this phase until we receive a
109
        // ReplyShortChanIDsEnd message which indicates that the remote party
110
        // has responded to all of our requests.
111
        waitingQueryChanReply
112

113
        // chansSynced is the terminal stage of the GossipSyncer. Once we enter
114
        // this phase, we'll send out our update horizon, which filters out the
115
        // set of channel updates that we're interested in. In this state,
116
        // we'll be able to accept any outgoing messages from the
117
        // AuthenticatedGossiper, and decide if we should forward them to our
118
        // target peer based on its update horizon.
119
        chansSynced
120

121
        // syncerIdle is a state in which the gossip syncer can handle external
122
        // requests to transition or perform historical syncs. It is used as the
123
        // initial state for pinned syncers, as well as a fallthrough case for
124
        // chansSynced allowing fully synced peers to facilitate requests.
125
        syncerIdle
126
)
127

128
// String returns a human readable string describing the target syncerState.
129
func (s syncerState) String() string {
3✔
130
        switch s {
3✔
131
        case syncingChans:
3✔
132
                return "syncingChans"
3✔
133

134
        case waitingQueryRangeReply:
3✔
135
                return "waitingQueryRangeReply"
3✔
136

137
        case queryNewChannels:
3✔
138
                return "queryNewChannels"
3✔
139

140
        case waitingQueryChanReply:
3✔
141
                return "waitingQueryChanReply"
3✔
142

143
        case chansSynced:
3✔
144
                return "chansSynced"
3✔
145

146
        case syncerIdle:
3✔
147
                return "syncerIdle"
3✔
148

149
        default:
×
150
                return "UNKNOWN STATE"
×
151
        }
152
}
153

154
const (
155
        // DefaultMaxUndelayedQueryReplies specifies how many gossip queries we
156
        // will respond to immediately before starting to delay responses.
157
        DefaultMaxUndelayedQueryReplies = 10
158

159
        // DefaultDelayedQueryReplyInterval is the length of time we will wait
160
        // before responding to gossip queries after replying to
161
        // maxUndelayedQueryReplies queries.
162
        DefaultDelayedQueryReplyInterval = 5 * time.Second
163

164
        // maxQueryChanRangeReplies specifies the default limit of replies to
165
        // process for a single QueryChannelRange request.
166
        maxQueryChanRangeReplies = 500
167

168
        // maxQueryChanRangeRepliesZlibFactor specifies the factor applied to
169
        // the maximum number of replies allowed for zlib encoded replies.
170
        maxQueryChanRangeRepliesZlibFactor = 4
171

172
        // chanRangeQueryBuffer is the number of blocks back that we'll go when
173
        // asking the remote peer for their any channels they know of beyond
174
        // our highest known channel ID.
175
        chanRangeQueryBuffer = 144
176

177
        // syncTransitionTimeout is the default timeout in which we'll wait up
178
        // to when attempting to perform a sync transition.
179
        syncTransitionTimeout = 5 * time.Second
180

181
        // requestBatchSize is the maximum number of channels we will query the
182
        // remote peer for in a QueryShortChanIDs message.
183
        requestBatchSize = 500
184

185
        // syncerBufferSize is the size of the syncer's buffers.
186
        syncerBufferSize = 5
187
)
188

189
var (
190
        // encodingTypeToChunkSize maps an encoding type, to the max number of
191
        // short chan ID's using the encoding type that we can fit into a
192
        // single message safely.
193
        encodingTypeToChunkSize = map[lnwire.QueryEncoding]int32{
194
                lnwire.EncodingSortedPlain: 8000,
195
        }
196

197
        // ErrGossipSyncerExiting signals that the syncer has been killed.
198
        ErrGossipSyncerExiting = errors.New("gossip syncer exiting")
199

200
        // ErrSyncTransitionTimeout is an error returned when we've timed out
201
        // attempting to perform a sync transition.
202
        ErrSyncTransitionTimeout = errors.New("timed out attempting to " +
203
                "transition sync type")
204

205
        // zeroTimestamp is the timestamp we'll use when we want to indicate to
206
        // peers that we do not want to receive any new graph updates.
207
        zeroTimestamp time.Time
208
)
209

210
// syncTransitionReq encapsulates a request for a gossip syncer sync transition.
211
type syncTransitionReq struct {
212
        newSyncType SyncerType
213
        errChan     chan error
214
}
215

216
// historicalSyncReq encapsulates a request for a gossip syncer to perform a
217
// historical sync.
218
type historicalSyncReq struct {
219
        // doneChan is a channel that serves as a signal and is closed to ensure
220
        // the historical sync is attempted by the time we return to the caller.
221
        doneChan chan struct{}
222
}
223

224
// gossipSyncerCfg is a struct that packages all the information a GossipSyncer
225
// needs to carry out its duties.
226
type gossipSyncerCfg struct {
227
        // chainHash is the chain that this syncer is responsible for.
228
        chainHash chainhash.Hash
229

230
        // peerPub is the public key of the peer we're syncing with, serialized
231
        // in compressed format.
232
        peerPub [33]byte
233

234
        // channelSeries is the primary interface that we'll use to generate
235
        // our queries and respond to the queries of the remote peer.
236
        channelSeries ChannelGraphTimeSeries
237

238
        // encodingType is the current encoding type we're aware of. Requests
239
        // with different encoding types will be rejected.
240
        encodingType lnwire.QueryEncoding
241

242
        // chunkSize is the max number of short chan IDs using the syncer's
243
        // encoding type that we can fit into a single message safely.
244
        chunkSize int32
245

246
        // batchSize is the max number of channels the syncer will query from
247
        // the remote node in a single QueryShortChanIDs request.
248
        batchSize int32
249

250
        // sendToPeer sends a variadic number of messages to the remote peer.
251
        // This method should not block while waiting for sends to be written
252
        // to the wire.
253
        sendToPeer func(...lnwire.Message) error
254

255
        // sendToPeerSync sends a variadic number of messages to the remote
256
        // peer, blocking until all messages have been sent successfully or a
257
        // write error is encountered.
258
        sendToPeerSync func(...lnwire.Message) error
259

260
        // maxUndelayedQueryReplies specifies how many gossip queries we will
261
        // respond to immediately before starting to delay responses.
262
        maxUndelayedQueryReplies int
263

264
        // delayedQueryReplyInterval is the length of time we will wait before
265
        // responding to gossip queries after replying to
266
        // maxUndelayedQueryReplies queries.
267
        delayedQueryReplyInterval time.Duration
268

269
        // noSyncChannels will prevent the GossipSyncer from spawning a
270
        // channelGraphSyncer, meaning we will not try to reconcile unknown
271
        // channels with the remote peer.
272
        noSyncChannels bool
273

274
        // noReplyQueries will prevent the GossipSyncer from spawning a
275
        // replyHandler, meaning we will not reply to queries from our remote
276
        // peer.
277
        noReplyQueries bool
278

279
        // noTimestampQueryOption will prevent the GossipSyncer from querying
280
        // timestamps of announcement messages from the peer, and it will
281
        // prevent it from responding to timestamp queries.
282
        noTimestampQueryOption bool
283

284
        // ignoreHistoricalFilters will prevent syncers from replying with
285
        // historical data when the remote peer sets a gossip_timestamp_range.
286
        // This prevents ranges with old start times from causing us to dump the
287
        // graph on connect.
288
        ignoreHistoricalFilters bool
289

290
        // bestHeight returns the latest height known of the chain.
291
        bestHeight func() uint32
292

293
        // markGraphSynced updates the SyncManager's perception of whether we
294
        // have completed at least one historical sync.
295
        markGraphSynced func()
296

297
        // maxQueryChanRangeReplies is the maximum number of replies we'll allow
298
        // for a single QueryChannelRange request.
299
        maxQueryChanRangeReplies uint32
300

301
        // isStillZombieChannel takes the timestamps of the latest channel
302
        // updates for a channel and returns true if the channel should be
303
        // considered a zombie based on these timestamps.
304
        isStillZombieChannel func(time.Time, time.Time) bool
305
}
306

307
// GossipSyncer is a struct that handles synchronizing the channel graph state
308
// with a remote peer. The GossipSyncer implements a state machine that will
309
// progressively ensure we're synchronized with the channel state of the remote
310
// node. Once both nodes have been synchronized, we'll use an update filter to
311
// filter out which messages should be sent to a remote peer based on their
312
// update horizon. If the update horizon isn't specified, then we won't send
313
// them any channel updates at all.
314
type GossipSyncer struct {
315
        started sync.Once
316
        stopped sync.Once
317

318
        // state is the current state of the GossipSyncer.
319
        //
320
        // NOTE: This variable MUST be used atomically.
321
        state uint32
322

323
        // syncType denotes the SyncerType the gossip syncer is currently
324
        // exercising.
325
        //
326
        // NOTE: This variable MUST be used atomically.
327
        syncType uint32
328

329
        // remoteUpdateHorizon is the update horizon of the remote peer. We'll
330
        // use this to properly filter out any messages.
331
        remoteUpdateHorizon *lnwire.GossipTimestampRange
332

333
        // localUpdateHorizon is our local update horizon, we'll use this to
334
        // determine if we've already sent out our update.
335
        localUpdateHorizon *lnwire.GossipTimestampRange
336

337
        // syncTransitions is a channel through which new sync type transition
338
        // requests will be sent through. These requests should only be handled
339
        // when the gossip syncer is in a chansSynced state to ensure its state
340
        // machine behaves as expected.
341
        syncTransitionReqs chan *syncTransitionReq
342

343
        // historicalSyncReqs is a channel that serves as a signal for the
344
        // gossip syncer to perform a historical sync. These can only be done
345
        // once the gossip syncer is in a chansSynced state to ensure its state
346
        // machine behaves as expected.
347
        historicalSyncReqs chan *historicalSyncReq
348

349
        // genHistoricalChanRangeQuery when true signals to the gossip syncer
350
        // that it should request the remote peer for all of its known channel
351
        // IDs starting from the genesis block of the chain. This can only
352
        // happen if the gossip syncer receives a request to attempt a
353
        // historical sync. It can be unset if the syncer ever transitions from
354
        // PassiveSync to ActiveSync.
355
        genHistoricalChanRangeQuery bool
356

357
        // gossipMsgs is a channel that all responses to our queries from the
358
        // target peer will be sent over, these will be read by the
359
        // channelGraphSyncer.
360
        gossipMsgs chan lnwire.Message
361

362
        // queryMsgs is a channel that all queries from the remote peer will be
363
        // received over, these will be read by the replyHandler.
364
        queryMsgs chan lnwire.Message
365

366
        // curQueryRangeMsg keeps track of the latest QueryChannelRange message
367
        // we've sent to a peer to ensure we've consumed all expected replies.
368
        // This field is primarily used within the waitingQueryChanReply state.
369
        curQueryRangeMsg *lnwire.QueryChannelRange
370

371
        // prevReplyChannelRange keeps track of the previous ReplyChannelRange
372
        // message we've received from a peer to ensure they've fully replied to
373
        // our query by ensuring they covered our requested block range. This
374
        // field is primarily used within the waitingQueryChanReply state.
375
        prevReplyChannelRange *lnwire.ReplyChannelRange
376

377
        // bufferedChanRangeReplies is used in the waitingQueryChanReply to
378
        // buffer all the chunked response to our query.
379
        bufferedChanRangeReplies []graphdb.ChannelUpdateInfo
380

381
        // numChanRangeRepliesRcvd is used to track the number of replies
382
        // received as part of a QueryChannelRange. This field is primarily used
383
        // within the waitingQueryChanReply state.
384
        numChanRangeRepliesRcvd uint32
385

386
        // newChansToQuery is used to pass the set of channels we should query
387
        // for from the waitingQueryChanReply state to the queryNewChannels
388
        // state.
389
        newChansToQuery []lnwire.ShortChannelID
390

391
        cfg gossipSyncerCfg
392

393
        // rateLimiter dictates the frequency with which we will reply to gossip
394
        // queries from a peer. This is used to delay responses to peers to
395
        // prevent DOS vulnerabilities if they are spamming with an unreasonable
396
        // number of queries.
397
        rateLimiter *rate.Limiter
398

399
        // syncedSignal is a channel that, if set, will be closed when the
400
        // GossipSyncer reaches its terminal chansSynced state.
401
        syncedSignal chan struct{}
402

403
        // syncerSema is used to more finely control the syncer's ability to
404
        // respond to gossip timestamp range messages.
405
        syncerSema chan struct{}
406

407
        sync.Mutex
408

409
        quit chan struct{}
410
        wg   sync.WaitGroup
411
}
412

413
// newGossipSyncer returns a new instance of the GossipSyncer populated using
414
// the passed config.
415
func newGossipSyncer(cfg gossipSyncerCfg, sema chan struct{}) *GossipSyncer {
3✔
416
        // If no parameter was specified for max undelayed query replies, set it
3✔
417
        // to the default of 5 queries.
3✔
418
        if cfg.maxUndelayedQueryReplies <= 0 {
3✔
UNCOV
419
                cfg.maxUndelayedQueryReplies = DefaultMaxUndelayedQueryReplies
×
UNCOV
420
        }
×
421

422
        // If no parameter was specified for delayed query reply interval, set
423
        // to the default of 5 seconds.
424
        if cfg.delayedQueryReplyInterval <= 0 {
3✔
425
                cfg.delayedQueryReplyInterval = DefaultDelayedQueryReplyInterval
×
426
        }
×
427

428
        // Construct a rate limiter that will govern how frequently we reply to
429
        // gossip queries from this peer. The limiter will automatically adjust
430
        // during periods of quiescence, and increase the reply interval under
431
        // load.
432
        interval := rate.Every(cfg.delayedQueryReplyInterval)
3✔
433
        rateLimiter := rate.NewLimiter(
3✔
434
                interval, cfg.maxUndelayedQueryReplies,
3✔
435
        )
3✔
436

3✔
437
        return &GossipSyncer{
3✔
438
                cfg:                cfg,
3✔
439
                rateLimiter:        rateLimiter,
3✔
440
                syncTransitionReqs: make(chan *syncTransitionReq),
3✔
441
                historicalSyncReqs: make(chan *historicalSyncReq),
3✔
442
                gossipMsgs:         make(chan lnwire.Message, syncerBufferSize),
3✔
443
                queryMsgs:          make(chan lnwire.Message, syncerBufferSize),
3✔
444
                syncerSema:         sema,
3✔
445
                quit:               make(chan struct{}),
3✔
446
        }
3✔
447
}
448

449
// Start starts the GossipSyncer and any goroutines that it needs to carry out
450
// its duties.
451
func (g *GossipSyncer) Start() {
3✔
452
        g.started.Do(func() {
6✔
453
                log.Debugf("Starting GossipSyncer(%x)", g.cfg.peerPub[:])
3✔
454

3✔
455
                // TODO(conner): only spawn channelGraphSyncer if remote
3✔
456
                // supports gossip queries, and only spawn replyHandler if we
3✔
457
                // advertise support
3✔
458
                if !g.cfg.noSyncChannels {
6✔
459
                        g.wg.Add(1)
3✔
460
                        go g.channelGraphSyncer()
3✔
461
                }
3✔
462
                if !g.cfg.noReplyQueries {
6✔
463
                        g.wg.Add(1)
3✔
464
                        go g.replyHandler()
3✔
465
                }
3✔
466
        })
467
}
468

469
// Stop signals the GossipSyncer for a graceful exit, then waits until it has
470
// exited.
471
func (g *GossipSyncer) Stop() {
3✔
472
        g.stopped.Do(func() {
6✔
473
                log.Debugf("Stopping GossipSyncer(%x)", g.cfg.peerPub[:])
3✔
474
                defer log.Debugf("GossipSyncer(%x) stopped", g.cfg.peerPub[:])
3✔
475

3✔
476
                close(g.quit)
3✔
477
                g.wg.Wait()
3✔
478
        })
3✔
479
}
480

481
// handleSyncingChans handles the state syncingChans for the GossipSyncer. When
482
// in this state, we will send a QueryChannelRange msg to our peer and advance
483
// the syncer's state to waitingQueryRangeReply.
484
func (g *GossipSyncer) handleSyncingChans() {
3✔
485
        // Prepare the query msg.
3✔
486
        queryRangeMsg, err := g.genChanRangeQuery(g.genHistoricalChanRangeQuery)
3✔
487
        if err != nil {
3✔
488
                log.Errorf("Unable to gen chan range query: %v", err)
×
489
                return
×
490
        }
×
491

492
        // Acquire a lock so the following state transition is atomic.
493
        //
494
        // NOTE: We must lock the following steps as it's possible we get an
495
        // immediate response (ReplyChannelRange) after sending the query msg.
496
        // The response is handled in ProcessQueryMsg, which requires the
497
        // current state to be waitingQueryRangeReply.
498
        g.Lock()
3✔
499
        defer g.Unlock()
3✔
500

3✔
501
        // Send the msg to the remote peer, which is non-blocking as
3✔
502
        // `sendToPeer` only queues the msg in Brontide.
3✔
503
        err = g.cfg.sendToPeer(queryRangeMsg)
3✔
504
        if err != nil {
3✔
505
                log.Errorf("Unable to send chan range query: %v", err)
×
506
                return
×
507
        }
×
508

509
        // With the message sent successfully, we'll transition into the next
510
        // state where we wait for their reply.
511
        g.setSyncState(waitingQueryRangeReply)
3✔
512
}
513

514
// channelGraphSyncer is the main goroutine responsible for ensuring that we
515
// properly channel graph state with the remote peer, and also that we only
516
// send them messages which actually pass their defined update horizon.
517
func (g *GossipSyncer) channelGraphSyncer() {
3✔
518
        defer g.wg.Done()
3✔
519

3✔
520
        for {
6✔
521
                state := g.syncState()
3✔
522
                syncType := g.SyncType()
3✔
523

3✔
524
                log.Debugf("GossipSyncer(%x): state=%v, type=%v",
3✔
525
                        g.cfg.peerPub[:], state, syncType)
3✔
526

3✔
527
                switch state {
3✔
528
                // When we're in this state, we're trying to synchronize our
529
                // view of the network with the remote peer. We'll kick off
530
                // this sync by asking them for the set of channels they
531
                // understand, as we'll as responding to any other queries by
532
                // them.
533
                case syncingChans:
3✔
534
                        g.handleSyncingChans()
3✔
535

536
                // In this state, we've sent out our initial channel range
537
                // query and are waiting for the final response from the remote
538
                // peer before we perform a diff to see with channels they know
539
                // of that we don't.
540
                case waitingQueryRangeReply:
3✔
541
                        // We'll wait to either process a new message from the
3✔
542
                        // remote party, or exit due to the gossiper exiting,
3✔
543
                        // or us being signalled to do so.
3✔
544
                        select {
3✔
545
                        case msg := <-g.gossipMsgs:
3✔
546
                                // The remote peer is sending a response to our
3✔
547
                                // initial query, we'll collate this response,
3✔
548
                                // and see if it's the final one in the series.
3✔
549
                                // If so, we can then transition to querying
3✔
550
                                // for the new channels.
3✔
551
                                queryReply, ok := msg.(*lnwire.ReplyChannelRange)
3✔
552
                                if ok {
6✔
553
                                        err := g.processChanRangeReply(queryReply)
3✔
554
                                        if err != nil {
3✔
555
                                                log.Errorf("Unable to "+
×
556
                                                        "process chan range "+
×
557
                                                        "query: %v", err)
×
558
                                                return
×
559
                                        }
×
560
                                        continue
3✔
561
                                }
562

563
                                log.Warnf("Unexpected message: %T in state=%v",
×
564
                                        msg, state)
×
565

UNCOV
566
                        case <-g.quit:
×
UNCOV
567
                                return
×
568
                        }
569

570
                // We'll enter this state once we've discovered which channels
571
                // the remote party knows of that we don't yet know of
572
                // ourselves.
573
                case queryNewChannels:
3✔
574
                        // First, we'll attempt to continue our channel
3✔
575
                        // synchronization by continuing to send off another
3✔
576
                        // query chunk.
3✔
577
                        done, err := g.synchronizeChanIDs()
3✔
578
                        if err != nil {
3✔
579
                                log.Errorf("Unable to sync chan IDs: %v", err)
×
580
                        }
×
581

582
                        // If this wasn't our last query, then we'll need to
583
                        // transition to our waiting state.
584
                        if !done {
6✔
585
                                g.setSyncState(waitingQueryChanReply)
3✔
586
                                continue
3✔
587
                        }
588

589
                        // If we're fully synchronized, then we can transition
590
                        // to our terminal state.
591
                        g.setSyncState(chansSynced)
3✔
592

3✔
593
                        // Ensure that the sync manager becomes aware that the
3✔
594
                        // historical sync completed so synced_to_graph is
3✔
595
                        // updated over rpc.
3✔
596
                        g.cfg.markGraphSynced()
3✔
597

598
                // In this state, we've just sent off a new query for channels
599
                // that we don't yet know of. We'll remain in this state until
600
                // the remote party signals they've responded to our query in
601
                // totality.
602
                case waitingQueryChanReply:
3✔
603
                        // Once we've sent off our query, we'll wait for either
3✔
604
                        // an ending reply, or just another query from the
3✔
605
                        // remote peer.
3✔
606
                        select {
3✔
607
                        case msg := <-g.gossipMsgs:
3✔
608
                                // If this is the final reply to one of our
3✔
609
                                // queries, then we'll loop back into our query
3✔
610
                                // state to send of the remaining query chunks.
3✔
611
                                _, ok := msg.(*lnwire.ReplyShortChanIDsEnd)
3✔
612
                                if ok {
6✔
613
                                        g.setSyncState(queryNewChannels)
3✔
614
                                        continue
3✔
615
                                }
616

617
                                log.Warnf("Unexpected message: %T in state=%v",
×
618
                                        msg, state)
×
619

UNCOV
620
                        case <-g.quit:
×
UNCOV
621
                                return
×
622
                        }
623

624
                // This is our final terminal state where we'll only reply to
625
                // any further queries by the remote peer.
626
                case chansSynced:
3✔
627
                        g.Lock()
3✔
628
                        if g.syncedSignal != nil {
6✔
629
                                close(g.syncedSignal)
3✔
630
                                g.syncedSignal = nil
3✔
631
                        }
3✔
632
                        g.Unlock()
3✔
633

3✔
634
                        // If we haven't yet sent out our update horizon, and
3✔
635
                        // we want to receive real-time channel updates, we'll
3✔
636
                        // do so now.
3✔
637
                        if g.localUpdateHorizon == nil &&
3✔
638
                                syncType.IsActiveSync() {
6✔
639

3✔
640
                                err := g.sendGossipTimestampRange(
3✔
641
                                        time.Now(), math.MaxUint32,
3✔
642
                                )
3✔
643
                                if err != nil {
3✔
644
                                        log.Errorf("Unable to send update "+
×
645
                                                "horizon to %x: %v",
×
646
                                                g.cfg.peerPub, err)
×
647
                                }
×
648
                        }
649
                        // With our horizon set, we'll simply reply to any new
650
                        // messages or process any state transitions and exit if
651
                        // needed.
652
                        fallthrough
3✔
653

654
                // Pinned peers will begin in this state, since they will
655
                // immediately receive a request to perform a historical sync.
656
                // Otherwise, we fall through after ending in chansSynced to
657
                // facilitate new requests.
658
                case syncerIdle:
3✔
659
                        select {
3✔
660
                        case req := <-g.syncTransitionReqs:
3✔
661
                                req.errChan <- g.handleSyncTransition(req)
3✔
662

663
                        case req := <-g.historicalSyncReqs:
3✔
664
                                g.handleHistoricalSync(req)
3✔
665

666
                        case <-g.quit:
3✔
667
                                return
3✔
668
                        }
669
                }
670
        }
671
}
672

673
// replyHandler is an event loop whose sole purpose is to reply to the remote
674
// peers queries. Our replyHandler will respond to messages generated by their
675
// channelGraphSyncer, and vice versa. Each party's channelGraphSyncer drives
676
// the other's replyHandler, allowing the replyHandler to operate independently
677
// from the state machine maintained on the same node.
678
//
679
// NOTE: This method MUST be run as a goroutine.
680
func (g *GossipSyncer) replyHandler() {
3✔
681
        defer g.wg.Done()
3✔
682

3✔
683
        for {
6✔
684
                select {
3✔
685
                case msg := <-g.queryMsgs:
3✔
686
                        err := g.replyPeerQueries(msg)
3✔
687
                        switch {
3✔
688
                        case err == ErrGossipSyncerExiting:
×
689
                                return
×
690

691
                        case err == lnpeer.ErrPeerExiting:
×
692
                                return
×
693

694
                        case err != nil:
×
695
                                log.Errorf("Unable to reply to peer "+
×
696
                                        "query: %v", err)
×
697
                        }
698

699
                case <-g.quit:
3✔
700
                        return
3✔
701
                }
702
        }
703
}
704

705
// sendGossipTimestampRange constructs and sets a GossipTimestampRange for the
706
// syncer and sends it to the remote peer.
707
func (g *GossipSyncer) sendGossipTimestampRange(firstTimestamp time.Time,
708
        timestampRange uint32) error {
3✔
709

3✔
710
        endTimestamp := firstTimestamp.Add(
3✔
711
                time.Duration(timestampRange) * time.Second,
3✔
712
        )
3✔
713

3✔
714
        log.Infof("GossipSyncer(%x): applying gossipFilter(start=%v, end=%v)",
3✔
715
                g.cfg.peerPub[:], firstTimestamp, endTimestamp)
3✔
716

3✔
717
        localUpdateHorizon := &lnwire.GossipTimestampRange{
3✔
718
                ChainHash:      g.cfg.chainHash,
3✔
719
                FirstTimestamp: uint32(firstTimestamp.Unix()),
3✔
720
                TimestampRange: timestampRange,
3✔
721
        }
3✔
722

3✔
723
        if err := g.cfg.sendToPeer(localUpdateHorizon); err != nil {
3✔
724
                return err
×
725
        }
×
726

727
        if firstTimestamp == zeroTimestamp && timestampRange == 0 {
3✔
UNCOV
728
                g.localUpdateHorizon = nil
×
729
        } else {
3✔
730
                g.localUpdateHorizon = localUpdateHorizon
3✔
731
        }
3✔
732

733
        return nil
3✔
734
}
735

736
// synchronizeChanIDs is called by the channelGraphSyncer when we need to query
737
// the remote peer for its known set of channel IDs within a particular block
738
// range. This method will be called continually until the entire range has
739
// been queried for with a response received. We'll chunk our requests as
740
// required to ensure they fit into a single message. We may re-renter this
741
// state in the case that chunking is required.
742
func (g *GossipSyncer) synchronizeChanIDs() (bool, error) {
3✔
743
        // If we're in this state yet there are no more new channels to query
3✔
744
        // for, then we'll transition to our final synced state and return true
3✔
745
        // to signal that we're fully synchronized.
3✔
746
        if len(g.newChansToQuery) == 0 {
6✔
747
                log.Infof("GossipSyncer(%x): no more chans to query",
3✔
748
                        g.cfg.peerPub[:])
3✔
749
                return true, nil
3✔
750
        }
3✔
751

752
        // Otherwise, we'll issue our next chunked query to receive replies
753
        // for.
754
        var queryChunk []lnwire.ShortChannelID
3✔
755

3✔
756
        // If the number of channels to query for is less than the chunk size,
3✔
757
        // then we can issue a single query.
3✔
758
        if int32(len(g.newChansToQuery)) < g.cfg.batchSize {
6✔
759
                queryChunk = g.newChansToQuery
3✔
760
                g.newChansToQuery = nil
3✔
761

3✔
762
        } else {
3✔
UNCOV
763
                // Otherwise, we'll need to only query for the next chunk.
×
UNCOV
764
                // We'll slice into our query chunk, then slide down our main
×
UNCOV
765
                // pointer down by the chunk size.
×
UNCOV
766
                queryChunk = g.newChansToQuery[:g.cfg.batchSize]
×
UNCOV
767
                g.newChansToQuery = g.newChansToQuery[g.cfg.batchSize:]
×
UNCOV
768
        }
×
769

770
        log.Infof("GossipSyncer(%x): querying for %v new channels",
3✔
771
                g.cfg.peerPub[:], len(queryChunk))
3✔
772

3✔
773
        // With our chunk obtained, we'll send over our next query, then return
3✔
774
        // false indicating that we're net yet fully synced.
3✔
775
        err := g.cfg.sendToPeer(&lnwire.QueryShortChanIDs{
3✔
776
                ChainHash:    g.cfg.chainHash,
3✔
777
                EncodingType: lnwire.EncodingSortedPlain,
3✔
778
                ShortChanIDs: queryChunk,
3✔
779
        })
3✔
780

3✔
781
        return false, err
3✔
782
}
783

784
// isLegacyReplyChannelRange determines where a ReplyChannelRange message is
785
// considered legacy. There was a point where lnd used to include the same query
786
// over multiple replies, rather than including the portion of the query the
787
// reply is handling. We'll use this as a way of detecting whether we are
788
// communicating with a legacy node so we can properly sync with them.
789
func isLegacyReplyChannelRange(query *lnwire.QueryChannelRange,
790
        reply *lnwire.ReplyChannelRange) bool {
3✔
791

3✔
792
        return (reply.ChainHash == query.ChainHash &&
3✔
793
                reply.FirstBlockHeight == query.FirstBlockHeight &&
3✔
794
                reply.NumBlocks == query.NumBlocks)
3✔
795
}
3✔
796

797
// processChanRangeReply is called each time the GossipSyncer receives a new
798
// reply to the initial range query to discover new channels that it didn't
799
// previously know of.
800
func (g *GossipSyncer) processChanRangeReply(msg *lnwire.ReplyChannelRange) error {
3✔
801
        // isStale returns whether the timestamp is too far into the past.
3✔
802
        isStale := func(timestamp time.Time) bool {
6✔
803
                return time.Since(timestamp) > graph.DefaultChannelPruneExpiry
3✔
804
        }
3✔
805

806
        // isSkewed returns whether the timestamp is too far into the future.
807
        isSkewed := func(timestamp time.Time) bool {
6✔
808
                return time.Until(timestamp) > graph.DefaultChannelPruneExpiry
3✔
809
        }
3✔
810

811
        // If we're not communicating with a legacy node, we'll apply some
812
        // further constraints on their reply to ensure it satisfies our query.
813
        if !isLegacyReplyChannelRange(g.curQueryRangeMsg, msg) {
3✔
UNCOV
814
                // The first block should be within our original request.
×
UNCOV
815
                if msg.FirstBlockHeight < g.curQueryRangeMsg.FirstBlockHeight {
×
816
                        return fmt.Errorf("reply includes channels for height "+
×
817
                                "%v prior to query %v", msg.FirstBlockHeight,
×
818
                                g.curQueryRangeMsg.FirstBlockHeight)
×
819
                }
×
820

821
                // The last block should also be. We don't need to check the
822
                // intermediate ones because they should already be in sorted
823
                // order.
UNCOV
824
                replyLastHeight := msg.LastBlockHeight()
×
UNCOV
825
                queryLastHeight := g.curQueryRangeMsg.LastBlockHeight()
×
UNCOV
826
                if replyLastHeight > queryLastHeight {
×
827
                        return fmt.Errorf("reply includes channels for height "+
×
828
                                "%v after query %v", replyLastHeight,
×
829
                                queryLastHeight)
×
830
                }
×
831

832
                // If we've previously received a reply for this query, look at
833
                // its last block to ensure the current reply properly follows
834
                // it.
UNCOV
835
                if g.prevReplyChannelRange != nil {
×
UNCOV
836
                        prevReply := g.prevReplyChannelRange
×
UNCOV
837
                        prevReplyLastHeight := prevReply.LastBlockHeight()
×
UNCOV
838

×
UNCOV
839
                        // The current reply can either start from the previous
×
UNCOV
840
                        // reply's last block, if there are still more channels
×
UNCOV
841
                        // for the same block, or the block after.
×
UNCOV
842
                        if msg.FirstBlockHeight != prevReplyLastHeight &&
×
UNCOV
843
                                msg.FirstBlockHeight != prevReplyLastHeight+1 {
×
844

×
845
                                return fmt.Errorf("first block of reply %v "+
×
846
                                        "does not continue from last block of "+
×
847
                                        "previous %v", msg.FirstBlockHeight,
×
848
                                        prevReplyLastHeight)
×
849
                        }
×
850
                }
851
        }
852

853
        g.prevReplyChannelRange = msg
3✔
854

3✔
855
        for i, scid := range msg.ShortChanIDs {
6✔
856
                info := graphdb.NewChannelUpdateInfo(
3✔
857
                        scid, time.Time{}, time.Time{},
3✔
858
                )
3✔
859

3✔
860
                if len(msg.Timestamps) != 0 {
6✔
861
                        t1 := time.Unix(int64(msg.Timestamps[i].Timestamp1), 0)
3✔
862
                        info.Node1UpdateTimestamp = t1
3✔
863

3✔
864
                        t2 := time.Unix(int64(msg.Timestamps[i].Timestamp2), 0)
3✔
865
                        info.Node2UpdateTimestamp = t2
3✔
866

3✔
867
                        // Sort out all channels with outdated or skewed
3✔
868
                        // timestamps. Both timestamps need to be out of
3✔
869
                        // boundaries for us to skip the channel and not query
3✔
870
                        // it later on.
3✔
871
                        switch {
3✔
872
                        case isStale(info.Node1UpdateTimestamp) &&
UNCOV
873
                                isStale(info.Node2UpdateTimestamp):
×
UNCOV
874

×
UNCOV
875
                                continue
×
876

877
                        case isSkewed(info.Node1UpdateTimestamp) &&
UNCOV
878
                                isSkewed(info.Node2UpdateTimestamp):
×
UNCOV
879

×
UNCOV
880
                                continue
×
881

882
                        case isStale(info.Node1UpdateTimestamp) &&
UNCOV
883
                                isSkewed(info.Node2UpdateTimestamp):
×
UNCOV
884

×
UNCOV
885
                                continue
×
886

887
                        case isStale(info.Node2UpdateTimestamp) &&
UNCOV
888
                                isSkewed(info.Node1UpdateTimestamp):
×
UNCOV
889

×
UNCOV
890
                                continue
×
891
                        }
892
                }
893

894
                g.bufferedChanRangeReplies = append(
3✔
895
                        g.bufferedChanRangeReplies, info,
3✔
896
                )
3✔
897
        }
898

899
        switch g.cfg.encodingType {
3✔
900
        case lnwire.EncodingSortedPlain:
3✔
901
                g.numChanRangeRepliesRcvd++
3✔
902
        case lnwire.EncodingSortedZlib:
×
903
                g.numChanRangeRepliesRcvd += maxQueryChanRangeRepliesZlibFactor
×
904
        default:
×
905
                return fmt.Errorf("unhandled encoding type %v", g.cfg.encodingType)
×
906
        }
907

908
        log.Infof("GossipSyncer(%x): buffering chan range reply of size=%v",
3✔
909
                g.cfg.peerPub[:], len(msg.ShortChanIDs))
3✔
910

3✔
911
        // If this isn't the last response and we can continue to receive more,
3✔
912
        // then we can exit as we've already buffered the latest portion of the
3✔
913
        // streaming reply.
3✔
914
        maxReplies := g.cfg.maxQueryChanRangeReplies
3✔
915
        switch {
3✔
916
        // If we're communicating with a legacy node, we'll need to look at the
917
        // complete field.
918
        case isLegacyReplyChannelRange(g.curQueryRangeMsg, msg):
3✔
919
                if msg.Complete == 0 && g.numChanRangeRepliesRcvd < maxReplies {
3✔
UNCOV
920
                        return nil
×
UNCOV
921
                }
×
922

923
        // Otherwise, we'll look at the reply's height range.
UNCOV
924
        default:
×
UNCOV
925
                replyLastHeight := msg.LastBlockHeight()
×
UNCOV
926
                queryLastHeight := g.curQueryRangeMsg.LastBlockHeight()
×
UNCOV
927

×
UNCOV
928
                // TODO(wilmer): This might require some padding if the remote
×
UNCOV
929
                // node is not aware of the last height we sent them, i.e., is
×
UNCOV
930
                // behind a few blocks from us.
×
UNCOV
931
                if replyLastHeight < queryLastHeight &&
×
UNCOV
932
                        g.numChanRangeRepliesRcvd < maxReplies {
×
UNCOV
933

×
UNCOV
934
                        return nil
×
UNCOV
935
                }
×
936
        }
937

938
        log.Infof("GossipSyncer(%x): filtering through %v chans",
3✔
939
                g.cfg.peerPub[:], len(g.bufferedChanRangeReplies))
3✔
940

3✔
941
        // Otherwise, this is the final response, so we'll now check to see
3✔
942
        // which channels they know of that we don't.
3✔
943
        newChans, err := g.cfg.channelSeries.FilterKnownChanIDs(
3✔
944
                g.cfg.chainHash, g.bufferedChanRangeReplies,
3✔
945
                g.cfg.isStillZombieChannel,
3✔
946
        )
3✔
947
        if err != nil {
3✔
948
                return fmt.Errorf("unable to filter chan ids: %w", err)
×
949
        }
×
950

951
        // As we've received the entirety of the reply, we no longer need to
952
        // hold on to the set of buffered replies or the original query that
953
        // prompted the replies, so we'll let that be garbage collected now.
954
        g.curQueryRangeMsg = nil
3✔
955
        g.prevReplyChannelRange = nil
3✔
956
        g.bufferedChanRangeReplies = nil
3✔
957
        g.numChanRangeRepliesRcvd = 0
3✔
958

3✔
959
        // If there aren't any channels that we don't know of, then we can
3✔
960
        // switch straight to our terminal state.
3✔
961
        if len(newChans) == 0 {
6✔
962
                log.Infof("GossipSyncer(%x): remote peer has no new chans",
3✔
963
                        g.cfg.peerPub[:])
3✔
964

3✔
965
                g.setSyncState(chansSynced)
3✔
966

3✔
967
                // Ensure that the sync manager becomes aware that the
3✔
968
                // historical sync completed so synced_to_graph is updated over
3✔
969
                // rpc.
3✔
970
                g.cfg.markGraphSynced()
3✔
971
                return nil
3✔
972
        }
3✔
973

974
        // Otherwise, we'll set the set of channels that we need to query for
975
        // the next state, and also transition our state.
976
        g.newChansToQuery = newChans
3✔
977
        g.setSyncState(queryNewChannels)
3✔
978

3✔
979
        log.Infof("GossipSyncer(%x): starting query for %v new chans",
3✔
980
                g.cfg.peerPub[:], len(newChans))
3✔
981

3✔
982
        return nil
3✔
983
}
984

985
// genChanRangeQuery generates the initial message we'll send to the remote
986
// party when we're kicking off the channel graph synchronization upon
987
// connection. The historicalQuery boolean can be used to generate a query from
988
// the genesis block of the chain.
989
func (g *GossipSyncer) genChanRangeQuery(
990
        historicalQuery bool) (*lnwire.QueryChannelRange, error) {
3✔
991

3✔
992
        // First, we'll query our channel graph time series for its highest
3✔
993
        // known channel ID.
3✔
994
        newestChan, err := g.cfg.channelSeries.HighestChanID(g.cfg.chainHash)
3✔
995
        if err != nil {
3✔
996
                return nil, err
×
997
        }
×
998

999
        // Once we have the chan ID of the newest, we'll obtain the block height
1000
        // of the channel, then subtract our default horizon to ensure we don't
1001
        // miss any channels. By default, we go back 1 day from the newest
1002
        // channel, unless we're attempting a historical sync, where we'll
1003
        // actually start from the genesis block instead.
1004
        var startHeight uint32
3✔
1005
        switch {
3✔
1006
        case historicalQuery:
3✔
1007
                fallthrough
3✔
1008
        case newestChan.BlockHeight <= chanRangeQueryBuffer:
3✔
1009
                startHeight = 0
3✔
UNCOV
1010
        default:
×
UNCOV
1011
                startHeight = newestChan.BlockHeight - chanRangeQueryBuffer
×
1012
        }
1013

1014
        // Determine the number of blocks to request based on our best height.
1015
        // We'll take into account any potential underflows and explicitly set
1016
        // numBlocks to its minimum value of 1 if so.
1017
        bestHeight := g.cfg.bestHeight()
3✔
1018
        numBlocks := bestHeight - startHeight
3✔
1019
        if int64(numBlocks) < 1 {
3✔
1020
                numBlocks = 1
×
1021
        }
×
1022

1023
        log.Infof("GossipSyncer(%x): requesting new chans from height=%v "+
3✔
1024
                "and %v blocks after", g.cfg.peerPub[:], startHeight, numBlocks)
3✔
1025

3✔
1026
        // Finally, we'll craft the channel range query, using our starting
3✔
1027
        // height, then asking for all known channels to the foreseeable end of
3✔
1028
        // the main chain.
3✔
1029
        query := &lnwire.QueryChannelRange{
3✔
1030
                ChainHash:        g.cfg.chainHash,
3✔
1031
                FirstBlockHeight: startHeight,
3✔
1032
                NumBlocks:        numBlocks,
3✔
1033
        }
3✔
1034

3✔
1035
        if !g.cfg.noTimestampQueryOption {
6✔
1036
                query.QueryOptions = lnwire.NewTimestampQueryOption()
3✔
1037
        }
3✔
1038

1039
        g.curQueryRangeMsg = query
3✔
1040

3✔
1041
        return query, nil
3✔
1042
}
1043

1044
// replyPeerQueries is called in response to any query by the remote peer.
1045
// We'll examine our state and send back our best response.
1046
func (g *GossipSyncer) replyPeerQueries(msg lnwire.Message) error {
3✔
1047
        reservation := g.rateLimiter.Reserve()
3✔
1048
        delay := reservation.Delay()
3✔
1049

3✔
1050
        // If we've already replied a handful of times, we will start to delay
3✔
1051
        // responses back to the remote peer. This can help prevent DOS attacks
3✔
1052
        // where the remote peer spams us endlessly.
3✔
1053
        if delay > 0 {
3✔
UNCOV
1054
                log.Infof("GossipSyncer(%x): rate limiting gossip replies, "+
×
UNCOV
1055
                        "responding in %s", g.cfg.peerPub[:], delay)
×
UNCOV
1056

×
UNCOV
1057
                select {
×
UNCOV
1058
                case <-time.After(delay):
×
1059
                case <-g.quit:
×
1060
                        return ErrGossipSyncerExiting
×
1061
                }
1062
        }
1063

1064
        switch msg := msg.(type) {
3✔
1065

1066
        // In this state, we'll also handle any incoming channel range queries
1067
        // from the remote peer as they're trying to sync their state as well.
1068
        case *lnwire.QueryChannelRange:
3✔
1069
                return g.replyChanRangeQuery(msg)
3✔
1070

1071
        // If the remote peer skips straight to requesting new channels that
1072
        // they don't know of, then we'll ensure that we also handle this case.
1073
        case *lnwire.QueryShortChanIDs:
3✔
1074
                return g.replyShortChanIDs(msg)
3✔
1075

1076
        default:
×
1077
                return fmt.Errorf("unknown message: %T", msg)
×
1078
        }
1079
}
1080

1081
// replyChanRangeQuery will be dispatched in response to a channel range query
1082
// by the remote node. We'll query the channel time series for channels that
1083
// meet the channel range, then chunk our responses to the remote node. We also
1084
// ensure that our final fragment carries the "complete" bit to indicate the
1085
// end of our streaming response.
1086
func (g *GossipSyncer) replyChanRangeQuery(query *lnwire.QueryChannelRange) error {
3✔
1087
        // Before responding, we'll check to ensure that the remote peer is
3✔
1088
        // querying for the same chain that we're on. If not, we'll send back a
3✔
1089
        // response with a complete value of zero to indicate we're on a
3✔
1090
        // different chain.
3✔
1091
        if g.cfg.chainHash != query.ChainHash {
3✔
UNCOV
1092
                log.Warnf("Remote peer requested QueryChannelRange for "+
×
UNCOV
1093
                        "chain=%v, we're on chain=%v", query.ChainHash,
×
UNCOV
1094
                        g.cfg.chainHash)
×
UNCOV
1095

×
UNCOV
1096
                return g.cfg.sendToPeerSync(&lnwire.ReplyChannelRange{
×
UNCOV
1097
                        ChainHash:        query.ChainHash,
×
UNCOV
1098
                        FirstBlockHeight: query.FirstBlockHeight,
×
UNCOV
1099
                        NumBlocks:        query.NumBlocks,
×
UNCOV
1100
                        Complete:         0,
×
UNCOV
1101
                        EncodingType:     g.cfg.encodingType,
×
UNCOV
1102
                        ShortChanIDs:     nil,
×
UNCOV
1103
                })
×
UNCOV
1104
        }
×
1105

1106
        log.Infof("GossipSyncer(%x): filtering chan range: start_height=%v, "+
3✔
1107
                "num_blocks=%v", g.cfg.peerPub[:], query.FirstBlockHeight,
3✔
1108
                query.NumBlocks)
3✔
1109

3✔
1110
        // Check if the query asked for timestamps. We will only serve
3✔
1111
        // timestamps if this has not been disabled with
3✔
1112
        // noTimestampQueryOption.
3✔
1113
        withTimestamps := query.WithTimestamps() &&
3✔
1114
                !g.cfg.noTimestampQueryOption
3✔
1115

3✔
1116
        // Next, we'll consult the time series to obtain the set of known
3✔
1117
        // channel ID's that match their query.
3✔
1118
        startBlock := query.FirstBlockHeight
3✔
1119
        endBlock := query.LastBlockHeight()
3✔
1120
        channelRanges, err := g.cfg.channelSeries.FilterChannelRange(
3✔
1121
                query.ChainHash, startBlock, endBlock, withTimestamps,
3✔
1122
        )
3✔
1123
        if err != nil {
3✔
1124
                return err
×
1125
        }
×
1126

1127
        // TODO(roasbeef): means can't send max uint above?
1128
        //  * or make internal 64
1129

1130
        // We'll send our response in a streaming manner, chunk-by-chunk. We do
1131
        // this as there's a transport message size limit which we'll need to
1132
        // adhere to. We also need to make sure all of our replies cover the
1133
        // expected range of the query.
1134
        sendReplyForChunk := func(channelChunk []graphdb.ChannelUpdateInfo,
3✔
1135
                firstHeight, lastHeight uint32, finalChunk bool) error {
6✔
1136

3✔
1137
                // The number of blocks contained in the current chunk (the
3✔
1138
                // total span) is the difference between the last channel ID and
3✔
1139
                // the first in the range. We add one as even if all channels
3✔
1140
                // returned are in the same block, we need to count that.
3✔
1141
                numBlocks := lastHeight - firstHeight + 1
3✔
1142
                complete := uint8(0)
3✔
1143
                if finalChunk {
6✔
1144
                        complete = 1
3✔
1145
                }
3✔
1146

1147
                var timestamps lnwire.Timestamps
3✔
1148
                if withTimestamps {
6✔
1149
                        timestamps = make(lnwire.Timestamps, len(channelChunk))
3✔
1150
                }
3✔
1151

1152
                scids := make([]lnwire.ShortChannelID, len(channelChunk))
3✔
1153
                for i, info := range channelChunk {
6✔
1154
                        scids[i] = info.ShortChannelID
3✔
1155

3✔
1156
                        if !withTimestamps {
3✔
UNCOV
1157
                                continue
×
1158
                        }
1159

1160
                        timestamps[i].Timestamp1 = uint32(
3✔
1161
                                info.Node1UpdateTimestamp.Unix(),
3✔
1162
                        )
3✔
1163

3✔
1164
                        timestamps[i].Timestamp2 = uint32(
3✔
1165
                                info.Node2UpdateTimestamp.Unix(),
3✔
1166
                        )
3✔
1167
                }
1168

1169
                return g.cfg.sendToPeerSync(&lnwire.ReplyChannelRange{
3✔
1170
                        ChainHash:        query.ChainHash,
3✔
1171
                        NumBlocks:        numBlocks,
3✔
1172
                        FirstBlockHeight: firstHeight,
3✔
1173
                        Complete:         complete,
3✔
1174
                        EncodingType:     g.cfg.encodingType,
3✔
1175
                        ShortChanIDs:     scids,
3✔
1176
                        Timestamps:       timestamps,
3✔
1177
                })
3✔
1178
        }
1179

1180
        var (
3✔
1181
                firstHeight  = query.FirstBlockHeight
3✔
1182
                lastHeight   uint32
3✔
1183
                channelChunk []graphdb.ChannelUpdateInfo
3✔
1184
        )
3✔
1185

3✔
1186
        // chunkSize is the maximum number of SCIDs that we can safely put in a
3✔
1187
        // single message. If we also need to include timestamps though, then
3✔
1188
        // this number is halved since encoding two timestamps takes the same
3✔
1189
        // number of bytes as encoding an SCID.
3✔
1190
        chunkSize := g.cfg.chunkSize
3✔
1191
        if withTimestamps {
6✔
1192
                chunkSize /= 2
3✔
1193
        }
3✔
1194

1195
        for _, channelRange := range channelRanges {
6✔
1196
                channels := channelRange.Channels
3✔
1197
                numChannels := int32(len(channels))
3✔
1198
                numLeftToAdd := chunkSize - int32(len(channelChunk))
3✔
1199

3✔
1200
                // Include the current block in the ongoing chunk if it can fit
3✔
1201
                // and move on to the next block.
3✔
1202
                if numChannels <= numLeftToAdd {
6✔
1203
                        channelChunk = append(channelChunk, channels...)
3✔
1204
                        continue
3✔
1205
                }
1206

1207
                // Otherwise, we need to send our existing channel chunk as is
1208
                // as its own reply and start a new one for the current block.
1209
                // We'll mark the end of our current chunk as the height before
1210
                // the current block to ensure the whole query range is replied
1211
                // to.
UNCOV
1212
                log.Infof("GossipSyncer(%x): sending range chunk of size=%v",
×
UNCOV
1213
                        g.cfg.peerPub[:], len(channelChunk))
×
UNCOV
1214

×
UNCOV
1215
                lastHeight = channelRange.Height - 1
×
UNCOV
1216
                err := sendReplyForChunk(
×
UNCOV
1217
                        channelChunk, firstHeight, lastHeight, false,
×
UNCOV
1218
                )
×
UNCOV
1219
                if err != nil {
×
1220
                        return err
×
1221
                }
×
1222

1223
                // With the reply constructed, we'll start tallying channels for
1224
                // our next one keeping in mind our chunk size. This may result
1225
                // in channels for this block being left out from the reply, but
1226
                // this isn't an issue since we'll randomly shuffle them and we
1227
                // assume a historical gossip sync is performed at a later time.
UNCOV
1228
                firstHeight = channelRange.Height
×
UNCOV
1229
                finalChunkSize := numChannels
×
UNCOV
1230
                exceedsChunkSize := numChannels > chunkSize
×
UNCOV
1231
                if exceedsChunkSize {
×
1232
                        rand.Shuffle(len(channels), func(i, j int) {
×
1233
                                channels[i], channels[j] = channels[j], channels[i]
×
1234
                        })
×
1235
                        finalChunkSize = chunkSize
×
1236
                }
UNCOV
1237
                channelChunk = channels[:finalChunkSize]
×
UNCOV
1238

×
UNCOV
1239
                // Sort the chunk once again if we had to shuffle it.
×
UNCOV
1240
                if exceedsChunkSize {
×
1241
                        sort.Slice(channelChunk, func(i, j int) bool {
×
1242
                                id1 := channelChunk[i].ShortChannelID.ToUint64()
×
1243
                                id2 := channelChunk[j].ShortChannelID.ToUint64()
×
1244

×
1245
                                return id1 < id2
×
1246
                        })
×
1247
                }
1248
        }
1249

1250
        // Send the remaining chunk as the final reply.
1251
        log.Infof("GossipSyncer(%x): sending final chan range chunk, size=%v",
3✔
1252
                g.cfg.peerPub[:], len(channelChunk))
3✔
1253

3✔
1254
        return sendReplyForChunk(
3✔
1255
                channelChunk, firstHeight, query.LastBlockHeight(), true,
3✔
1256
        )
3✔
1257
}
1258

1259
// replyShortChanIDs will be dispatched in response to a query by the remote
1260
// node for information concerning a set of short channel ID's. Our response
1261
// will be sent in a streaming chunked manner to ensure that we remain below
1262
// the current transport level message size.
1263
func (g *GossipSyncer) replyShortChanIDs(query *lnwire.QueryShortChanIDs) error {
3✔
1264
        // Before responding, we'll check to ensure that the remote peer is
3✔
1265
        // querying for the same chain that we're on. If not, we'll send back a
3✔
1266
        // response with a complete value of zero to indicate we're on a
3✔
1267
        // different chain.
3✔
1268
        if g.cfg.chainHash != query.ChainHash {
3✔
UNCOV
1269
                log.Warnf("Remote peer requested QueryShortChanIDs for "+
×
UNCOV
1270
                        "chain=%v, we're on chain=%v", query.ChainHash,
×
UNCOV
1271
                        g.cfg.chainHash)
×
UNCOV
1272

×
UNCOV
1273
                return g.cfg.sendToPeerSync(&lnwire.ReplyShortChanIDsEnd{
×
UNCOV
1274
                        ChainHash: query.ChainHash,
×
UNCOV
1275
                        Complete:  0,
×
UNCOV
1276
                })
×
UNCOV
1277
        }
×
1278

1279
        if len(query.ShortChanIDs) == 0 {
3✔
1280
                log.Infof("GossipSyncer(%x): ignoring query for blank short chan ID's",
×
1281
                        g.cfg.peerPub[:])
×
1282
                return nil
×
1283
        }
×
1284

1285
        log.Infof("GossipSyncer(%x): fetching chan anns for %v chans",
3✔
1286
                g.cfg.peerPub[:], len(query.ShortChanIDs))
3✔
1287

3✔
1288
        // Now that we know we're on the same chain, we'll query the channel
3✔
1289
        // time series for the set of messages that we know of which satisfies
3✔
1290
        // the requirement of being a chan ann, chan update, or a node ann
3✔
1291
        // related to the set of queried channels.
3✔
1292
        replyMsgs, err := g.cfg.channelSeries.FetchChanAnns(
3✔
1293
                query.ChainHash, query.ShortChanIDs,
3✔
1294
        )
3✔
1295
        if err != nil {
3✔
1296
                return fmt.Errorf("unable to fetch chan anns for %v..., %w",
×
1297
                        query.ShortChanIDs[0].ToUint64(), err)
×
1298
        }
×
1299

1300
        // Reply with any messages related to those channel ID's, we'll write
1301
        // each one individually and synchronously to throttle the sends and
1302
        // perform buffering of responses in the syncer as opposed to the peer.
1303
        for _, msg := range replyMsgs {
6✔
1304
                err := g.cfg.sendToPeerSync(msg)
3✔
1305
                if err != nil {
3✔
1306
                        return err
×
1307
                }
×
1308
        }
1309

1310
        // Regardless of whether we had any messages to reply with, send over
1311
        // the sentinel message to signal that the stream has terminated.
1312
        return g.cfg.sendToPeerSync(&lnwire.ReplyShortChanIDsEnd{
3✔
1313
                ChainHash: query.ChainHash,
3✔
1314
                Complete:  1,
3✔
1315
        })
3✔
1316
}
1317

1318
// ApplyGossipFilter applies a gossiper filter sent by the remote node to the
1319
// state machine. Once applied, we'll ensure that we don't forward any messages
1320
// to the peer that aren't within the time range of the filter.
1321
func (g *GossipSyncer) ApplyGossipFilter(filter *lnwire.GossipTimestampRange) error {
3✔
1322
        g.Lock()
3✔
1323

3✔
1324
        g.remoteUpdateHorizon = filter
3✔
1325

3✔
1326
        startTime := time.Unix(int64(g.remoteUpdateHorizon.FirstTimestamp), 0)
3✔
1327
        endTime := startTime.Add(
3✔
1328
                time.Duration(g.remoteUpdateHorizon.TimestampRange) * time.Second,
3✔
1329
        )
3✔
1330

3✔
1331
        g.Unlock()
3✔
1332

3✔
1333
        // If requested, don't reply with historical gossip data when the remote
3✔
1334
        // peer sets their gossip timestamp range.
3✔
1335
        if g.cfg.ignoreHistoricalFilters {
3✔
UNCOV
1336
                return nil
×
UNCOV
1337
        }
×
1338

1339
        select {
3✔
1340
        case <-g.syncerSema:
3✔
1341
        case <-g.quit:
×
1342
                return ErrGossipSyncerExiting
×
1343
        }
1344

1345
        // We don't put this in a defer because if the goroutine is launched,
1346
        // it needs to be called when the goroutine is stopped.
1347
        returnSema := func() {
6✔
1348
                g.syncerSema <- struct{}{}
3✔
1349
        }
3✔
1350

1351
        // Now that the remote peer has applied their filter, we'll query the
1352
        // database for all the messages that are beyond this filter.
1353
        newUpdatestoSend, err := g.cfg.channelSeries.UpdatesInHorizon(
3✔
1354
                g.cfg.chainHash, startTime, endTime,
3✔
1355
        )
3✔
1356
        if err != nil {
3✔
1357
                returnSema()
×
1358
                return err
×
1359
        }
×
1360

1361
        log.Infof("GossipSyncer(%x): applying new remote update horizon: "+
3✔
1362
                "start=%v, end=%v, backlog_size=%v", g.cfg.peerPub[:],
3✔
1363
                startTime, endTime, len(newUpdatestoSend))
3✔
1364

3✔
1365
        // If we don't have any to send, then we can return early.
3✔
1366
        if len(newUpdatestoSend) == 0 {
6✔
1367
                returnSema()
3✔
1368
                return nil
3✔
1369
        }
3✔
1370

1371
        // We'll conclude by launching a goroutine to send out any updates.
1372
        g.wg.Add(1)
3✔
1373
        go func() {
6✔
1374
                defer g.wg.Done()
3✔
1375
                defer returnSema()
3✔
1376

3✔
1377
                for _, msg := range newUpdatestoSend {
6✔
1378
                        err := g.cfg.sendToPeerSync(msg)
3✔
1379
                        switch {
3✔
1380
                        case err == ErrGossipSyncerExiting:
×
1381
                                return
×
1382

1383
                        case err == lnpeer.ErrPeerExiting:
×
1384
                                return
×
1385

1386
                        case err != nil:
×
1387
                                log.Errorf("Unable to send message for "+
×
1388
                                        "peer catch up: %v", err)
×
1389
                        }
1390
                }
1391
        }()
1392

1393
        return nil
3✔
1394
}
1395

1396
// FilterGossipMsgs takes a set of gossip messages, and only send it to a peer
1397
// iff the message is within the bounds of their set gossip filter. If the peer
1398
// doesn't have a gossip filter set, then no messages will be forwarded.
1399
func (g *GossipSyncer) FilterGossipMsgs(msgs ...msgWithSenders) {
3✔
1400
        // If the peer doesn't have an update horizon set, then we won't send
3✔
1401
        // it any new update messages.
3✔
1402
        if g.remoteUpdateHorizon == nil {
6✔
1403
                log.Tracef("GossipSyncer(%x): skipped due to nil "+
3✔
1404
                        "remoteUpdateHorizon", g.cfg.peerPub[:])
3✔
1405
                return
3✔
1406
        }
3✔
1407

1408
        // If we've been signaled to exit, or are exiting, then we'll stop
1409
        // short.
1410
        select {
3✔
1411
        case <-g.quit:
×
1412
                return
×
1413
        default:
3✔
1414
        }
1415

1416
        // TODO(roasbeef): need to ensure that peer still online...send msg to
1417
        // gossiper on peer termination to signal peer disconnect?
1418

1419
        var err error
3✔
1420

3✔
1421
        // Before we filter out the messages, we'll construct an index over the
3✔
1422
        // set of channel announcements and channel updates. This will allow us
3✔
1423
        // to quickly check if we should forward a chan ann, based on the known
3✔
1424
        // channel updates for a channel.
3✔
1425
        chanUpdateIndex := make(
3✔
1426
                map[lnwire.ShortChannelID][]*lnwire.ChannelUpdate1,
3✔
1427
        )
3✔
1428
        for _, msg := range msgs {
6✔
1429
                chanUpdate, ok := msg.msg.(*lnwire.ChannelUpdate1)
3✔
1430
                if !ok {
6✔
1431
                        continue
3✔
1432
                }
1433

1434
                chanUpdateIndex[chanUpdate.ShortChannelID] = append(
3✔
1435
                        chanUpdateIndex[chanUpdate.ShortChannelID], chanUpdate,
3✔
1436
                )
3✔
1437
        }
1438

1439
        // We'll construct a helper function that we'll us below to determine
1440
        // if a given messages passes the gossip msg filter.
1441
        g.Lock()
3✔
1442
        startTime := time.Unix(int64(g.remoteUpdateHorizon.FirstTimestamp), 0)
3✔
1443
        endTime := startTime.Add(
3✔
1444
                time.Duration(g.remoteUpdateHorizon.TimestampRange) * time.Second,
3✔
1445
        )
3✔
1446
        g.Unlock()
3✔
1447

3✔
1448
        passesFilter := func(timeStamp uint32) bool {
6✔
1449
                t := time.Unix(int64(timeStamp), 0)
3✔
1450
                return t.Equal(startTime) ||
3✔
1451
                        (t.After(startTime) && t.Before(endTime))
3✔
1452
        }
3✔
1453

1454
        msgsToSend := make([]lnwire.Message, 0, len(msgs))
3✔
1455
        for _, msg := range msgs {
6✔
1456
                // If the target peer is the peer that sent us this message,
3✔
1457
                // then we'll exit early as we don't need to filter this
3✔
1458
                // message.
3✔
1459
                if _, ok := msg.senders[g.cfg.peerPub]; ok {
6✔
1460
                        continue
3✔
1461
                }
1462

1463
                switch msg := msg.msg.(type) {
3✔
1464

1465
                // For each channel announcement message, we'll only send this
1466
                // message if the channel updates for the channel are between
1467
                // our time range.
1468
                case *lnwire.ChannelAnnouncement1:
3✔
1469
                        // First, we'll check if the channel updates are in
3✔
1470
                        // this message batch.
3✔
1471
                        chanUpdates, ok := chanUpdateIndex[msg.ShortChannelID]
3✔
1472
                        if !ok {
6✔
1473
                                // If not, we'll attempt to query the database
3✔
1474
                                // to see if we know of the updates.
3✔
1475
                                chanUpdates, err = g.cfg.channelSeries.FetchChanUpdates(
3✔
1476
                                        g.cfg.chainHash, msg.ShortChannelID,
3✔
1477
                                )
3✔
1478
                                if err != nil {
3✔
1479
                                        log.Warnf("no channel updates found for "+
×
1480
                                                "short_chan_id=%v",
×
1481
                                                msg.ShortChannelID)
×
1482
                                        continue
×
1483
                                }
1484
                        }
1485

1486
                        for _, chanUpdate := range chanUpdates {
6✔
1487
                                if passesFilter(chanUpdate.Timestamp) {
6✔
1488
                                        msgsToSend = append(msgsToSend, msg)
3✔
1489
                                        break
3✔
1490
                                }
1491
                        }
1492

1493
                        if len(chanUpdates) == 0 {
6✔
1494
                                msgsToSend = append(msgsToSend, msg)
3✔
1495
                        }
3✔
1496

1497
                // For each channel update, we'll only send if it the timestamp
1498
                // is between our time range.
1499
                case *lnwire.ChannelUpdate1:
3✔
1500
                        if passesFilter(msg.Timestamp) {
6✔
1501
                                msgsToSend = append(msgsToSend, msg)
3✔
1502
                        }
3✔
1503

1504
                // Similarly, we only send node announcements if the update
1505
                // timestamp ifs between our set gossip filter time range.
1506
                case *lnwire.NodeAnnouncement:
3✔
1507
                        if passesFilter(msg.Timestamp) {
6✔
1508
                                msgsToSend = append(msgsToSend, msg)
3✔
1509
                        }
3✔
1510
                }
1511
        }
1512

1513
        log.Tracef("GossipSyncer(%x): filtered gossip msgs: set=%v, sent=%v",
3✔
1514
                g.cfg.peerPub[:], len(msgs), len(msgsToSend))
3✔
1515

3✔
1516
        if len(msgsToSend) == 0 {
6✔
1517
                return
3✔
1518
        }
3✔
1519

1520
        g.cfg.sendToPeer(msgsToSend...)
3✔
1521
}
1522

1523
// ProcessQueryMsg is used by outside callers to pass new channel time series
1524
// queries to the internal processing goroutine.
1525
func (g *GossipSyncer) ProcessQueryMsg(msg lnwire.Message, peerQuit <-chan struct{}) error {
3✔
1526
        var msgChan chan lnwire.Message
3✔
1527
        switch msg.(type) {
3✔
1528
        case *lnwire.QueryChannelRange, *lnwire.QueryShortChanIDs:
3✔
1529
                msgChan = g.queryMsgs
3✔
1530

1531
        // Reply messages should only be expected in states where we're waiting
1532
        // for a reply.
1533
        case *lnwire.ReplyChannelRange, *lnwire.ReplyShortChanIDsEnd:
3✔
1534
                g.Lock()
3✔
1535
                syncState := g.syncState()
3✔
1536
                g.Unlock()
3✔
1537

3✔
1538
                if syncState != waitingQueryRangeReply &&
3✔
1539
                        syncState != waitingQueryChanReply {
3✔
UNCOV
1540

×
UNCOV
1541
                        return fmt.Errorf("unexpected msg %T received in "+
×
UNCOV
1542
                                "state %v", msg, syncState)
×
UNCOV
1543
                }
×
1544
                msgChan = g.gossipMsgs
3✔
1545

1546
        default:
×
1547
                msgChan = g.gossipMsgs
×
1548
        }
1549

1550
        select {
3✔
1551
        case msgChan <- msg:
3✔
1552
        case <-peerQuit:
×
1553
        case <-g.quit:
×
1554
        }
1555

1556
        return nil
3✔
1557
}
1558

1559
// setSyncState sets the gossip syncer's state to the given state.
1560
func (g *GossipSyncer) setSyncState(state syncerState) {
3✔
1561
        atomic.StoreUint32(&g.state, uint32(state))
3✔
1562
}
3✔
1563

1564
// syncState returns the current syncerState of the target GossipSyncer.
1565
func (g *GossipSyncer) syncState() syncerState {
3✔
1566
        return syncerState(atomic.LoadUint32(&g.state))
3✔
1567
}
3✔
1568

1569
// ResetSyncedSignal returns a channel that will be closed in order to serve as
1570
// a signal for when the GossipSyncer has reached its chansSynced state.
1571
func (g *GossipSyncer) ResetSyncedSignal() chan struct{} {
3✔
1572
        g.Lock()
3✔
1573
        defer g.Unlock()
3✔
1574

3✔
1575
        syncedSignal := make(chan struct{})
3✔
1576

3✔
1577
        syncState := syncerState(atomic.LoadUint32(&g.state))
3✔
1578
        if syncState == chansSynced {
3✔
UNCOV
1579
                close(syncedSignal)
×
UNCOV
1580
                return syncedSignal
×
UNCOV
1581
        }
×
1582

1583
        g.syncedSignal = syncedSignal
3✔
1584
        return g.syncedSignal
3✔
1585
}
1586

1587
// ProcessSyncTransition sends a request to the gossip syncer to transition its
1588
// sync type to a new one.
1589
//
1590
// NOTE: This can only be done once the gossip syncer has reached its final
1591
// chansSynced state.
1592
func (g *GossipSyncer) ProcessSyncTransition(newSyncType SyncerType) error {
3✔
1593
        errChan := make(chan error, 1)
3✔
1594
        select {
3✔
1595
        case g.syncTransitionReqs <- &syncTransitionReq{
1596
                newSyncType: newSyncType,
1597
                errChan:     errChan,
1598
        }:
3✔
1599
        case <-time.After(syncTransitionTimeout):
×
1600
                return ErrSyncTransitionTimeout
×
1601
        case <-g.quit:
×
1602
                return ErrGossipSyncerExiting
×
1603
        }
1604

1605
        select {
3✔
1606
        case err := <-errChan:
3✔
1607
                return err
3✔
1608
        case <-g.quit:
×
1609
                return ErrGossipSyncerExiting
×
1610
        }
1611
}
1612

1613
// handleSyncTransition handles a new sync type transition request.
1614
//
1615
// NOTE: The gossip syncer might have another sync state as a result of this
1616
// transition.
1617
func (g *GossipSyncer) handleSyncTransition(req *syncTransitionReq) error {
3✔
1618
        // Return early from any NOP sync transitions.
3✔
1619
        syncType := g.SyncType()
3✔
1620
        if syncType == req.newSyncType {
3✔
1621
                return nil
×
1622
        }
×
1623

1624
        log.Debugf("GossipSyncer(%x): transitioning from %v to %v",
3✔
1625
                g.cfg.peerPub, syncType, req.newSyncType)
3✔
1626

3✔
1627
        var (
3✔
1628
                firstTimestamp time.Time
3✔
1629
                timestampRange uint32
3✔
1630
        )
3✔
1631

3✔
1632
        switch req.newSyncType {
3✔
1633
        // If an active sync has been requested, then we should resume receiving
1634
        // new graph updates from the remote peer.
1635
        case ActiveSync, PinnedSync:
3✔
1636
                firstTimestamp = time.Now()
3✔
1637
                timestampRange = math.MaxUint32
3✔
1638

1639
        // If a PassiveSync transition has been requested, then we should no
1640
        // longer receive any new updates from the remote peer. We can do this
1641
        // by setting our update horizon to a range in the past ensuring no
1642
        // graph updates match the timestamp range.
UNCOV
1643
        case PassiveSync:
×
UNCOV
1644
                firstTimestamp = zeroTimestamp
×
UNCOV
1645
                timestampRange = 0
×
1646

1647
        default:
×
1648
                return fmt.Errorf("unhandled sync transition %v",
×
1649
                        req.newSyncType)
×
1650
        }
1651

1652
        err := g.sendGossipTimestampRange(firstTimestamp, timestampRange)
3✔
1653
        if err != nil {
3✔
1654
                return fmt.Errorf("unable to send local update horizon: %w",
×
1655
                        err)
×
1656
        }
×
1657

1658
        g.setSyncType(req.newSyncType)
3✔
1659

3✔
1660
        return nil
3✔
1661
}
1662

1663
// setSyncType sets the gossip syncer's sync type to the given type.
1664
func (g *GossipSyncer) setSyncType(syncType SyncerType) {
3✔
1665
        atomic.StoreUint32(&g.syncType, uint32(syncType))
3✔
1666
}
3✔
1667

1668
// SyncType returns the current SyncerType of the target GossipSyncer.
1669
func (g *GossipSyncer) SyncType() SyncerType {
3✔
1670
        return SyncerType(atomic.LoadUint32(&g.syncType))
3✔
1671
}
3✔
1672

1673
// historicalSync sends a request to the gossip syncer to perofmr a historical
1674
// sync.
1675
//
1676
// NOTE: This can only be done once the gossip syncer has reached its final
1677
// chansSynced state.
1678
func (g *GossipSyncer) historicalSync() error {
3✔
1679
        done := make(chan struct{})
3✔
1680

3✔
1681
        select {
3✔
1682
        case g.historicalSyncReqs <- &historicalSyncReq{
1683
                doneChan: done,
1684
        }:
3✔
1685
        case <-time.After(syncTransitionTimeout):
×
1686
                return ErrSyncTransitionTimeout
×
1687
        case <-g.quit:
×
1688
                return ErrGossiperShuttingDown
×
1689
        }
1690

1691
        select {
3✔
1692
        case <-done:
3✔
1693
                return nil
3✔
1694
        case <-g.quit:
×
1695
                return ErrGossiperShuttingDown
×
1696
        }
1697
}
1698

1699
// handleHistoricalSync handles a request to the gossip syncer to perform a
1700
// historical sync.
1701
func (g *GossipSyncer) handleHistoricalSync(req *historicalSyncReq) {
3✔
1702
        // We'll go back to our initial syncingChans state in order to request
3✔
1703
        // the remote peer to give us all of the channel IDs they know of
3✔
1704
        // starting from the genesis block.
3✔
1705
        g.genHistoricalChanRangeQuery = true
3✔
1706
        g.setSyncState(syncingChans)
3✔
1707
        close(req.doneChan)
3✔
1708
}
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