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

lightningnetwork / lnd / 15561477203

10 Jun 2025 01:54PM UTC coverage: 58.351% (-10.1%) from 68.487%
15561477203

Pull #9356

github

web-flow
Merge 6440b25db into c6d6d4c0b
Pull Request #9356: lnrpc: add incoming/outgoing channel ids filter to forwarding history request

33 of 36 new or added lines in 2 files covered. (91.67%)

28366 existing lines in 455 files now uncovered.

97715 of 167461 relevant lines covered (58.35%)

1.81 hits per line

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

74.0
/discovery/syncer.go
1
package discovery
2

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

14
        "github.com/btcsuite/btcd/chaincfg/chainhash"
15
        "github.com/lightningnetwork/lnd/fn/v2"
16
        "github.com/lightningnetwork/lnd/graph"
17
        graphdb "github.com/lightningnetwork/lnd/graph/db"
18
        "github.com/lightningnetwork/lnd/lnpeer"
19
        "github.com/lightningnetwork/lnd/lnwire"
20
)
21

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

155
const (
156
        // maxQueryChanRangeReplies specifies the default limit of replies to
157
        // process for a single QueryChannelRange request.
158
        maxQueryChanRangeReplies = 500
159

160
        // maxQueryChanRangeRepliesZlibFactor specifies the factor applied to
161
        // the maximum number of replies allowed for zlib encoded replies.
162
        maxQueryChanRangeRepliesZlibFactor = 4
163

164
        // chanRangeQueryBuffer is the number of blocks back that we'll go when
165
        // asking the remote peer for their any channels they know of beyond
166
        // our highest known channel ID.
167
        chanRangeQueryBuffer = 144
168

169
        // syncTransitionTimeout is the default timeout in which we'll wait up
170
        // to when attempting to perform a sync transition.
171
        syncTransitionTimeout = 5 * time.Second
172

173
        // requestBatchSize is the maximum number of channels we will query the
174
        // remote peer for in a QueryShortChanIDs message.
175
        requestBatchSize = 500
176

177
        // syncerBufferSize is the size of the syncer's buffers.
178
        syncerBufferSize = 50
179
)
180

181
var (
182
        // encodingTypeToChunkSize maps an encoding type, to the max number of
183
        // short chan ID's using the encoding type that we can fit into a
184
        // single message safely.
185
        encodingTypeToChunkSize = map[lnwire.QueryEncoding]int32{
186
                lnwire.EncodingSortedPlain: 8000,
187
        }
188

189
        // ErrGossipSyncerExiting signals that the syncer has been killed.
190
        ErrGossipSyncerExiting = errors.New("gossip syncer exiting")
191

192
        // ErrSyncTransitionTimeout is an error returned when we've timed out
193
        // attempting to perform a sync transition.
194
        ErrSyncTransitionTimeout = errors.New("timed out attempting to " +
195
                "transition sync type")
196

197
        // zeroTimestamp is the timestamp we'll use when we want to indicate to
198
        // peers that we do not want to receive any new graph updates.
199
        zeroTimestamp time.Time
200
)
201

202
// syncTransitionReq encapsulates a request for a gossip syncer sync transition.
203
type syncTransitionReq struct {
204
        newSyncType SyncerType
205
        errChan     chan error
206
}
207

208
// historicalSyncReq encapsulates a request for a gossip syncer to perform a
209
// historical sync.
210
type historicalSyncReq struct {
211
        // doneChan is a channel that serves as a signal and is closed to ensure
212
        // the historical sync is attempted by the time we return to the caller.
213
        doneChan chan struct{}
214
}
215

216
// gossipSyncerCfg is a struct that packages all the information a GossipSyncer
217
// needs to carry out its duties.
218
type gossipSyncerCfg struct {
219
        // chainHash is the chain that this syncer is responsible for.
220
        chainHash chainhash.Hash
221

222
        // peerPub is the public key of the peer we're syncing with, serialized
223
        // in compressed format.
224
        peerPub [33]byte
225

226
        // channelSeries is the primary interface that we'll use to generate
227
        // our queries and respond to the queries of the remote peer.
228
        channelSeries ChannelGraphTimeSeries
229

230
        // encodingType is the current encoding type we're aware of. Requests
231
        // with different encoding types will be rejected.
232
        encodingType lnwire.QueryEncoding
233

234
        // chunkSize is the max number of short chan IDs using the syncer's
235
        // encoding type that we can fit into a single message safely.
236
        chunkSize int32
237

238
        // batchSize is the max number of channels the syncer will query from
239
        // the remote node in a single QueryShortChanIDs request.
240
        batchSize int32
241

242
        // sendToPeer sends a variadic number of messages to the remote peer.
243
        // This method should not block while waiting for sends to be written
244
        // to the wire.
245
        sendToPeer func(context.Context, ...lnwire.Message) error
246

247
        // sendToPeerSync sends a variadic number of messages to the remote
248
        // peer, blocking until all messages have been sent successfully or a
249
        // write error is encountered.
250
        sendToPeerSync func(context.Context, ...lnwire.Message) error
251

252
        // noSyncChannels will prevent the GossipSyncer from spawning a
253
        // channelGraphSyncer, meaning we will not try to reconcile unknown
254
        // channels with the remote peer.
255
        noSyncChannels bool
256

257
        // noReplyQueries will prevent the GossipSyncer from spawning a
258
        // replyHandler, meaning we will not reply to queries from our remote
259
        // peer.
260
        noReplyQueries bool
261

262
        // noTimestampQueryOption will prevent the GossipSyncer from querying
263
        // timestamps of announcement messages from the peer, and it will
264
        // prevent it from responding to timestamp queries.
265
        noTimestampQueryOption bool
266

267
        // ignoreHistoricalFilters will prevent syncers from replying with
268
        // historical data when the remote peer sets a gossip_timestamp_range.
269
        // This prevents ranges with old start times from causing us to dump the
270
        // graph on connect.
271
        ignoreHistoricalFilters bool
272

273
        // bestHeight returns the latest height known of the chain.
274
        bestHeight func() uint32
275

276
        // markGraphSynced updates the SyncManager's perception of whether we
277
        // have completed at least one historical sync.
278
        markGraphSynced func()
279

280
        // maxQueryChanRangeReplies is the maximum number of replies we'll allow
281
        // for a single QueryChannelRange request.
282
        maxQueryChanRangeReplies uint32
283

284
        // isStillZombieChannel takes the timestamps of the latest channel
285
        // updates for a channel and returns true if the channel should be
286
        // considered a zombie based on these timestamps.
287
        isStillZombieChannel func(time.Time, time.Time) bool
288
}
289

