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

lightningnetwork / lnd / 16034820197

02 Jul 2025 08:11PM UTC coverage: 57.761% (-9.8%) from 67.589%
16034820197

Pull #10018

github

web-flow
Merge a11ccc22c into 8a0341419
Pull Request #10018: Refactor link's long methods

415 of 786 new or added lines in 1 file covered. (52.8%)

28401 existing lines in 456 files now uncovered.

98450 of 170445 relevant lines covered (57.76%)

1.79 hits per line

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

74.05
/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(ctx 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(
3✔
974
                ctx, g.cfg.chainHash,
3✔
975
        )
3✔
976
        if err != nil {
3✔
977
                return nil, err
×
978
        }
×
979

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

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

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

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

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

1020
        g.curQueryRangeMsg = query
3✔
1021

3✔
1022
        return query, nil
3✔
1023
}
1024

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

3✔
1030
        switch msg := msg.(type) {
3✔
1031

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1124
                        if !withTimestamps {
3✔
UNCOV
1125
                                continue
×
1126
                        }
1127

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

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

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

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

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

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

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

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

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

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

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

×
1213
                                return id1 < id2
×
1214
                        })
×
1215
                }
1216
        }
1217

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

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

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

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

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

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

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

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

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

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

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

3✔
1294
        g.Lock()
3✔
1295

3✔
1296
        g.remoteUpdateHorizon = filter
3✔
1297

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

3✔
1303
        g.Unlock()
3✔
1304

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

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

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

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

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

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

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

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

1357
                        case err == lnpeer.ErrPeerExiting:
×
1358
                                return
×
1359

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

1367
        return nil
3✔
1368
}
1369

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

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

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

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

1397
        var err error
3✔
1398

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

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

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

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

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

1441
                switch msg := msg.msg.(type) {
3✔
1442

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

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

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

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

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

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

3✔
1494
        if len(msgsToSend) == 0 {
6✔
1495
                return
3✔
1496
        }
3✔
1497

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

1502
}
1503

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

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

3✔
1519
                if syncState != waitingQueryRangeReply &&
3✔
1520
                        syncState != waitingQueryChanReply {
3✔
UNCOV
1521

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

1527
        default:
×
1528
                msgChan = g.gossipMsgs
×
1529
        }
1530

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

1537
        return nil
3✔
1538
}
1539

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

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

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

3✔
1556
        syncedSignal := make(chan struct{})
3✔
1557

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

1564
        g.syncedSignal = syncedSignal
3✔
1565
        return g.syncedSignal
3✔
1566
}
1567

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

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

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

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

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

3✔
1610
        var (
3✔
1611
                firstTimestamp time.Time
3✔
1612
                timestampRange uint32
3✔
1613
        )
3✔
1614

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

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

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

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

1641
        g.setSyncType(req.newSyncType)
3✔
1642

3✔
1643
        return nil
3✔
1644
}
1645

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

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

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

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

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

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