-
Notifications
You must be signed in to change notification settings - Fork 211
/
syncer.go
650 lines (591 loc) · 18.9 KB
/
syncer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
package syncer
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
"golang.org/x/sync/errgroup"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/datastore"
"github.com/spacemeshos/go-spacemesh/events"
"github.com/spacemeshos/go-spacemesh/fetch"
"github.com/spacemeshos/go-spacemesh/log"
"github.com/spacemeshos/go-spacemesh/mesh"
"github.com/spacemeshos/go-spacemesh/p2p"
"github.com/spacemeshos/go-spacemesh/syncer/atxsync"
"github.com/spacemeshos/go-spacemesh/syncer/malsync"
"github.com/spacemeshos/go-spacemesh/system"
)
// Config is the config params for syncer.
type Config struct {
Interval time.Duration `mapstructure:"interval"`
EpochEndFraction float64 `mapstructure:"epochendfraction"`
HareDelayLayers uint32
SyncCertDistance uint32
// TallyVotesFrequency how often to tally votes during layers sync.
// Setting this to 0.25 will tally votes after downloading data for quarter of the epoch.
TallyVotesFrequency float64
MaxStaleDuration time.Duration `mapstructure:"maxstaleduration"`
Standalone bool
GossipDuration time.Duration `mapstructure:"gossipduration"`
DisableMeshAgreement bool `mapstructure:"disable-mesh-agreement"`
OutOfSyncThresholdLayers uint32 `mapstructure:"out-of-sync-threshold"`
AtxSync atxsync.Config `mapstructure:"atx-sync"`
MalSync malsync.Config `mapstructure:"malfeasance-sync"`
}
// DefaultConfig for the syncer.
func DefaultConfig() Config {
return Config{
Interval: 10 * time.Second,
EpochEndFraction: 0.5,
HareDelayLayers: 10,
SyncCertDistance: 10,
TallyVotesFrequency: 0.25,
MaxStaleDuration: time.Second,
GossipDuration: 15 * time.Second,
OutOfSyncThresholdLayers: 3,
AtxSync: atxsync.DefaultConfig(),
MalSync: malsync.DefaultConfig(),
}
}
type syncState uint32
const (
// notSynced is the state where the node is outOfSyncThreshold layers or more behind the current layer.
notSynced syncState = iota
// gossipSync is the state in which a node listens to at least one full layer of gossip before participating
// in the protocol. this is to protect the node from participating in the consensus without full information.
// for example, when a node wakes up in the middle of layer N, since it didn't receive all relevant messages and
// blocks of layer N, it shouldn't vote or produce blocks in layer N+1. it instead listens to gossip for all
// through layer N+1 and starts producing blocks and participates in hare committee in layer N+2.
gossipSync
// synced is the state where the node is in sync with its peers.
synced
)
func (s syncState) String() string {
switch s {
case notSynced:
return "notSynced"
case gossipSync:
return "gossipSync"
case synced:
return "synced"
default:
return "unknown"
}
}
var (
errHareInCharge = errors.New("hare in charge of layer")
errATXsNotSynced = errors.New("ATX not synced")
)
// Option is a type to configure a syncer.
type Option func(*Syncer)
// WithConfig ...
func WithConfig(c Config) Option {
return func(s *Syncer) {
s.cfg = c
}
}
// WithLogger ...
func WithLogger(l log.Log) Option {
return func(s *Syncer) {
s.logger = l
}
}
func withDataFetcher(d fetchLogic) Option {
return func(s *Syncer) {
s.dataFetcher = d
}
}
func withForkFinder(f forkFinder) Option {
return func(s *Syncer) {
s.forkFinder = f
}
}
// Syncer is responsible to keep the node in sync with the network.
type Syncer struct {
logger log.Log
cfg Config
cdb *datastore.CachedDB
atxsyncer atxSyncer
malsyncer malSyncer
ticker layerTicker
beacon system.BeaconGetter
mesh *mesh.Mesh
tortoise system.Tortoise
certHandler certHandler
dataFetcher fetchLogic
patrol layerPatrol
forkFinder forkFinder
syncOnce sync.Once
syncState atomic.Value
atxSyncState atomic.Value
isBusy atomic.Bool
// syncedTargetTime is used to signal at which time we can set this node to synced state
syncedTargetTime time.Time
lastLayerSynced atomic.Uint32
lastEpochSynced atomic.Uint32
stateErr atomic.Bool
// backgroundSync always runs one sync operation in the background.
backgroundSync struct {
epoch atomic.Uint32
eg errgroup.Group
cancel context.CancelFunc
}
// malSync runs malfeasant identity sync in the background
malSync struct {
started bool
eg errgroup.Group
}
// awaitATXSyncedCh is the list of subscribers' channels to notify when this node enters ATX synced state
awaitATXSyncedCh chan struct{}
eg errgroup.Group
stop context.CancelFunc
}
// NewSyncer creates a new Syncer instance.
func NewSyncer(
cdb *datastore.CachedDB,
ticker layerTicker,
beacon system.BeaconGetter,
mesh *mesh.Mesh,
tortoise system.Tortoise,
fetcher fetcher,
patrol layerPatrol,
ch certHandler,
atxSyncer atxSyncer,
malSyncer malSyncer,
opts ...Option,
) *Syncer {
s := &Syncer{
logger: log.NewNop(),
cfg: DefaultConfig(),
cdb: cdb,
atxsyncer: atxSyncer,
malsyncer: malSyncer,
ticker: ticker,
beacon: beacon,
mesh: mesh,
tortoise: tortoise,
certHandler: ch,
patrol: patrol,
awaitATXSyncedCh: make(chan struct{}),
}
for _, opt := range opts {
opt(s)
}
if s.dataFetcher == nil {
s.dataFetcher = NewDataFetch(mesh, fetcher, cdb, tortoise, s.logger)
}
if s.forkFinder == nil {
s.forkFinder = NewForkFinder(s.logger, cdb, fetcher, s.cfg.MaxStaleDuration)
}
s.syncState.Store(notSynced)
s.atxSyncState.Store(notSynced)
s.isBusy.Store(false)
s.lastLayerSynced.Store(s.mesh.LatestLayer().Uint32())
s.lastEpochSynced.Store(types.GetEffectiveGenesis().GetEpoch().Uint32() - 1)
return s
}
// Close stops the syncing process and the goroutines syncer spawns.
func (s *Syncer) Close() {
s.stop()
s.logger.With().Info("waiting for syncer goroutines to finish")
err := s.eg.Wait()
s.logger.With().Info("all syncer goroutines finished", log.Err(err))
}
// RegisterForATXSynced returns a channel for notification when the node enters ATX synced state.
func (s *Syncer) RegisterForATXSynced() <-chan struct{} {
return s.awaitATXSyncedCh
}
// ListenToGossip returns true if the node is listening to gossip for blocks/TXs data.
func (s *Syncer) ListenToGossip() bool {
return s.getSyncState() >= gossipSync
}
// ListenToATXGossip returns true if the node is listening to gossip for ATXs data.
func (s *Syncer) ListenToATXGossip() bool {
return s.getATXSyncState() == synced
}
// IsSynced returns true if the node is in synced state.
func (s *Syncer) IsSynced(ctx context.Context) bool {
return s.getSyncState() == synced
}
func (s *Syncer) IsBeaconSynced(epoch types.EpochID) bool {
_, err := s.beacon.GetBeacon(epoch)
return err == nil
}
// Start starts the main sync loop that tries to sync data for every SyncInterval.
func (s *Syncer) Start() {
s.syncOnce.Do(func() {
ctx, cancel := context.WithCancel(context.Background())
s.stop = cancel
s.logger.WithContext(ctx).Info("starting syncer loop")
s.eg.Go(func() error {
if s.ticker.CurrentLayer() <= types.GetEffectiveGenesis() {
s.setSyncState(ctx, synced)
}
for {
select {
case <-ctx.Done():
s.logger.WithContext(ctx).Info("stopping sync to shutdown")
return fmt.Errorf("shutdown context done: %w", ctx.Err())
case <-time.After(s.cfg.Interval):
ok := s.synchronize(ctx)
if ok {
runSuccess.Inc()
} else {
runFail.Inc()
}
}
}
})
s.logger.WithContext(ctx).Info("starting syncer layer processing loop")
s.eg.Go(func() error {
for {
select {
case <-ctx.Done():
return nil
case <-time.After(s.cfg.Interval):
if err := s.processLayers(ctx); err != nil {
sRunFail.Inc()
} else {
sRunSuccess.Inc()
}
s.forkFinder.Purge(false)
}
}
})
})
}
func (s *Syncer) setATXSynced() {
s.atxSyncState.Store(synced)
select {
case <-s.awaitATXSyncedCh:
default:
close(s.awaitATXSyncedCh)
atxSynced.Set(1)
}
}
func (s *Syncer) getATXSyncState() syncState {
return s.atxSyncState.Load().(syncState)
}
func (s *Syncer) getSyncState() syncState {
return s.syncState.Load().(syncState)
}
func (s *Syncer) setSyncState(ctx context.Context, newState syncState) {
oldState := s.syncState.Swap(newState).(syncState)
if oldState != newState {
s.logger.WithContext(ctx).With().Info("sync state change",
log.String("from state", oldState.String()),
log.String("to state", newState.String()),
log.Stringer("current", s.ticker.CurrentLayer()),
log.Stringer("last synced", s.getLastSyncedLayer()),
log.Stringer("latest", s.mesh.LatestLayer()),
log.Stringer("processed", s.mesh.ProcessedLayer()))
events.ReportNodeStatusUpdate()
}
switch newState {
case notSynced:
nodeNotSynced.Set(1)
nodeGossip.Set(0)
nodeSynced.Set(0)
case gossipSync:
nodeNotSynced.Set(0)
nodeGossip.Set(1)
nodeSynced.Set(0)
case synced:
nodeNotSynced.Set(0)
nodeGossip.Set(0)
nodeSynced.Set(1)
}
}
// setSyncerBusy returns false if the syncer is already running a sync process.
// otherwise it sets syncer to be busy and returns true.
func (s *Syncer) setSyncerBusy() bool {
return s.isBusy.CompareAndSwap(false, true)
}
func (s *Syncer) setSyncerIdle() {
s.isBusy.Store(false)
}
func (s *Syncer) setLastSyncedLayer(lid types.LayerID) {
s.lastLayerSynced.Store(lid.Uint32())
syncedLayer.Set(float64(lid))
}
func (s *Syncer) getLastSyncedLayer() types.LayerID {
return types.LayerID(s.lastLayerSynced.Load())
}
func (s *Syncer) setLastAtxEpoch(epoch types.EpochID) {
s.lastEpochSynced.Store(epoch.Uint32())
}
func (s *Syncer) lastAtxEpoch() types.EpochID {
return types.EpochID(s.lastEpochSynced.Load())
}
// synchronize sync data up to the currentLayer-1 and wait for the layers to be validated.
// it returns false if the data sync failed.
func (s *Syncer) synchronize(ctx context.Context) bool {
ctx = log.WithNewSessionID(ctx)
select {
case <-ctx.Done():
s.logger.WithContext(ctx).Warning("attempting to sync while shutting down")
return false
default:
}
// at most one synchronize process can run at any time
if !s.setSyncerBusy() {
s.logger.WithContext(ctx).Info("sync is already running, giving up")
return false
}
defer s.setSyncerIdle()
s.setStateBeforeSync(ctx)
if s.ticker.CurrentLayer().Uint32() == 0 {
return false
}
// no need to worry about race condition for s.run. only one instance of synchronize can run at a time
s.logger.WithContext(ctx).With().Debug("starting sync run",
log.Stringer("sync_state", s.getSyncState()),
log.Stringer("last_synced", s.getLastSyncedLayer()),
log.Stringer("current", s.ticker.CurrentLayer()),
log.Stringer("latest", s.mesh.LatestLayer()),
log.Stringer("in_state", s.mesh.LatestLayerInState()),
log.Stringer("processed", s.mesh.ProcessedLayer()),
)
// TODO
// https://github.com/spacemeshos/go-spacemesh/issues/3987
syncFunc := func() bool {
if s.cfg.Standalone {
s.setLastSyncedLayer(s.ticker.CurrentLayer().Sub(1))
s.setATXSynced()
return true
}
// check that we have any peers
if len(s.dataFetcher.SelectBestShuffled(1)) == 0 {
return false
}
if err := s.syncAtx(ctx); err != nil {
if !errors.Is(err, context.Canceled) {
s.logger.With().Error("failed to sync atxs", log.Context(ctx), log.Err(err))
}
return false
}
if s.ticker.CurrentLayer() <= types.GetEffectiveGenesis() {
return true
}
// always sync to currentLayer-1 to reduce race with gossip and hare/tortoise
for layer := s.getLastSyncedLayer().Add(1); layer.Before(s.ticker.CurrentLayer()); layer = layer.Add(1) {
if err := s.syncLayer(ctx, layer); err != nil {
batchError := &fetch.BatchError{}
if errors.As(err, &batchError) && batchError.Ignore() {
s.logger.With().
Info("remaining ballots are rejected in the layer", log.Context(ctx), log.Err(err), layer)
} else {
if !errors.Is(err, context.Canceled) {
// BatchError spams too much, in case of no progress enable debug mode for sync
s.logger.With().
Debug("failed to sync layer", log.Context(ctx), log.Err(err), layer)
}
return false
}
}
s.setLastSyncedLayer(layer)
}
s.logger.WithContext(ctx).With().Debug("data is synced",
log.Stringer("current", s.ticker.CurrentLayer()),
log.Stringer("latest", s.mesh.LatestLayer()),
log.Stringer("last_synced", s.getLastSyncedLayer()))
return true
}
success := syncFunc()
s.setStateAfterSync(ctx, success)
s.logger.WithContext(ctx).With().Debug("finished sync run",
log.Bool("success", success),
log.Stringer("sync_state", s.getSyncState()),
log.Stringer("last_synced", s.getLastSyncedLayer()),
log.Stringer("current", s.ticker.CurrentLayer()),
log.Stringer("latest", s.mesh.LatestLayer()),
log.Stringer("in_state", s.mesh.LatestLayerInState()),
log.Stringer("processed", s.mesh.ProcessedLayer()),
)
return success
}
func (s *Syncer) syncAtx(ctx context.Context) error {
current := s.ticker.CurrentLayer()
// on startup always download all activations that were published before current epoch
if !s.ListenToATXGossip() {
s.logger.With().Debug("syncing atx from genesis", log.Context(ctx), current, s.lastAtxEpoch())
for epoch := s.lastAtxEpoch() + 1; epoch < current.GetEpoch(); epoch++ {
if err := s.fetchATXsForEpoch(ctx, epoch, false); err != nil {
return err
}
}
s.logger.With().Debug("atxs synced to epoch", log.Context(ctx), s.lastAtxEpoch())
// FIXME https://github.com/spacemeshos/go-spacemesh/issues/3987
s.logger.With().Info("syncing malicious proofs", log.Context(ctx))
if err := s.syncMalfeasance(ctx, current.GetEpoch()); err != nil {
return err
}
s.logger.With().Info("malicious IDs synced", log.Context(ctx))
s.setATXSynced()
}
publish := current.GetEpoch()
if publish == 0 {
return nil // nothing to sync in epoch 0
}
// if we are not advanced enough sync previous epoch, otherwise start syncing activations published in this epoch
if current.OrdinalInEpoch() <= uint32(float64(types.GetLayersPerEpoch())*s.cfg.EpochEndFraction) {
publish -= 1
}
if epoch := s.backgroundSync.epoch.Load(); epoch != 0 && epoch != publish.Uint32() {
s.backgroundSync.cancel()
s.backgroundSync.eg.Wait()
s.backgroundSync.epoch.Store(0)
}
if s.backgroundSync.epoch.Load() == 0 && publish.Uint32() != 0 {
s.logger.With().Debug("download atx for epoch in background", publish, log.Context(ctx))
s.backgroundSync.epoch.Store(publish.Uint32())
ctx, cancel := context.WithCancel(ctx)
s.backgroundSync.cancel = cancel
s.backgroundSync.eg.Go(func() error {
err := s.fetchATXsForEpoch(ctx, publish, true)
if err == nil {
return nil
}
if !errors.Is(err, context.Canceled) {
s.logger.With().
Warning("background atx sync failed", log.Context(ctx), publish.Field(), log.Err(err))
} else {
s.logger.With().Debug("background atx sync stopped", log.Context(ctx), publish.Field())
}
s.backgroundSync.epoch.Store(0)
return err
})
}
if !s.malSync.started {
s.malSync.started = true
s.malSync.eg.Go(func() error {
select {
case <-ctx.Done():
return nil
case <-s.awaitATXSyncedCh:
err := s.malsyncer.DownloadLoop(ctx)
if err != nil && !errors.Is(err, context.Canceled) {
s.logger.WithContext(ctx).Error("malfeasance sync failed", log.Err(err))
}
return nil
}
})
}
return nil
}
func isTooFarBehind(
ctx context.Context,
logger log.Log,
current, lastSynced types.LayerID,
outOfSyncThreshold uint32,
) bool {
if current.After(lastSynced) && current.Difference(lastSynced) >= outOfSyncThreshold {
logger.WithContext(ctx).With().Info("node is too far behind",
log.Stringer("current", current),
log.Stringer("last synced", lastSynced),
log.Uint32("behind threshold", outOfSyncThreshold))
return true
}
return false
}
func (s *Syncer) setStateBeforeSync(ctx context.Context) {
current := s.ticker.CurrentLayer()
if s.ticker.CurrentLayer() <= types.GetEffectiveGenesis() {
s.setSyncState(ctx, synced)
if current.GetEpoch() == 0 {
s.setATXSynced()
}
return
}
if isTooFarBehind(
ctx,
s.logger,
current,
s.getLastSyncedLayer(),
s.cfg.OutOfSyncThresholdLayers,
) {
s.setSyncState(ctx, notSynced)
}
}
func (s *Syncer) dataSynced() bool {
current := s.ticker.CurrentLayer()
return current.Uint32() <= 1 || !s.getLastSyncedLayer().Before(current.Sub(1))
}
func (s *Syncer) setStateAfterSync(ctx context.Context, success bool) {
currSyncState := s.getSyncState()
current := s.ticker.CurrentLayer()
// for the gossipSync/notSynced states, we check if the mesh state is on target before we advance sync state.
// but for the synced state, we don't check the mesh state because gossip+hare+tortoise are in charge of
// advancing processed/verified layers. syncer is just auxiliary that fetches data in case of a temporary
// network outage.
switch currSyncState {
case synced:
if !success &&
isTooFarBehind(
ctx,
s.logger,
current,
s.getLastSyncedLayer(),
s.cfg.OutOfSyncThresholdLayers,
) {
s.setSyncState(ctx, notSynced)
}
case gossipSync:
if !success || !s.dataSynced() || !s.stateSynced() {
// push out the target synced layer
s.syncedTargetTime = time.Now().Add(s.cfg.GossipDuration)
s.logger.With().Info("extending gossip sync",
log.Bool("success", success),
log.Bool("data", s.dataSynced()),
log.Bool("state", s.stateSynced()),
)
break
}
// if we have gossip-synced long enough, we are ready to participate in consensus
if !time.Now().Before(s.syncedTargetTime) {
s.setSyncState(ctx, synced)
}
case notSynced:
if success && s.dataSynced() && s.stateSynced() {
// wait till s.ticker.GetCurrentLayer() + numGossipSyncLayers to participate in consensus
s.setSyncState(ctx, gossipSync)
s.syncedTargetTime = time.Now().Add(s.cfg.GossipDuration)
}
}
}
func (s *Syncer) syncMalfeasance(ctx context.Context, epoch types.EpochID) error {
epochStart := s.ticker.LayerToTime(epoch.FirstLayer())
epochEnd := s.ticker.LayerToTime(epoch.Add(1).FirstLayer())
if err := s.malsyncer.EnsureInSync(ctx, epochStart, epochEnd); err != nil {
return fmt.Errorf("syncing malfeasance proof: %w", err)
}
return nil
}
func (s *Syncer) syncLayer(ctx context.Context, layerID types.LayerID, peers ...p2p.Peer) error {
if err := s.dataFetcher.PollLayerData(ctx, layerID, peers...); err != nil {
return err
}
dataLayer.Set(float64(layerID))
return nil
}
// fetching ATXs published the specified epoch.
func (s *Syncer) fetchATXsForEpoch(ctx context.Context, publish types.EpochID, background bool) error {
target := publish + 1
if background {
target++
}
downloadUntil := s.ticker.LayerToTime(target.FirstLayer())
if err := s.atxsyncer.Download(ctx, publish, downloadUntil); err != nil {
return err
}
s.setLastAtxEpoch(publish)
atxEpoch.Set(float64(publish))
return nil
}
// waitBackgroundSync is a helper to wait for the background sync to finish.
func (s *Syncer) waitBackgroundSync() {
s.backgroundSync.eg.Wait()
}