290
// GossipSyncer is a struct that handles synchronizing the channel graph state
291
// with a remote peer. The GossipSyncer implements a state machine that will
292
// progressively ensure we're synchronized with the channel state of the remote
293
// node. Once both nodes have been synchronized, we'll use an update filter to
294
// filter out which messages should be sent to a remote peer based on their
295
// update horizon. If the update horizon isn't specified, then we won't send
296
// them any channel updates at all.
297
type GossipSyncer struct {
298
        started sync.Once
299
        stopped sync.Once
300

301
        // state is the current state of the GossipSyncer.
302
        //
303
        // NOTE: This variable MUST be used atomically.
304
        state uint32
305

306
        // syncType denotes the SyncerType the gossip syncer is currently
307
        // exercising.
308
        //
309
        // NOTE: This variable MUST be used atomically.
310
        syncType uint32
311

312
        // remoteUpdateHorizon is the update horizon of the remote peer. We'll
313
        // use this to properly filter out any messages.
314
        remoteUpdateHorizon *lnwire.GossipTimestampRange
315

316
        // localUpdateHorizon is our local update horizon, we'll use this to
317
        // determine if we've already sent out our update.
318
        localUpdateHorizon *lnwire.GossipTimestampRange
319

320
        // syncTransitions is a channel through which new sync type transition
321
        // requests will be sent through. These requests should only be handled
322
        // when the gossip syncer is in a chansSynced state to ensure its state
323
        // machine behaves as expected.
324
        syncTransitionReqs chan *syncTransitionReq
325

326
        // historicalSyncReqs is a channel that serves as a signal for the
327
        // gossip syncer to perform a historical sync. These can only be done
328
        // once the gossip syncer is in a chansSynced state to ensure its state
329
        // machine behaves as expected.
330
        historicalSyncReqs chan *historicalSyncReq
331

332
        // genHistoricalChanRangeQuery when true signals to the gossip syncer
333
        // that it should request the remote peer for all of its known channel
334
        // IDs starting from the genesis block of the chain. This can only
335
        // happen if the gossip syncer receives a request to attempt a
336
        // historical sync. It can be unset if the syncer ever transitions from
337
        // PassiveSync to ActiveSync.
338
        genHistoricalChanRangeQuery bool
339

340
        // gossipMsgs is a channel that all responses to our queries from the
341
        // target peer will be sent over, these will be read by the
342
        // channelGraphSyncer.
343
        gossipMsgs chan lnwire.Message
344

345
        // queryMsgs is a channel that all queries from the remote peer will be
346
        // received over, these will be read by the replyHandler.
347
        queryMsgs chan lnwire.Message
348

349
        // curQueryRangeMsg keeps track of the latest QueryChannelRange message
350
        // we've sent to a peer to ensure we've consumed all expected replies.
351
        // This field is primarily used within the waitingQueryChanReply state.
352
        curQueryRangeMsg *lnwire.QueryChannelRange
353

354
        // prevReplyChannelRange keeps track of the previous ReplyChannelRange
355
        // message we've received from a peer to ensure they've fully replied to
356
        // our query by ensuring they covered our requested block range. This
357
        // field is primarily used within the waitingQueryChanReply state.
358
        prevReplyChannelRange *lnwire.ReplyChannelRange
359

360
        // bufferedChanRangeReplies is used in the waitingQueryChanReply to
361
        // buffer all the chunked response to our query.
362
        bufferedChanRangeReplies []graphdb.ChannelUpdateInfo
363

364
        // numChanRangeRepliesRcvd is used to track the number of replies
365
        // received as part of a QueryChannelRange. This field is primarily used
366
        // within the waitingQueryChanReply state.
367
        numChanRangeRepliesRcvd uint32
368

369
        // newChansToQuery is used to pass the set of channels we should query
370
        // for from the waitingQueryChanReply state to the queryNewChannels
371
        // state.
372
        newChansToQuery []lnwire.ShortChannelID
373

374
        cfg gossipSyncerCfg
375

376
        // syncedSignal is a channel that, if set, will be closed when the
377
        // GossipSyncer reaches its terminal chansSynced state.
378
        syncedSignal chan struct{}
379

380
        // syncerSema is used to more finely control the syncer's ability to
381
        // respond to gossip timestamp range messages.
382
        syncerSema chan struct{}
383

384
        sync.Mutex
385

386
        // cg is a helper that encapsulates a wait group and quit channel and
387
        // allows contexts that either block or cancel on those depending on
388
        // the use case.
389
        cg *fn.ContextGuard
390
}
391

392
// newGossipSyncer returns a new instance of the GossipSyncer populated using
393
// the passed config.
394
func newGossipSyncer(cfg gossipSyncerCfg, sema chan struct{}) *GossipSyncer {
3✔
395
        return &GossipSyncer{
3✔
396
                cfg:                cfg,
3✔
397
                syncTransitionReqs: make(chan *syncTransitionReq),
3✔
398
                historicalSyncReqs: make(chan *historicalSyncReq),
3✔
399
                gossipMsgs:         make(chan lnwire.Message, syncerBufferSize),
3✔
400
                queryMsgs:          make(chan lnwire.Message, syncerBufferSize),
3✔
401
                syncerSema:         sema,
3✔
402
                cg:                 fn.NewContextGuard(),
3✔
403
        }
3✔
404
}
3✔
405

406
// Start starts the GossipSyncer and any goroutines that it needs to carry out
407
// its duties.
408
func (g *GossipSyncer) Start() {
3✔
409
        g.started.Do(func() {
6✔
410
                log.Debugf("Starting GossipSyncer(%x)", g.cfg.peerPub[:])
3✔
411

3✔
412
                ctx, _ := g.cg.Create(context.Background())
3✔
413

3✔
414
                // TODO(conner): only spawn channelGraphSyncer if remote
3✔
415
                // supports gossip queries, and only spawn replyHandler if we
3✔
416
                // advertise support
3✔
417
                if !g.cfg.noSyncChannels {
6✔
418
                        g.cg.WgAdd(1)
3✔
419
                        go g.channelGraphSyncer(ctx)
3✔
420
                }
3✔
421
                if !g.cfg.noReplyQueries {
6✔
422
                        g.cg.WgAdd(1)
3✔
423
                        go g.replyHandler(ctx)
3✔
424
                }
3✔
425
        })
426
}
427

428
// Stop signals the GossipSyncer for a graceful exit, then waits until it has
429
// exited.
430
func (g *GossipSyncer) Stop() {
3✔
431
        g.stopped.Do(func() {
6✔
432
                log.Debugf("Stopping GossipSyncer(%x)", g.cfg.peerPub[:])
3✔
433
                defer log.Debugf("GossipSyncer(%x) stopped", g.cfg.peerPub[:])
3✔
434

3✔
435
                g.cg.Quit()
3✔
436
        })
3✔
437
}
438

439
// handleSyncingChans handles the state syncingChans for the GossipSyncer. When
440
// in this state, we will send a QueryChannelRange msg to our peer and advance
441
// the syncer's state to waitingQueryRangeReply.
442
func (g *GossipSyncer) handleSyncingChans(ctx context.Context) {
3✔
443
        // Prepare the query msg.
3✔
444
        queryRangeMsg, err := g.genChanRangeQuery(
3✔
445
                ctx, g.genHistoricalChanRangeQuery,
3✔
446
        )
3✔
447
        if err != nil {
3✔
448
                log.Errorf("Unable to gen chan range query: %v", err)
×
449
                return
×
450
        }
×
451

452
        // Acquire a lock so the following state transition is atomic.
453
        //
454
        // NOTE: We must lock the following steps as it's possible we get an
455
        // immediate response (ReplyChannelRange) after sending the query msg.
456
        // The response is handled in ProcessQueryMsg, which requires the
457
        // current state to be waitingQueryRangeReply.
458
        g.Lock()
3✔
459
        defer g.Unlock()
3✔
460

3✔
461
        // Send the msg to the remote peer, which is non-blocking as
3✔
462
        // `sendToPeer` only queues the msg in Brontide.
3✔
463
        err = g.cfg.sendToPeer(ctx, queryRangeMsg)
3✔
464
        if err != nil {
3✔
465
                log.Errorf("Unable to send chan range query: %v", err)
×
466
                return
×
467
        }
×
468

469
        // With the message sent successfully, we'll transition into the next
470
        // state where we wait for their reply.
471
        g.setSyncState(waitingQueryRangeReply)
3✔
472
}
473

474
// channelGraphSyncer is the main goroutine responsible for ensuring that we
475
// properly channel graph state with the remote peer, and also that we only
476
// send them messages which actually pass their defined update horizon.
477
func (g *GossipSyncer) channelGraphSyncer(ctx context.Context) {
3✔
478
        defer g.cg.WgDone()
3✔
479

3✔
480
        for {
6✔
481
                state := g.syncState()
3✔
482
                syncType := g.SyncType()
3✔
483

3✔
484
                log.Debugf("GossipSyncer(%x): state=%v, type=%v",
3✔
485
                        g.cfg.peerPub[:], state, syncType)
3✔
486

3✔
487
                switch state {
3✔
488
                // When we're in this state, we're trying to synchronize our
489
                // view of the network with the remote peer. We'll kick off
490
                // this sync by asking them for the set of channels they
491
                // understand, as we'll as responding to any other queries by
492
                // them.
493
                case syncingChans:
3✔
494
                        g.handleSyncingChans(ctx)
3✔
495

496
                // In this state, we've sent out our initial channel range
497
                // query and are waiting for the final response from the remote
498
                // peer before we perform a diff to see with channels they know
499
                // of that we don't.
500
                case waitingQueryRangeReply:
3✔
501
                        // We'll wait to either process a new message from the
3✔
502
                        // remote party, or exit due to the gossiper exiting,
3✔
503
                        // or us being signalled to do so.
3✔
504
                        select {
3✔
505
                        case msg := <-g.gossipMsgs:
3✔
506
                                // The remote peer is sending a response to our
3✔
507
                                // initial query, we'll collate this response,
3✔
508
                                // and see if it's the final one in the series.
3✔
509
                                // If so, we can then transition to querying
3✔
510
                                // for the new channels.
3✔
511
                                queryReply, ok := msg.(*lnwire.ReplyChannelRange)
3✔
512
                                if ok {
6✔
513
                                        err := g.processChanRangeReply(
3✔
514
                                                ctx, queryReply,
3✔
515
                                        )
3✔
516
                                        if err != nil {
3✔
517
                                                log.Errorf("Unable to "+
×
518
                                                        "process chan range "+
×
519
                                                        "query: %v", err)
×
520
                                                return
×
521
                                        }
×
522
                                        continue
3✔
523
                                }
524

525
                                log.Warnf("Unexpected message: %T in state=%v",
×
526
                                        msg, state)
×
527

528
                        case <-g.cg.Done():
×
529
                                return
×
530

UNCOV
531
                        case <-ctx.Done():
×
UNCOV
532
                                return
×
533
                        }
534

535
                // We'll enter this state once we've discovered which channels
536
                // the remote party knows of that we don't yet know of
537
                // ourselves.
538
                case queryNewChannels:
3✔
539
                        // First, we'll attempt to continue our channel
3✔
540
                        // synchronization by continuing to send off another
3✔
541
                        // query chunk.
3✔
542
                        done := g.synchronizeChanIDs(ctx)
3✔
543

3✔
544
                        // If this wasn't our last query, then we'll need to
3✔
545
                        // transition to our waiting state.
3✔
546
                        if !done {
6✔
547
                                continue
3✔
548
                        }
549

550
                        // If we're fully synchronized, then we can transition
551
                        // to our terminal state.
552
                        g.setSyncState(chansSynced)
3✔
553

3✔
554
                        // Ensure that the sync manager becomes aware that the
3✔
555
                        // historical sync completed so synced_to_graph is
3✔
556
                        // updated over rpc.
3✔
557
                        g.cfg.markGraphSynced()
3✔
558

559
                // In this state, we've just sent off a new query for channels
560
                // that we don't yet know of. We'll remain in this state until
561
                // the remote party signals they've responded to our query in
562
                // totality.
563
                case waitingQueryChanReply:
3✔
564
                        // Once we've sent off our query, we'll wait for either
3✔
565
                        // an ending reply, or just another query from the
3✔
566
                        // remote peer.
3✔
567
                        select {
3✔
568
                        case msg := <-g.gossipMsgs:
3✔
569
                                // If this is the final reply to one of our
3✔
570
                                // queries, then we'll loop back into our query
3✔
571
                                // state to send of the remaining query chunks.
3✔
572
                                _, ok := msg.(*lnwire.ReplyShortChanIDsEnd)
3✔
573
                                if ok {
6✔
574
                                        g.setSyncState(queryNewChannels)
3✔
575
                                        continue
3✔
576
                                }
577

578
                                log.Warnf("Unexpected message: %T in state=%v",
×
579
                                        msg, state)
×
580

581
                        case <-g.cg.Done():
×
582
                                return
×
583

584
                        case <-ctx.Done():
×
585
                                return
×
586
                        }
587

588
                // This is our final terminal state where we'll only reply to
589
                // any further queries by the remote peer.
590
                case chansSynced:
3✔
591
                        g.Lock()
3✔
592
                        if g.syncedSignal != nil {
6✔
593
                                close(g.syncedSignal)
3✔
594
                                g.syncedSignal = nil
3✔
595
                        }
3✔
596
                        g.Unlock()
3✔
597

3✔
598
                        // If we haven't yet sent out our update horizon, and
3✔
599
                        // we want to receive real-time channel updates, we'll
3✔
600
                        // do so now.
3✔
601
                        if g.localUpdateHorizon == nil &&
3✔
602
                                syncType.IsActiveSync() {
6✔
603

3✔
604
                                err := g.sendGossipTimestampRange(
3✔
605
                                        ctx, time.Now(), math.MaxUint32,
3✔
606
                                )
3✔
607
                                if err != nil {
3✔
608
                                        log.Errorf("Unable to send update "+
×
609
                                                "horizon to %x: %v",
×
610
                                                g.cfg.peerPub, err)
×
611
                                }
×
612
                        }
613
                        // With our horizon set, we'll simply reply to any new
614
                        // messages or process any state transitions and exit if
615
                        // needed.
616
                        fallthrough
3✔
617

618
                // Pinned peers will begin in this state, since they will
619
                // immediately receive a request to perform a historical sync.
620
                // Otherwise, we fall through after ending in chansSynced to
621
                // facilitate new requests.
622
                case syncerIdle:
3✔
623
                        select {
3✔
624
                        case req := <-g.syncTransitionReqs:
3✔
625
                                req.errChan <- g.handleSyncTransition(ctx, req)
3✔
626

627
                        case req := <-g.historicalSyncReqs:
3✔
628
                                g.handleHistoricalSync(req)
3✔
629

630
                        case <-g.cg.Done():
×
631
                                return
×
632

633
                        case <-ctx.Done():
3✔
634
                                return
3✔
635
                        }
636
                }
637
        }
638
}
639

640
// replyHandler is an event loop whose sole purpose is to reply to the remote
641
// peers queries. Our replyHandler will respond to messages generated by their
642
// channelGraphSyncer, and vice versa. Each party's channelGraphSyncer drives
643
// the other's replyHandler, allowing the replyHandler to operate independently
644
// from the state machine maintained on the same node.
645
//
646
// NOTE: This method MUST be run as a goroutine.
647
func (g *GossipSyncer) replyHandler(ctx context.Context) {
3✔
648
        defer g.cg.WgDone()
3✔
649

3✔
650
        for {
6✔
651
                select {
3✔
652
                case msg := <-g.queryMsgs:
3✔
653
                        err := g.replyPeerQueries(ctx, msg)
3✔
654
                        switch {
3✔
655
                        case err == ErrGossipSyncerExiting:
×
656
                                return
×
657

658
                        case err == lnpeer.ErrPeerExiting:
×
659
                                return
×
660

661
                        case err != nil:
×
662
                                log.Errorf("Unable to reply to peer "+
×
663
                                        "query: %v", err)
×
664
                        }
665

UNCOV
666
                case <-g.cg.Done():
×
UNCOV
667
                        return
×
668

669
                case <-ctx.Done():
3✔
670
                        return
3✔
671
                }
672
        }
673
}
674

675
// sendGossipTimestampRange constructs and sets a GossipTimestampRange for the
676
// syncer and sends it to the remote peer.
677
func (g *GossipSyncer) sendGossipTimestampRange(ctx context.Context,
678
        firstTimestamp time.Time, timestampRange uint32) error {
3✔
679

3✔
680
        endTimestamp := firstTimestamp.Add(
3✔
681
                time.Duration(timestampRange) * time.Second,
3✔
682
        )
3✔
683

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

3✔
687
        localUpdateHorizon := &lnwire.GossipTimestampRange{
3✔
688
                ChainHash:      g.cfg.chainHash,
3✔
689
                FirstTimestamp: uint32(firstTimestamp.Unix()),
3✔
690
                TimestampRange: timestampRange,
3✔
691
        }
3✔
692

3✔
693
        if err := g.cfg.sendToPeer(ctx, localUpdateHorizon); err != nil {
3✔
694
                return err
×
695
        }
×
696

697
        if firstTimestamp == zeroTimestamp && timestampRange == 0 {
3✔
UNCOV
698
                g.localUpdateHorizon = nil
×
699
        } else {
3✔
700
                g.localUpdateHorizon = localUpdateHorizon
3✔
701
        }
3✔
702

703
        return nil
3✔
704
}
705

706
// synchronizeChanIDs is called by the channelGraphSyncer when we need to query
707
// the remote peer for its known set of channel IDs within a particular block
708
// range. This method will be called continually until the entire range has
709
// been queried for with a response received. We'll chunk our requests as
710
// required to ensure they fit into a single message. We may re-renter this
711
// state in the case that chunking is required.
712
func (g *GossipSyncer) synchronizeChanIDs(ctx context.Context) bool {
3✔
713
        // If we're in this state yet there are no more new channels to query
3✔
714
        // for, then we'll transition to our final synced state and return true
3✔
715
        // to signal that we're fully synchronized.
3✔
716
        if len(g.newChansToQuery) == 0 {
6✔
717
                log.Infof("GossipSyncer(%x): no more chans to query",
3✔
718
                        g.cfg.peerPub[:])
3✔
719

3✔
720
                return true
3✔
721
        }
3✔
722

723
        // Otherwise, we'll issue our next chunked query to receive replies
724
        // for.
725
        var queryChunk []lnwire.ShortChannelID
3✔
726

3✔
727
        // If the number of channels to query for is less than the chunk size,
3✔
728
        // then we can issue a single query.
3✔
729
        if int32(len(g.newChansToQuery)) < g.cfg.batchSize {
6✔
730
                queryChunk = g.newChansToQuery
3✔
731
                g.newChansToQuery = nil
3✔
732

3✔
733
        } else {
3✔
UNCOV
734
                // Otherwise, we'll need to only query for the next chunk.
×
UNCOV
735
                // We'll slice into our query chunk, then slide down our main
×
UNCOV
736
                // pointer down by the chunk size.
×
UNCOV
737
                queryChunk = g.newChansToQuery[:g.cfg.batchSize]
×
UNCOV
738
                g.newChansToQuery = g.newChansToQuery[g.cfg.batchSize:]
×
UNCOV
739
        }
×
740

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

3✔
744
        // Change the state before sending the query msg.
3✔
745
        g.setSyncState(waitingQueryChanReply)
3✔
746

3✔
747
        // With our chunk obtained, we'll send over our next query, then return
3✔
748
        // false indicating that we're net yet fully synced.
3✔
749
        err := g.cfg.sendToPeer(ctx, &lnwire.QueryShortChanIDs{
3✔
750
                ChainHash:    g.cfg.chainHash,
3✔
751
                EncodingType: lnwire.EncodingSortedPlain,
3✔
752
                ShortChanIDs: queryChunk,
3✔
753
        })
3✔
754
        if err != nil {
3✔
755
                log.Errorf("Unable to sync chan IDs: %v", err)
×
756
        }
×
757

758
        return false
3✔
759
}
760

761
// isLegacyReplyChannelRange determines where a ReplyChannelRange message is
762
// considered legacy. There was a point where lnd used to include the same query
763
// over multiple replies, rather than including the portion of the query the
764
// reply is handling. We'll use this as a way of detecting whether we are
765
// communicating with a legacy node so we can properly sync with them.
766
func isLegacyReplyChannelRange(query *lnwire.QueryChannelRange,
767
        reply *lnwire.ReplyChannelRange) bool {
3✔
768

3✔
769
        return (reply.ChainHash == query.ChainHash &&
3✔
770
                reply.FirstBlockHeight == query.FirstBlockHeight &&
3✔
771
                reply.NumBlocks == query.NumBlocks)
3✔
772
}
3✔
773

774
// processChanRangeReply is called each time the GossipSyncer receives a new
775
// reply to the initial range query to discover new channels that it didn't
776
// previously know of.
777
func (g *GossipSyncer) processChanRangeReply(_ context.Context,
778
        msg *lnwire.ReplyChannelRange) error {
3✔
779

3✔
780
        // isStale returns whether the timestamp is too far into the past.
3✔
781
        isStale := func(timestamp time.Time) bool {
6✔
782
                return time.Since(timestamp) > graph.DefaultChannelPruneExpiry
3✔
783
        }
3✔
784

785
        // isSkewed returns whether the timestamp is too far into the future.
786
        isSkewed := func(timestamp time.Time) bool {
6✔
787
                return time.Until(timestamp) > graph.DefaultChannelPruneExpiry
3✔
788
        }
3✔
789

790
        // If we're not communicating with a legacy node, we'll apply some
791
        // further constraints on their reply to ensure it satisfies our query.
792
        if !isLegacyReplyChannelRange(g.curQueryRangeMsg, msg) {
3✔
UNCOV
793
                // The first block should be within our original request.
×
UNCOV
794
                if msg.FirstBlockHeight < g.curQueryRangeMsg.FirstBlockHeight {
×
795
                        return fmt.Errorf("reply includes channels for height "+
×
796
                                "%v prior to query %v", msg.FirstBlockHeight,
×
797
                                g.curQueryRangeMsg.FirstBlockHeight)
×
798
                }
×
799

800
                // The last block should also be. We don't need to check the
801
                // intermediate ones because they should already be in sorted
802
                // order.
UNCOV
803
                replyLastHeight := msg.LastBlockHeight()
×
UNCOV
804
                queryLastHeight := g.curQueryRangeMsg.LastBlockHeight()
×
UNCOV
805
                if replyLastHeight > queryLastHeight {
×
806
                        return fmt.Errorf("reply includes channels for height "+
×
807
                                "%v after query %v", replyLastHeight,
×
808
                                queryLastHeight)
×
809
                }
×
810

811
                // If we've previously received a reply for this query, look at
812
                // its last block to ensure the current reply properly follows
813
                // it.
UNCOV
814
                if g.prevReplyChannelRange != nil {
×
UNCOV
815
                        prevReply := g.prevReplyChannelRange
×
UNCOV
816
                        prevReplyLastHeight := prevReply.LastBlockHeight()
×
UNCOV
817

×
UNCOV
818
                        // The current reply can either start from the previous
×
UNCOV
819
                        // reply's last block, if there are still more channels
×
UNCOV
820
                        // for the same block, or the block after.
×
UNCOV
821
                        if msg.FirstBlockHeight != prevReplyLastHeight &&
×
UNCOV
822
                                msg.FirstBlockHeight != prevReplyLastHeight+1 {
×
823

×
824
                                return fmt.Errorf("first block of reply %v "+
×
825
                                        "does not continue from last block of "+
×
826
                                        "previous %v", msg.FirstBlockHeight,
×
827
                                        prevReplyLastHeight)
×
828
                        }
×
829
                }
830
        }
831

832
        g.prevReplyChannelRange = msg
3✔
833

3✔
834
        for i, scid := range msg.ShortChanIDs {
6✔
835
                info := graphdb.NewChannelUpdateInfo(
3✔
836
                        scid, time.Time{}, time.Time{},
3✔
837
                )
3✔
838

3✔
839
                if len(msg.Timestamps) != 0 {
6✔
840
                        t1 := time.Unix(int64(msg.Timestamps[i].Timestamp1), 0)
3✔
841
                        info.Node1UpdateTimestamp = t1
3✔
842

3✔
843
                        t2 := time.Unix(int64(msg.Timestamps[i].Timestamp2), 0)
3✔
844
                        info.Node2UpdateTimestamp = t2
3✔
845

3✔
846
                        // Sort out all channels with outdated or skewed
3✔
847
                        // timestamps. Both timestamps need to be out of
3✔
848
                        // boundaries for us to skip the channel and not query
3✔
849
                        // it later on.
3✔
850
                        switch {
3✔
851
                        case isStale(info.Node1UpdateTimestamp) &&
UNCOV
852
                                isStale(info.Node2UpdateTimestamp):
×
UNCOV
853

×
UNCOV
854
                                continue
×
855

856
                        case isSkewed(info.Node1UpdateTimestamp) &&
UNCOV
857
                                isSkewed(info.Node2UpdateTimestamp):
×
UNCOV
858

×
UNCOV
859
                                continue
×
860

861
                        case isStale(info.Node1UpdateTimestamp) &&
UNCOV
862
                                isSkewed(info.Node2UpdateTimestamp):
×
UNCOV
863

×
UNCOV
864
                                continue
×
865

866
                        case isStale(info.Node2UpdateTimestamp) &&
UNCOV
867
                                isSkewed(info.Node1UpdateTimestamp):
×
UNCOV
868

×
UNCOV
869
                                continue
×
870
                        }
871
                }
872

873
                g.bufferedChanRangeReplies = append(
3✔
874
                        g.bufferedChanRangeReplies, info,
3✔
875
                )
3✔
876
        }
877

878
        switch g.cfg.encodingType {
3✔
879
        case lnwire.EncodingSortedPlain:
3✔
880
                g.numChanRangeRepliesRcvd++
3✔
881
        case lnwire.EncodingSortedZlib:
×
882
                g.numChanRangeRepliesRcvd += maxQueryChanRangeRepliesZlibFactor
×
883
        default:
×
884
                return fmt.Errorf("unhandled encoding type %v", g.cfg.encodingType)
×
885
        }
886

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

3✔
890
        // If this isn't the last response and we can continue to receive more,
3✔
891
        // then we can exit as we've already buffered the latest portion of the
3✔
892
        // streaming reply.
3✔
893
        maxReplies := g.cfg.maxQueryChanRangeReplies
3✔
894
        switch {
3✔
895
        // If we're communicating with a legacy node, we'll need to look at the
896
        // complete field.
897
        case isLegacyReplyChannelRange(g.curQueryRangeMsg, msg):
3✔
898
                if msg.Complete == 0 && g.numChanRangeRepliesRcvd < maxReplies {
3✔
UNCOV
899
                        return nil
×
UNCOV
900
                }
×
901

902
        // Otherwise, we'll look at the reply's height range.
UNCOV
903
        default:
×
UNCOV
904
                replyLastHeight := msg.LastBlockHeight()
×
UNCOV
905
                queryLastHeight := g.curQueryRangeMsg.LastBlockHeight()
×
UNCOV
906

×
UNCOV
907
                // TODO(wilmer): This might require some padding if the remote
×
UNCOV
908
                // node is not aware of the last height we sent them, i.e., is
×
UNCOV
909
                // behind a few blocks from us.
×
UNCOV
910
                if replyLastHeight < queryLastHeight &&
×
UNCOV
911
                        g.numChanRangeRepliesRcvd < maxReplies {
×
UNCOV
912

×
UNCOV
913
                        return nil
×
UNCOV
914
                }
×
915
        }
916

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

3✔
920
        // Otherwise, this is the final response, so we'll now check to see
3✔
921
        // which channels they know of that we don't.
3✔
922
        newChans, err := g.cfg.channelSeries.FilterKnownChanIDs(
3✔
923
                g.cfg.chainHash, g.bufferedChanRangeReplies,
3✔
924
                g.cfg.isStillZombieChannel,
3✔
925
        )
3✔
926
        if err != nil {
3✔
927
                return fmt.Errorf("unable to filter chan ids: %w", err)
×
928
        }
×
929

930
        // As we've received the entirety of the reply, we no longer need to
931
        // hold on to the set of buffered replies or the original query that
932
        // prompted the replies, so we'll let that be garbage collected now.
933
        g.curQueryRangeMsg = nil
3✔
934
        g.prevReplyChannelRange = nil
3✔
935
        g.bufferedChanRangeReplies = nil
3✔
936
        g.numChanRangeRepliesRcvd = 0
3✔
937

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

3✔
944
                g.setSyncState(chansSynced)
3✔
945

3✔
946
                // Ensure that the sync manager becomes aware that the
3✔
947
                // historical sync completed so synced_to_graph is updated over
3✔
948
                // rpc.
3✔
949
                g.cfg.markGraphSynced()
3✔
950
                return nil
3✔
951
        }
3✔
952

953
        // Otherwise, we'll set the set of channels that we need to query for
954
        // the next state, and also transition our state.
955
        g.newChansToQuery = newChans
3✔
956
        g.setSyncState(queryNewChannels)
3✔
957

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

3✔
961
        return nil
3✔
962
}
963

964
// genChanRangeQuery generates the initial message we'll send to the remote
965
// party when we're kicking off the channel graph synchronization upon
966
// connection. The historicalQuery boolean can be used to generate a query from
967
// the genesis block of the chain.
968
func (g *GossipSyncer) genChanRangeQuery(_ context.Context,
969
        historicalQuery bool) (*lnwire.QueryChannelRange, error) {
3✔
970

3✔
971
        // First, we'll query our channel graph time series for its highest
3✔
972
        // known channel ID.
3✔
973
        newestChan, err := g.cfg.channelSeries.HighestChanID(g.cfg.chainHash)
3✔
974
        if err != nil {
3✔
975
                return nil, err
×
976
        }
×
977

978
        // Once we have the chan ID of the newest, we'll obtain the block height
979
        // of the channel, then subtract our default horizon to ensure we don't
980
        // miss any channels. By default, we go back 1 day from the newest
981
        // channel, unless we're attempting a historical sync, where we'll
982
        // actually start from the genesis block instead.
983
        var startHeight uint32
3✔
984
        switch {
3✔
985
        case historicalQuery:
3✔
986
                fallthrough
3✔
987
        case newestChan.BlockHeight <= chanRangeQueryBuffer:
3✔
988
                startHeight = 0
3✔
UNCOV
989
        default:
×
UNCOV
990
                startHeight = newestChan.BlockHeight - chanRangeQueryBuffer
×
991
        }
992

993
        // Determine the number of blocks to request based on our best height.
994
        // We'll take into account any potential underflows and explicitly set
995
        // numBlocks to its minimum value of 1 if so.
996
        bestHeight := g.cfg.bestHeight()
3✔
997
        numBlocks := bestHeight - startHeight
3✔
998
        if int64(numBlocks) < 1 {
3✔
999
                numBlocks = 1
×
1000
        }
×
1001

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

3✔
1005
        // Finally, we'll craft the channel range query, using our starting
3✔
1006
        // height, then asking for all known channels to the foreseeable end of
3✔
1007
        // the main chain.
3✔
1008
        query := &lnwire.QueryChannelRange{
3✔
1009
                ChainHash:        g.cfg.chainHash,
3✔
1010
                FirstBlockHeight: startHeight,
3✔
1011
                NumBlocks:        numBlocks,
3✔
1012
        }
3✔
1013

3✔
1014
        if !g.cfg.noTimestampQueryOption {
6✔
1015
                query.QueryOptions = lnwire.NewTimestampQueryOption()
3✔
1016
        }
3✔
1017

1018
        g.curQueryRangeMsg = query
3✔
1019

3✔
1020
        return query, nil
3✔
1021
}
1022

1023
// replyPeerQueries is called in response to any query by the remote peer.
1024
// We'll examine our state and send back our best response.
1025
func (g *GossipSyncer) replyPeerQueries(ctx context.Context,
1026
        msg lnwire.Message) error {
3✔
1027

3✔
1028
        switch msg := msg.(type) {
3✔
1029

1030
        // In this state, we'll also handle any incoming channel range queries
1031
        // from the remote peer as they're trying to sync their state as well.
1032
        case *lnwire.QueryChannelRange:
3✔
1033
                return g.replyChanRangeQuery(ctx, msg)
3✔
1034

1035
        // If the remote peer skips straight to requesting new channels that
1036
        // they don't know of, then we'll ensure that we also handle this case.
1037
        case *lnwire.QueryShortChanIDs:
3✔
1038
                return g.replyShortChanIDs(ctx, msg)
3✔
1039

1040
        default:
×
1041
                return fmt.Errorf("unknown message: %T", msg)
×
1042
        }
1043
}
1044

1045
// replyChanRangeQuery will be dispatched in response to a channel range query
1046
// by the remote node. We'll query the channel time series for channels that
1047
// meet the channel range, then chunk our responses to the remote node. We also
1048
// ensure that our final fragment carries the "complete" bit to indicate the
1049
// end of our streaming response.
1050
func (g *GossipSyncer) replyChanRangeQuery(ctx context.Context,
1051
        query *lnwire.QueryChannelRange) error {
3✔
1052

3✔
1053
        // Before responding, we'll check to ensure that the remote peer is
3✔
1054
        // querying for the same chain that we're on. If not, we'll send back a
3✔
1055
        // response with a complete value of zero to indicate we're on a
3✔
1056
        // different chain.
3✔
1057
        if g.cfg.chainHash != query.ChainHash {
3✔
UNCOV
1058
                log.Warnf("Remote peer requested QueryChannelRange for "+
×
UNCOV
1059
                        "chain=%v, we're on chain=%v", query.ChainHash,
×
UNCOV
1060
                        g.cfg.chainHash)
×
UNCOV
1061

×
UNCOV
1062
                return g.cfg.sendToPeerSync(ctx, &lnwire.ReplyChannelRange{
×
UNCOV
1063
                        ChainHash:        query.ChainHash,
×
UNCOV
1064
                        FirstBlockHeight: query.FirstBlockHeight,
×
UNCOV
1065
                        NumBlocks:        query.NumBlocks,
×
UNCOV
1066
                        Complete:         0,
×
UNCOV
1067
                        EncodingType:     g.cfg.encodingType,
×
UNCOV
1068
                        ShortChanIDs:     nil,
×
UNCOV
1069
                })
×
UNCOV
1070
        }
×
1071

1072
        log.Infof("GossipSyncer(%x): filtering chan range: start_height=%v, "+
3✔
1073
                "num_blocks=%v", g.cfg.peerPub[:], query.FirstBlockHeight,
3✔
1074
                query.NumBlocks)
3✔
1075

3✔
1076
        // Check if the query asked for timestamps. We will only serve
3✔
1077
        // timestamps if this has not been disabled with
3✔
1078
        // noTimestampQueryOption.
3✔
1079
        withTimestamps := query.WithTimestamps() &&
3✔
1080
                !g.cfg.noTimestampQueryOption
3✔
1081

3✔
1082
        // Next, we'll consult the time series to obtain the set of known
3✔
1083
        // channel ID's that match their query.
3✔
1084
        startBlock := query.FirstBlockHeight
3✔
1085
        endBlock := query.LastBlockHeight()
3✔
1086
        channelRanges, err := g.cfg.channelSeries.FilterChannelRange(
3✔
1087
                query.ChainHash, startBlock, endBlock, withTimestamps,
3✔
1088
        )
3✔
1089
        if err != nil {
3✔
1090
                return err
×
1091
        }
×
1092

1093
        // TODO(roasbeef): means can't send max uint above?
1094
        //  * or make internal 64
1095

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

3✔
1103
                // The number of blocks contained in the current chunk (the
3✔
1104
                // total span) is the difference between the last channel ID and
3✔
1105
                // the first in the range. We add one as even if all channels
3✔
1106
                // returned are in the same block, we need to count that.
3✔
1107
                numBlocks := lastHeight - firstHeight + 1
3✔
1108
                complete := uint8(0)
3✔
1109
                if finalChunk {
6✔
1110
                        complete = 1
3✔
1111
                }
3✔
1112

1113
                var timestamps lnwire.Timestamps
3✔
1114
                if withTimestamps {
6✔
1115
                        timestamps = make(lnwire.Timestamps, len(channelChunk))
3✔
1116
                }
3✔
1117

1118
                scids := make([]lnwire.ShortChannelID, len(channelChunk))
3✔
1119
                for i, info := range channelChunk {
6✔
1120
                        scids[i] = info.ShortChannelID
3✔
1121

3✔
1122
                        if !withTimestamps {
3✔
UNCOV
1123
                                continue
×
1124
                        }
1125

1126
                        timestamps[i].Timestamp1 = uint32(
3✔
1127
                                info.Node1UpdateTimestamp.Unix(),
3✔
1128
                        )
3✔
1129

3✔
1130
                        timestamps[i].Timestamp2 = uint32(
3✔
1131
                                info.Node2UpdateTimestamp.Unix(),
3✔
1132
                        )
3✔
1133
                }
1134

1135
                return g.cfg.sendToPeerSync(ctx, &lnwire.ReplyChannelRange{
3✔
1136
                        ChainHash:        query.ChainHash,
3✔
1137
                        NumBlocks:        numBlocks,
3✔
1138
                        FirstBlockHeight: firstHeight,
3✔
1139
                        Complete:         complete,
3✔
1140
                        EncodingType:     g.cfg.encodingType,
3✔
1141
                        ShortChanIDs:     scids,
3✔
1142
                        Timestamps:       timestamps,
3✔
1143
                })
3✔
1144
        }
1145

1146
        var (
3✔
1147
                firstHeight  = query.FirstBlockHeight
3✔
1148
                lastHeight   uint32
3✔
1149
                channelChunk []graphdb.ChannelUpdateInfo
3✔
1150
        )
3✔
1151

3✔
1152
        // chunkSize is the maximum number of SCIDs that we can safely put in a
3✔
1153
        // single message. If we also need to include timestamps though, then
3✔
1154
        // this number is halved since encoding two timestamps takes the same
3✔
1155
        // number of bytes as encoding an SCID.
3✔
1156
        chunkSize := g.cfg.chunkSize
3✔
1157
        if withTimestamps {
6✔
1158
                chunkSize /= 2
3✔
1159
        }
3✔
1160

1161
        for _, channelRange := range channelRanges {
6✔
1162
                channels := channelRange.Channels
3✔
1163
                numChannels := int32(len(channels))
3✔
1164
                numLeftToAdd := chunkSize - int32(len(channelChunk))
3✔
1165

3✔
1166
                // Include the current block in the ongoing chunk if it can fit
3✔
1167
                // and move on to the next block.
3✔
1168
                if numChannels <= numLeftToAdd {
6✔
1169
                        channelChunk = append(channelChunk, channels...)
3✔
1170
                        continue
3✔
1171
                }
1172

1173
                // Otherwise, we need to send our existing channel chunk as is
1174
                // as its own reply and start a new one for the current block.
1175
                // We'll mark the end of our current chunk as the height before
1176
                // the current block to ensure the whole query range is replied
1177
                // to.
UNCOV
1178
                log.Infof("GossipSyncer(%x): sending range chunk of size=%v",
×
UNCOV
1179
                        g.cfg.peerPub[:], len(channelChunk))
×
UNCOV
1180

×
UNCOV
1181
                lastHeight = channelRange.Height - 1
×
UNCOV
1182
                err := sendReplyForChunk(
×
UNCOV
1183
                        channelChunk, firstHeight, lastHeight, false,
×
UNCOV
1184
                )
×
UNCOV
1185
                if err != nil {
×
1186
                        return err
×
1187
                }
×
1188

1189
                // With the reply constructed, we'll start tallying channels for
1190
                // our next one keeping in mind our chunk size. This may result
1191
                // in channels for this block being left out from the reply, but
1192
                // this isn't an issue since we'll randomly shuffle them and we
1193
                // assume a historical gossip sync is performed at a later time.
UNCOV
1194
                firstHeight = channelRange.Height
×
UNCOV
1195
                finalChunkSize := numChannels
×
UNCOV
1196
                exceedsChunkSize := numChannels > chunkSize
×
UNCOV
1197
                if exceedsChunkSize {
×
1198
                        rand.Shuffle(len(channels), func(i, j int) {
×
1199
                                channels[i], channels[j] = channels[j], channels[i]
×
1200
                        })
×
1201
                        finalChunkSize = chunkSize
×
1202
                }
UNCOV
1203
                channelChunk = channels[:finalChunkSize]
×
UNCOV
1204

×
UNCOV
1205
                // Sort the chunk once again if we had to shuffle it.
×
UNCOV
1206
                if exceedsChunkSize {
×
1207
                        sort.Slice(channelChunk, func(i, j int) bool {
×
1208
                                id1 := channelChunk[i].ShortChannelID.ToUint64()
×
1209
                                id2 := channelChunk[j].ShortChannelID.ToUint64()
×
1210

×
1211
                                return id1 < id2
×
1212
                        })
×
1213
                }
1214
        }
1215

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

3✔
1220
        return sendReplyForChunk(
3✔
1221
                channelChunk, firstHeight, query.LastBlockHeight(), true,
3✔
1222
        )
3✔
1223
}
1224

1225
// replyShortChanIDs will be dispatched in response to a query by the remote
1226
// node for information concerning a set of short channel ID's. Our response
1227
// will be sent in a streaming chunked manner to ensure that we remain below
1228
// the current transport level message size.
1229
func (g *GossipSyncer) replyShortChanIDs(ctx context.Context,
1230
        query *lnwire.QueryShortChanIDs) error {
3✔
1231

3✔
1232
        // Before responding, we'll check to ensure that the remote peer is
3✔
1233
        // querying for the same chain that we're on. If not, we'll send back a
3✔
1234
        // response with a complete value of zero to indicate we're on a
3✔
1235
        // different chain.
3✔
1236
        if g.cfg.chainHash != query.ChainHash {
3✔
UNCOV
1237
                log.Warnf("Remote peer requested QueryShortChanIDs for "+
×
UNCOV
1238
                        "chain=%v, we're on chain=%v", query.ChainHash,
×
UNCOV
1239
                        g.cfg.chainHash)
×
UNCOV
1240

×
UNCOV
1241
                return g.cfg.sendToPeerSync(ctx, &lnwire.ReplyShortChanIDsEnd{
×
UNCOV
1242
                        ChainHash: query.ChainHash,
×
UNCOV
1243
                        Complete:  0,
×
UNCOV
1244
                })
×
UNCOV
1245
        }
×
1246

1247
        if len(query.ShortChanIDs) == 0 {
3✔
1248
                log.Infof("GossipSyncer(%x): ignoring query for blank short chan ID's",
×
1249
                        g.cfg.peerPub[:])
×
1250
                return nil
×
1251
        }
×
1252

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

3✔
1256
        // Now that we know we're on the same chain, we'll query the channel
3✔
1257
        // time series for the set of messages that we know of which satisfies
3✔
1258
        // the requirement of being a chan ann, chan update, or a node ann
3✔
1259
        // related to the set of queried channels.
3✔
1260
        replyMsgs, err := g.cfg.channelSeries.FetchChanAnns(
3✔
1261
                query.ChainHash, query.ShortChanIDs,
3✔
1262
        )
3✔
1263
        if err != nil {
3✔
1264
                return fmt.Errorf("unable to fetch chan anns for %v..., %w",
×
1265
                        query.ShortChanIDs[0].ToUint64(), err)
×
1266
        }
×
1267

1268
        // Reply with any messages related to those channel ID's, we'll write
1269
        // each one individually and synchronously to throttle the sends and
1270
        // perform buffering of responses in the syncer as opposed to the peer.
1271
        for _, msg := range replyMsgs {
6✔
1272
                err := g.cfg.sendToPeerSync(ctx, msg)
3✔
1273
                if err != nil {
3✔
1274
                        return err
×
1275
                }
×
1276
        }
1277

1278
        // Regardless of whether we had any messages to reply with, send over
1279
        // the sentinel message to signal that the stream has terminated.
1280
        return g.cfg.sendToPeerSync(ctx, &lnwire.ReplyShortChanIDsEnd{
3✔
1281
                ChainHash: query.ChainHash,
3✔
1282
                Complete:  1,
3✔
1283
        })
3✔
1284
}
1285

1286
// ApplyGossipFilter applies a gossiper filter sent by the remote node to the
1287
// state machine. Once applied, we'll ensure that we don't forward any messages
1288
// to the peer that aren't within the time range of the filter.
1289
func (g *GossipSyncer) ApplyGossipFilter(ctx context.Context,
1290
        filter *lnwire.GossipTimestampRange) error {
3✔
1291

3✔
1292
        g.Lock()
3✔
1293

3✔
1294
        g.remoteUpdateHorizon = filter
3✔
1295

3✔
1296
        startTime := time.Unix(int64(g.remoteUpdateHorizon.FirstTimestamp), 0)
3✔
1297
        endTime := startTime.Add(
3✔
1298
                time.Duration(g.remoteUpdateHorizon.TimestampRange) * time.Second,
3✔
1299
        )
3✔
1300

3✔
1301
        g.Unlock()
3✔
1302

3✔
1303
        // If requested, don't reply with historical gossip data when the remote
3✔
1304
        // peer sets their gossip timestamp range.
3✔
1305
        if g.cfg.ignoreHistoricalFilters {
3✔
UNCOV
1306
                return nil
×
UNCOV
1307
        }
×
1308

1309
        select {
3✔
1310
        case <-g.syncerSema:
3✔
1311
        case <-g.cg.Done():
×
1312
                return ErrGossipSyncerExiting
×
1313
        case <-ctx.Done():
×
1314
                return ctx.Err()
×
1315
        }
1316

1317
        // We don't put this in a defer because if the goroutine is launched,
1318
        // it needs to be called when the goroutine is stopped.
1319
        returnSema := func() {
6✔
1320
                g.syncerSema <- struct{}{}
3✔
1321
        }
3✔
1322

1323
        // Now that the remote peer has applied their filter, we'll query the
1324
        // database for all the messages that are beyond this filter.
1325
        newUpdatestoSend, err := g.cfg.channelSeries.UpdatesInHorizon(
3✔
1326
                g.cfg.chainHash, startTime, endTime,
3✔
1327
        )
3✔
1328
        if err != nil {
3✔
1329
                returnSema()
×
1330
                return err
×
1331
        }
×
1332

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

3✔
1337
        // If we don't have any to send, then we can return early.
3✔
1338
        if len(newUpdatestoSend) == 0 {
6✔
1339
                returnSema()
3✔
1340
                return nil
3✔
1341
        }
3✔
1342

1343
        // We'll conclude by launching a goroutine to send out any updates.
1344
        g.cg.WgAdd(1)
3✔
1345
        go func() {
6✔
1346
                defer g.cg.WgDone()
3✔
1347
                defer returnSema()
3✔
1348

3✔
1349
                for _, msg := range newUpdatestoSend {
6✔
1350
                        err := g.cfg.sendToPeerSync(ctx, msg)
3✔
1351
                        switch {
3✔
1352
                        case err == ErrGossipSyncerExiting:
×
1353
                                return
×
1354

1355
                        case err == lnpeer.ErrPeerExiting:
×
1356
                                return
×
1357

1358
                        case err != nil:
×
1359
                                log.Errorf("Unable to send message for "+
×
1360
                                        "peer catch up: %v", err)
×
1361
                        }
1362
                }
1363
        }()
1364

1365
        return nil
3✔
1366
}
1367

1368
// FilterGossipMsgs takes a set of gossip messages, and only send it to a peer
1369
// iff the message is within the bounds of their set gossip filter. If the peer
1370
// doesn't have a gossip filter set, then no messages will be forwarded.
1371
func (g *GossipSyncer) FilterGossipMsgs(ctx context.Context,
1372
        msgs ...msgWithSenders) {
3✔
1373

3✔
1374
        // If the peer doesn't have an update horizon set, then we won't send
3✔
1375
        // it any new update messages.
3✔
1376
        if g.remoteUpdateHorizon == nil {
6✔
1377
                log.Tracef("GossipSyncer(%x): skipped due to nil "+
3✔
1378
                        "remoteUpdateHorizon", g.cfg.peerPub[:])
3✔
1379
                return
3✔
1380
        }
3✔
1381

1382
        // If we've been signaled to exit, or are exiting, then we'll stop
1383
        // short.
1384
        select {
3✔
1385
        case <-g.cg.Done():
×
1386
                return
×
1387
        case <-ctx.Done():
×
1388
                return
×
1389
        default:
3✔
1390
        }
1391

1392
        // TODO(roasbeef): need to ensure that peer still online...send msg to
1393
        // gossiper on peer termination to signal peer disconnect?
1394

1395
        var err error
3✔
1396

3✔
1397
        // Before we filter out the messages, we'll construct an index over the
3✔
1398
        // set of channel announcements and channel updates. This will allow us
3✔
1399
        // to quickly check if we should forward a chan ann, based on the known
3✔
1400
        // channel updates for a channel.
3✔
1401
        chanUpdateIndex := make(
3✔
1402
                map[lnwire.ShortChannelID][]*lnwire.ChannelUpdate1,
3✔
1403
        )
3✔
1404
        for _, msg := range msgs {
6✔
1405
                chanUpdate, ok := msg.msg.(*lnwire.ChannelUpdate1)
3✔
1406
                if !ok {
6✔
1407
                        continue
3✔
1408
                }
1409

1410
                chanUpdateIndex[chanUpdate.ShortChannelID] = append(
3✔
1411
                        chanUpdateIndex[chanUpdate.ShortChannelID], chanUpdate,
3✔
1412
                )
3✔
1413
        }
1414

1415
        // We'll construct a helper function that we'll us below to determine
1416
        // if a given messages passes the gossip msg filter.
1417
        g.Lock()
3✔
1418
        startTime := time.Unix(int64(g.remoteUpdateHorizon.FirstTimestamp), 0)
3✔
1419
        endTime := startTime.Add(
3✔
1420
                time.Duration(g.remoteUpdateHorizon.TimestampRange) * time.Second,
3✔
1421
        )
3✔
1422
        g.Unlock()
3✔
1423

3✔
1424
        passesFilter := func(timeStamp uint32) bool {
6✔
1425
                t := time.Unix(int64(timeStamp), 0)
3✔
1426
                return t.Equal(startTime) ||
3✔
1427
                        (t.After(startTime) && t.Before(endTime))
3✔
1428
        }
3✔
1429

1430
        msgsToSend := make([]lnwire.Message, 0, len(msgs))
3✔
1431
        for _, msg := range msgs {
6✔
1432
                // If the target peer is the peer that sent us this message,
3✔
1433
                // then we'll exit early as we don't need to filter this
3✔
1434
                // message.
3✔
1435
                if _, ok := msg.senders[g.cfg.peerPub]; ok {
6✔
1436
                        continue
3✔
1437
                }
1438

1439
                switch msg := msg.msg.(type) {
3✔
1440

1441
                // For each channel announcement message, we'll only send this
1442
                // message if the channel updates for the channel are between
1443
                // our time range.
1444
                case *lnwire.ChannelAnnouncement1:
3✔
1445
                        // First, we'll check if the channel updates are in
3✔
1446
                        // this message batch.
3✔
1447
                        chanUpdates, ok := chanUpdateIndex[msg.ShortChannelID]
3✔
1448
                        if !ok {
6✔
1449
                                // If not, we'll attempt to query the database
3✔
1450
                                // to see if we know of the updates.
3✔
1451
                                chanUpdates, err = g.cfg.channelSeries.FetchChanUpdates(
3✔
1452
                                        g.cfg.chainHash, msg.ShortChannelID,
3✔
1453
                                )
3✔
1454
                                if err != nil {
3✔
1455
                                        log.Warnf("no channel updates found for "+
×
1456
                                                "short_chan_id=%v",
×
1457
                                                msg.ShortChannelID)
×
1458
                                        continue
×
1459
                                }
1460
                        }
1461

1462
                        for _, chanUpdate := range chanUpdates {
6✔
1463
                                if passesFilter(chanUpdate.Timestamp) {
6✔
1464
                                        msgsToSend = append(msgsToSend, msg)
3✔
1465
                                        break
3✔
1466
                                }
1467
                        }
1468

1469
                        if len(chanUpdates) == 0 {
6✔
1470
                                msgsToSend = append(msgsToSend, msg)
3✔
1471
                        }
3✔
1472

1473
                // For each channel update, we'll only send if it the timestamp
1474
                // is between our time range.
1475
                case *lnwire.ChannelUpdate1:
3✔
1476
                        if passesFilter(msg.Timestamp) {
6✔
1477
                                msgsToSend = append(msgsToSend, msg)
3✔
1478
                        }
3✔
1479

1480
                // Similarly, we only send node announcements if the update
1481
                // timestamp ifs between our set gossip filter time range.
1482
                case *lnwire.NodeAnnouncement:
3✔
1483
                        if passesFilter(msg.Timestamp) {
6✔
1484
                                msgsToSend = append(msgsToSend, msg)
3✔
1485
                        }
3✔
1486
                }
1487
        }
1488

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

3✔
1492
        if len(msgsToSend) == 0 {
6✔
1493
                return
3✔
1494
        }
3✔
1495

1496
        if err = g.cfg.sendToPeer(ctx, msgsToSend...); err != nil {
3✔
1497
                log.Errorf("unable to send gossip msgs: %v", err)
×
1498
        }
×
1499

1500
}
1501

1502
// ProcessQueryMsg is used by outside callers to pass new channel time series
1503
// queries to the internal processing goroutine.
1504
func (g *GossipSyncer) ProcessQueryMsg(msg lnwire.Message, peerQuit <-chan struct{}) error {
3✔
1505
        var msgChan chan lnwire.Message
3✔
1506
        switch msg.(type) {
3✔
1507
        case *lnwire.QueryChannelRange, *lnwire.QueryShortChanIDs:
3✔
1508
                msgChan = g.queryMsgs
3✔
1509

1510
        // Reply messages should only be expected in states where we're waiting
1511
        // for a reply.
1512
        case *lnwire.ReplyChannelRange, *lnwire.ReplyShortChanIDsEnd:
3✔
1513
                g.Lock()
3✔
1514
                syncState := g.syncState()
3✔
1515
                g.Unlock()
3✔
1516

3✔
1517
                if syncState != waitingQueryRangeReply &&
3✔
1518
                        syncState != waitingQueryChanReply {
3✔
UNCOV
1519

×
UNCOV
1520
                        return fmt.Errorf("unexpected msg %T received in "+
×
UNCOV
1521
                                "state %v", msg, syncState)
×
UNCOV
1522
                }
×
1523
                msgChan = g.gossipMsgs
3✔
1524

1525
        default:
×
1526
                msgChan = g.gossipMsgs
×
1527
        }
1528

1529
        select {
3✔
1530
        case msgChan <- msg:
3✔
1531
        case <-peerQuit:
×
1532
        case <-g.cg.Done():
×
1533
        }
1534

1535
        return nil
3✔
1536
}
1537

1538
// setSyncState sets the gossip syncer's state to the given state.
1539
func (g *GossipSyncer) setSyncState(state syncerState) {
3✔
1540
        atomic.StoreUint32(&g.state, uint32(state))
3✔
1541
}
3✔
1542

1543
// syncState returns the current syncerState of the target GossipSyncer.
1544
func (g *GossipSyncer) syncState() syncerState {
3✔
1545
        return syncerState(atomic.LoadUint32(&g.state))
3✔
1546
}
3✔
1547

1548
// ResetSyncedSignal returns a channel that will be closed in order to serve as
1549
// a signal for when the GossipSyncer has reached its chansSynced state.
1550
func (g *GossipSyncer) ResetSyncedSignal() chan struct{} {
3✔
1551
        g.Lock()
3✔
1552
        defer g.Unlock()
3✔
1553

3✔
1554
        syncedSignal := make(chan struct{})
3✔
1555

3✔
1556
        syncState := syncerState(atomic.LoadUint32(&g.state))
3✔
1557
        if syncState == chansSynced {
4✔
1558
                close(syncedSignal)
1✔
1559
                return syncedSignal
1✔
1560
        }
1✔
1561

1562
        g.syncedSignal = syncedSignal
3✔
1563
        return g.syncedSignal
3✔
1564
}
1565

1566
// ProcessSyncTransition sends a request to the gossip syncer to transition its
1567
// sync type to a new one.
1568
//
1569
// NOTE: This can only be done once the gossip syncer has reached its final
1570
// chansSynced state.
1571
func (g *GossipSyncer) ProcessSyncTransition(newSyncType SyncerType) error {
3✔
1572
        errChan := make(chan error, 1)
3✔
1573
        select {
3✔
1574
        case g.syncTransitionReqs <- &syncTransitionReq{
1575
                newSyncType: newSyncType,
1576
                errChan:     errChan,
1577
        }:
3✔
1578
        case <-time.After(syncTransitionTimeout):
×
1579
                return ErrSyncTransitionTimeout
×
1580
        case <-g.cg.Done():
×
1581
                return ErrGossipSyncerExiting
×
1582
        }
1583

1584
        select {
3✔
1585
        case err := <-errChan:
3✔
1586
                return err
3✔
1587
        case <-g.cg.Done():
×
1588
                return ErrGossipSyncerExiting
×
1589
        }
1590
}
1591

1592
// handleSyncTransition handles a new sync type transition request.
1593
//
1594
// NOTE: The gossip syncer might have another sync state as a result of this
1595
// transition.
1596
func (g *GossipSyncer) handleSyncTransition(ctx context.Context,
1597
        req *syncTransitionReq) error {
3✔
1598

3✔
1599
        // Return early from any NOP sync transitions.
3✔
1600
        syncType := g.SyncType()
3✔
1601
        if syncType == req.newSyncType {
3✔
1602
                return nil
×
1603
        }
×
1604

1605
        log.Debugf("GossipSyncer(%x): transitioning from %v to %v",
3✔
1606
                g.cfg.peerPub, syncType, req.newSyncType)
3✔
1607

3✔
1608
        var (
3✔
1609
                firstTimestamp time.Time
3✔
1610
                timestampRange uint32
3✔
1611
        )
3✔
1612

3✔
1613
        switch req.newSyncType {
3✔
1614
        // If an active sync has been requested, then we should resume receiving
1615
        // new graph updates from the remote peer.
1616
        case ActiveSync, PinnedSync:
3✔
1617
                firstTimestamp = time.Now()
3✔
1618
                timestampRange = math.MaxUint32
3✔
1619

1620
        // If a PassiveSync transition has been requested, then we should no
1621
        // longer receive any new updates from the remote peer. We can do this
1622
        // by setting our update horizon to a range in the past ensuring no
1623
        // graph updates match the timestamp range.
UNCOV
1624
        case PassiveSync:
×
UNCOV
1625
                firstTimestamp = zeroTimestamp
×
UNCOV
1626
                timestampRange = 0
×
1627

1628
        default:
×
1629
                return fmt.Errorf("unhandled sync transition %v",
×
1630
                        req.newSyncType)
×
1631
        }
1632

1633
        err := g.sendGossipTimestampRange(ctx, firstTimestamp, timestampRange)
3✔
1634
        if err != nil {
3✔
1635
                return fmt.Errorf("unable to send local update horizon: %w",
×
1636
                        err)
×
1637
        }
×
1638

1639
        g.setSyncType(req.newSyncType)
3✔
1640

3✔
1641
        return nil
3✔
1642
}
1643

1644
// setSyncType sets the gossip syncer's sync type to the given type.
1645
func (g *GossipSyncer) setSyncType(syncType SyncerType) {
3✔
1646
        atomic.StoreUint32(&g.syncType, uint32(syncType))
3✔
1647
}
3✔
1648

1649
// SyncType returns the current SyncerType of the target GossipSyncer.
1650
func (g *GossipSyncer) SyncType() SyncerType {
3✔
1651
        return SyncerType(atomic.LoadUint32(&g.syncType))
3✔
1652
}
3✔
1653

1654
// historicalSync sends a request to the gossip syncer to perofmr a historical
1655
// sync.
1656
//
1657
// NOTE: This can only be done once the gossip syncer has reached its final
1658
// chansSynced state.
1659
func (g *GossipSyncer) historicalSync() error {
3✔
1660
        done := make(chan struct{})
3✔
1661

3✔
1662
        select {
3✔
1663
        case g.historicalSyncReqs <- &historicalSyncReq{
1664
                doneChan: done,
1665
        }:
3✔
1666
        case <-time.After(syncTransitionTimeout):
×
1667
                return ErrSyncTransitionTimeout
×
1668
        case <-g.cg.Done():
×
1669
                return ErrGossiperShuttingDown
×
1670
        }
1671

1672
        select {
3✔
1673
        case <-done:
3✔
1674
                return nil
3✔
1675
        case <-g.cg.Done():
×
1676
                return ErrGossiperShuttingDown
×
1677
        }
1678
}
1679

1680
// handleHistoricalSync handles a request to the gossip syncer to perform a
1681
// historical sync.
1682
func (g *GossipSyncer) handleHistoricalSync(req *historicalSyncReq) {
3✔
1683
        // We'll go back to our initial syncingChans state in order to request
3✔
1684
        // the remote peer to give us all of the channel IDs they know of
3✔
1685
        // starting from the genesis block.
3✔
1686
        g.genHistoricalChanRangeQuery = true
3✔
1687
        g.setSyncState(syncingChans)
3✔
1688
        close(req.doneChan)
3✔
1689
}
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