-
Notifications
You must be signed in to change notification settings - Fork 198
/
trigger.go
1130 lines (933 loc) · 33.2 KB
/
trigger.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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package shardchain
import (
"bytes"
"context"
"fmt"
"math"
"sort"
"sync"
"time"
"github.com/ElrondNetwork/elrond-go-core/core"
"github.com/ElrondNetwork/elrond-go-core/core/atomic"
"github.com/ElrondNetwork/elrond-go-core/core/check"
"github.com/ElrondNetwork/elrond-go-core/core/closing"
"github.com/ElrondNetwork/elrond-go-core/data"
"github.com/ElrondNetwork/elrond-go-core/data/block"
"github.com/ElrondNetwork/elrond-go-core/data/typeConverters"
"github.com/ElrondNetwork/elrond-go-core/display"
"github.com/ElrondNetwork/elrond-go-core/hashing"
"github.com/ElrondNetwork/elrond-go-core/marshal"
"github.com/ElrondNetwork/elrond-go-logger"
"github.com/ElrondNetwork/elrond-go/common"
"github.com/ElrondNetwork/elrond-go/dataRetriever"
"github.com/ElrondNetwork/elrond-go/epochStart"
"github.com/ElrondNetwork/elrond-go/errors"
"github.com/ElrondNetwork/elrond-go/process"
"github.com/ElrondNetwork/elrond-go/storage"
)
var log = logger.GetOrCreate("epochStart/shardchain")
var _ dataRetriever.EpochHandler = (*trigger)(nil)
var _ epochStart.TriggerHandler = (*trigger)(nil)
var _ process.EpochStartTriggerHandler = (*trigger)(nil)
var _ process.EpochBootstrapper = (*trigger)(nil)
var _ closing.Closer = (*trigger)(nil)
// sleepTime defines the time in milliseconds between each iteration made in requestMissingMiniBlocks method
const sleepTime = 1 * time.Second
// ArgsShardEpochStartTrigger struct { defines the arguments needed for new start of epoch trigger
type ArgsShardEpochStartTrigger struct {
Marshalizer marshal.Marshalizer
Hasher hashing.Hasher
HeaderValidator epochStart.HeaderValidator
Uint64Converter typeConverters.Uint64ByteSliceConverter
DataPool dataRetriever.PoolsHolder
Storage dataRetriever.StorageService
RequestHandler epochStart.RequestHandler
EpochStartNotifier epochStart.Notifier
PeerMiniBlocksSyncer process.ValidatorInfoSyncer
RoundHandler process.RoundHandler
AppStatusHandler core.AppStatusHandler
EnableEpochsHandler common.EnableEpochsHandler
Epoch uint32
Validity uint64
Finality uint64
}
type trigger struct {
currentRoundIndex int64
epochStartRound uint64
epochMetaBlockHash []byte
triggerStateKey []byte
finality uint64
validity uint64
epochFinalityAttestingRound uint64
epochStartShardHeader data.HeaderHandler
epochStartMeta data.HeaderHandler
mutTrigger sync.RWMutex
mapHashHdr map[string]data.HeaderHandler
mapNonceHashes map[uint64][]string
mapEpochStartHdrs map[string]data.HeaderHandler
mapFinalizedEpochs map[uint32]string
headersPool dataRetriever.HeadersPool
miniBlocksPool storage.Cacher
validatorInfoPool dataRetriever.ShardedDataCacherNotifier
currentEpochValidatorInfoPool epochStart.ValidatorInfoCacher
shardHdrStorage storage.Storer
metaHdrStorage storage.Storer
triggerStorage storage.Storer
metaNonceHdrStorage storage.Storer
uint64Converter typeConverters.Uint64ByteSliceConverter
marshaller marshal.Marshalizer
hasher hashing.Hasher
headerValidator epochStart.HeaderValidator
requestHandler epochStart.RequestHandler
epochStartNotifier epochStart.Notifier
roundHandler process.RoundHandler
epoch uint32
metaEpoch uint32
newEpochHdrReceived bool
isEpochStart bool
requestedFinalityAttestingBlock atomic.Flag
peerMiniBlocksSyncer process.ValidatorInfoSyncer
appStatusHandler core.AppStatusHandler
enableEpochsHandler common.EnableEpochsHandler
mapMissingMiniBlocks map[string]uint32
mapMissingValidatorsInfo map[string]uint32
mutMissingMiniBlocks sync.RWMutex
mutMissingValidatorsInfo sync.RWMutex
cancelFunc func()
}
type metaInfo struct {
hdr data.HeaderHandler
hash string
}
type metaInfoSlice []*metaInfo
// Len will return the length of the metaInfoSlice
func (m metaInfoSlice) Len() int { return len(m) }
// Swap will interchange the objects on input indexes
func (m metaInfoSlice) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
// Less will return true if object on index i should appear before object in index j
// Sorting of headers should be by epoch, by nonce and by hash in ascending order
// this will ensure that in case of equality for epoch, the metaHdr with higher nonce will
// be processed last - that is the correct one - as it finalizes the previous nonce
func (m metaInfoSlice) Less(i, j int) bool {
if m[i].hdr.GetEpoch() == m[j].hdr.GetEpoch() {
if m[i].hdr.GetNonce() == m[j].hdr.GetNonce() {
return m[i].hash < m[j].hash
}
return m[i].hdr.GetNonce() < m[j].hdr.GetNonce()
}
return m[i].hdr.GetEpoch() < m[j].hdr.GetEpoch()
}
// NewEpochStartTrigger creates a trigger to signal start of epoch
func NewEpochStartTrigger(args *ArgsShardEpochStartTrigger) (*trigger, error) {
if args == nil {
return nil, epochStart.ErrNilArgsNewShardEpochStartTrigger
}
if check.IfNil(args.Hasher) {
return nil, epochStart.ErrNilHasher
}
if check.IfNil(args.Marshalizer) {
return nil, epochStart.ErrNilMarshalizer
}
if check.IfNil(args.HeaderValidator) {
return nil, epochStart.ErrNilHeaderValidator
}
if check.IfNil(args.DataPool) {
return nil, epochStart.ErrNilDataPoolsHolder
}
if check.IfNil(args.Storage) {
return nil, epochStart.ErrNilStorageService
}
if check.IfNil(args.RequestHandler) {
return nil, epochStart.ErrNilRequestHandler
}
if check.IfNil(args.DataPool.Headers()) {
return nil, epochStart.ErrNilMetaBlocksPool
}
if check.IfNil(args.DataPool.MiniBlocks()) {
return nil, epochStart.ErrNilMiniBlockPool
}
if check.IfNil(args.DataPool.ValidatorsInfo()) {
return nil, epochStart.ErrNilValidatorsInfoPool
}
if check.IfNil(args.DataPool.CurrentEpochValidatorInfo()) {
return nil, epochStart.ErrNilCurrentEpochValidatorsInfoPool
}
if check.IfNil(args.PeerMiniBlocksSyncer) {
return nil, epochStart.ErrNilValidatorInfoProcessor
}
if check.IfNil(args.Uint64Converter) {
return nil, epochStart.ErrNilUint64Converter
}
if check.IfNil(args.EpochStartNotifier) {
return nil, epochStart.ErrNilEpochStartNotifier
}
if check.IfNil(args.RoundHandler) {
return nil, epochStart.ErrNilRoundHandler
}
if check.IfNil(args.AppStatusHandler) {
return nil, epochStart.ErrNilStatusHandler
}
if check.IfNil(args.EnableEpochsHandler) {
return nil, epochStart.ErrNilEnableEpochsHandler
}
metaHdrStorage, err := args.Storage.GetStorer(dataRetriever.MetaBlockUnit)
if err != nil {
return nil, err
}
triggerStorage, err := args.Storage.GetStorer(dataRetriever.BootstrapUnit)
if err != nil {
return nil, err
}
metaHdrNoncesStorage, err := args.Storage.GetStorer(dataRetriever.MetaHdrNonceHashDataUnit)
if err != nil {
return nil, err
}
shardHdrStorage, err := args.Storage.GetStorer(dataRetriever.BlockHeaderUnit)
if err != nil {
return nil, err
}
trigggerStateKey := common.TriggerRegistryInitialKeyPrefix + fmt.Sprintf("%d", args.Epoch)
t := &trigger{
triggerStateKey: []byte(trigggerStateKey),
epoch: args.Epoch,
metaEpoch: args.Epoch,
currentRoundIndex: 0,
epochStartRound: 0,
epochFinalityAttestingRound: 0,
isEpochStart: false,
validity: args.Validity,
finality: args.Finality,
newEpochHdrReceived: false,
mutTrigger: sync.RWMutex{},
mapHashHdr: make(map[string]data.HeaderHandler),
mapNonceHashes: make(map[uint64][]string),
mapEpochStartHdrs: make(map[string]data.HeaderHandler),
mapFinalizedEpochs: make(map[uint32]string),
headersPool: args.DataPool.Headers(),
miniBlocksPool: args.DataPool.MiniBlocks(),
validatorInfoPool: args.DataPool.ValidatorsInfo(),
currentEpochValidatorInfoPool: args.DataPool.CurrentEpochValidatorInfo(),
metaHdrStorage: metaHdrStorage,
shardHdrStorage: shardHdrStorage,
triggerStorage: triggerStorage,
metaNonceHdrStorage: metaHdrNoncesStorage,
uint64Converter: args.Uint64Converter,
marshaller: args.Marshalizer,
hasher: args.Hasher,
headerValidator: args.HeaderValidator,
requestHandler: args.RequestHandler,
epochMetaBlockHash: nil,
epochStartNotifier: args.EpochStartNotifier,
epochStartMeta: &block.MetaBlock{},
epochStartShardHeader: &block.Header{},
peerMiniBlocksSyncer: args.PeerMiniBlocksSyncer,
appStatusHandler: args.AppStatusHandler,
roundHandler: args.RoundHandler,
enableEpochsHandler: args.EnableEpochsHandler,
}
t.headersPool.RegisterHandler(t.receivedMetaBlock)
err = t.saveState(t.triggerStateKey)
if err != nil {
return nil, err
}
t.mapMissingMiniBlocks = make(map[string]uint32)
t.mapMissingValidatorsInfo = make(map[string]uint32)
var ctx context.Context
ctx, t.cancelFunc = context.WithCancel(context.Background())
go t.requestMissingMiniBlocks(ctx)
go t.requestMissingValidatorsInfo(ctx)
return t, nil
}
func (t *trigger) clearMissingMiniBlocksMap(epoch uint32) {
t.mutMissingMiniBlocks.Lock()
defer t.mutMissingMiniBlocks.Unlock()
for hash, epochOfMissingMb := range t.mapMissingMiniBlocks {
if epochOfMissingMb <= epoch {
delete(t.mapMissingMiniBlocks, hash)
}
}
}
func (t *trigger) clearMissingValidatorsInfoMap(epoch uint32) {
t.mutMissingValidatorsInfo.Lock()
defer t.mutMissingValidatorsInfo.Unlock()
for hash, epochOfMissingValidatorInfo := range t.mapMissingValidatorsInfo {
if epochOfMissingValidatorInfo <= epoch {
delete(t.mapMissingValidatorsInfo, hash)
}
}
}
func (t *trigger) requestMissingMiniBlocks(ctx context.Context) {
timer := time.NewTimer(sleepTime)
defer timer.Stop()
for {
timer.Reset(sleepTime)
select {
case <-ctx.Done():
log.Debug("requestMissingMiniBlocks: trigger's go routine is stopping...")
return
case <-timer.C:
}
t.mutMissingMiniBlocks.RLock()
if len(t.mapMissingMiniBlocks) == 0 {
t.mutMissingMiniBlocks.RUnlock()
continue
}
missingMiniBlocks := make([][]byte, 0, len(t.mapMissingMiniBlocks))
for hash, epoch := range t.mapMissingMiniBlocks {
missingMiniBlocks = append(missingMiniBlocks, []byte(hash))
log.Debug("trigger.requestMissingMiniBlocks", "epoch", epoch, "hash", []byte(hash))
}
t.mutMissingMiniBlocks.RUnlock()
go t.requestHandler.RequestMiniBlocks(core.MetachainShardId, missingMiniBlocks)
timer.Reset(waitTime)
select {
case <-ctx.Done():
log.Debug("requestMissingMiniBlocks: trigger's go routine is stopping...")
return
case <-timer.C:
}
t.updateMissingMiniBlocks()
}
}
func (t *trigger) requestMissingValidatorsInfo(ctx context.Context) {
timer := time.NewTimer(sleepTime)
defer timer.Stop()
for {
timer.Reset(sleepTime)
select {
case <-ctx.Done():
log.Debug("requestMissingValidatorsInfo: trigger's go routine is stopping...")
return
case <-timer.C:
}
t.mutMissingValidatorsInfo.RLock()
if len(t.mapMissingValidatorsInfo) == 0 {
t.mutMissingValidatorsInfo.RUnlock()
continue
}
missingValidatorsInfo := make([][]byte, 0, len(t.mapMissingValidatorsInfo))
for hash, epoch := range t.mapMissingValidatorsInfo {
missingValidatorsInfo = append(missingValidatorsInfo, []byte(hash))
log.Debug("trigger.requestMissingValidatorsInfo", "epoch", epoch, "hash", []byte(hash))
}
t.mutMissingValidatorsInfo.RUnlock()
go t.requestHandler.RequestValidatorsInfo(missingValidatorsInfo)
timer.Reset(waitTime)
select {
case <-ctx.Done():
log.Debug("requestMissingValidatorsInfo: trigger's go routine is stopping...")
return
case <-timer.C:
}
t.updateMissingValidatorsInfo()
}
}
func (t *trigger) updateMissingMiniBlocks() {
t.mutMissingMiniBlocks.Lock()
for hash := range t.mapMissingMiniBlocks {
if t.miniBlocksPool.Has([]byte(hash)) {
delete(t.mapMissingMiniBlocks, hash)
}
}
numMissingMiniBlocks := len(t.mapMissingMiniBlocks)
t.mutMissingMiniBlocks.Unlock()
if numMissingMiniBlocks == 0 {
log.Debug("trigger.updateMissingMiniBlocks -> updateTriggerFromMeta")
t.mutTrigger.Lock()
t.updateTriggerFromMeta()
t.mutTrigger.Unlock()
}
}
func (t *trigger) updateMissingValidatorsInfo() {
t.mutMissingValidatorsInfo.Lock()
for hash := range t.mapMissingValidatorsInfo {
_, isValidatorInfoFound := t.validatorInfoPool.SearchFirstData([]byte(hash))
if isValidatorInfoFound {
delete(t.mapMissingValidatorsInfo, hash)
}
}
numMissingValidatorsInfo := len(t.mapMissingValidatorsInfo)
t.mutMissingValidatorsInfo.Unlock()
if numMissingValidatorsInfo == 0 {
log.Debug("trigger.updateMissingValidatorsInfo -> updateTriggerFromMeta")
t.mutTrigger.Lock()
t.updateTriggerFromMeta()
t.mutTrigger.Unlock()
}
}
// IsEpochStart returns true if conditions are fulfilled for start of epoch
func (t *trigger) IsEpochStart() bool {
t.mutTrigger.RLock()
defer t.mutTrigger.RUnlock()
return t.isEpochStart
}
// Epoch returns the current epoch number
func (t *trigger) Epoch() uint32 {
t.mutTrigger.RLock()
defer t.mutTrigger.RUnlock()
return t.epoch
}
// MetaEpoch returns the highest finalized meta epoch number
func (t *trigger) MetaEpoch() uint32 {
t.mutTrigger.RLock()
defer t.mutTrigger.RUnlock()
return t.metaEpoch
}
// EpochStartRound returns the start round of the current epoch
func (t *trigger) EpochStartRound() uint64 {
t.mutTrigger.RLock()
defer t.mutTrigger.RUnlock()
return t.epochStartRound
}
// EpochFinalityAttestingRound returns the round when epoch start block was finalized
func (t *trigger) EpochFinalityAttestingRound() uint64 {
t.mutTrigger.Lock()
defer t.mutTrigger.Unlock()
return t.epochFinalityAttestingRound
}
// ForceEpochStart does nothing in this implementation
func (t *trigger) ForceEpochStart(_ uint64) {
}
// RequestEpochStartIfNeeded request the needed epoch start block if metablock with new epoch was received
func (t *trigger) RequestEpochStartIfNeeded(interceptedHeader data.HeaderHandler) {
if interceptedHeader.IsStartOfEpochBlock() {
return
}
if interceptedHeader.GetEpoch() <= t.Epoch() {
return
}
_, ok := interceptedHeader.(*block.MetaBlock)
if !ok {
return
}
t.mutTrigger.Lock()
defer t.mutTrigger.Unlock()
found := false
for _, header := range t.mapEpochStartHdrs {
if header.GetEpoch() >= interceptedHeader.GetEpoch() {
found = true
break
}
}
if !found {
t.requestHandler.RequestStartOfEpochMetaBlock(interceptedHeader.GetEpoch())
}
}
func (t *trigger) changeEpochFinalityAttestingRoundIfNeeded(
metaHdr *block.MetaBlock,
receivedHash []byte,
) {
hash := t.mapFinalizedEpochs[metaHdr.Epoch]
epochStartMetaHdr := t.mapEpochStartHdrs[hash]
if check.IfNil(epochStartMetaHdr) {
return
}
isHeaderOnTopOfFinalityAttestingRound := metaHdr.Nonce == epochStartMetaHdr.GetNonce()+t.finality+1
if isHeaderOnTopOfFinalityAttestingRound {
metaHdrWithFinalityAttestingRound, err := t.getHeaderWithNonceAndHash(epochStartMetaHdr.GetNonce()+t.finality, metaHdr.PrevHash)
if err != nil {
log.Debug("searched metaHeader was not found")
_ = t.requestedFinalityAttestingBlock.SetReturningPrevious()
return
}
t.epochFinalityAttestingRound = metaHdrWithFinalityAttestingRound.GetRound()
return
}
isFinalityAttestingBlock := metaHdr.Nonce == epochStartMetaHdr.GetNonce()+t.finality
if !isFinalityAttestingBlock {
return
}
err := t.headerValidator.IsHeaderConstructionValid(metaHdr, t.epochStartMeta)
if err != nil {
return
}
if t.requestedFinalityAttestingBlock.IsSet() {
_, err = t.getHeaderWithNonceAndPrevHash(metaHdr.Nonce+1, receivedHash)
if err != nil {
return
}
t.epochFinalityAttestingRound = metaHdr.GetRound()
t.requestedFinalityAttestingBlock.Reset()
return
}
if metaHdr.GetRound() >= t.epochFinalityAttestingRound {
return
}
t.epochFinalityAttestingRound = metaHdr.GetRound()
}
// receivedMetaBlock is a callback function when a new metablock was received
// upon receiving checks if trigger can be updated
func (t *trigger) receivedMetaBlock(headerHandler data.HeaderHandler, metaBlockHash []byte) {
t.mutTrigger.Lock()
defer t.mutTrigger.Unlock()
metaHdr, ok := headerHandler.(*block.MetaBlock)
if !ok {
return
}
if !t.isPreviousEpochStartMetaBlock(metaHdr, metaBlockHash) {
_, ok = t.mapFinalizedEpochs[metaHdr.Epoch]
if t.metaEpoch == headerHandler.GetEpoch() && ok {
t.changeEpochFinalityAttestingRoundIfNeeded(metaHdr, metaBlockHash)
return
}
}
if !t.newEpochHdrReceived && !metaHdr.IsStartOfEpochBlock() {
return
}
isMetaStartOfEpochForCurrentEpoch := metaHdr.Epoch == t.epoch && metaHdr.IsStartOfEpochBlock()
if isMetaStartOfEpochForCurrentEpoch {
return
}
if _, ok = t.mapHashHdr[string(metaBlockHash)]; ok {
return
}
if _, ok = t.mapEpochStartHdrs[string(metaBlockHash)]; ok {
return
}
if metaHdr.IsStartOfEpochBlock() {
t.newEpochHdrReceived = true
t.mapEpochStartHdrs[string(metaBlockHash)] = metaHdr
// waiting for late broadcast of mini blocks and transactions to be done and received
wait := common.ExtraDelayForRequestBlockInfo
roundDifferences := t.roundHandler.Index() - int64(headerHandler.GetRound())
if roundDifferences > 1 {
wait = 0
}
time.Sleep(wait)
}
t.mapHashHdr[string(metaBlockHash)] = metaHdr
t.mapNonceHashes[metaHdr.Nonce] = append(t.mapNonceHashes[metaHdr.Nonce], string(metaBlockHash))
t.updateTriggerFromMeta()
}
// call only if mutex is locked before
func (t *trigger) isPreviousEpochStartMetaBlock(metaBlock *block.MetaBlock, metaBlockHash []byte) bool {
metaHdrHashesWithNonce := t.mapNonceHashes[metaBlock.Nonce+1]
for _, hash := range metaHdrHashesWithNonce {
epochStartMetaBlock, ok := t.mapEpochStartHdrs[hash]
if !ok {
continue
}
if !bytes.Equal(metaBlockHash, epochStartMetaBlock.GetPrevHash()) {
continue
}
return true
}
return false
}
// call only if mutex is locked before
func (t *trigger) updateTriggerFromMeta() {
sortedMetaInfo := make(metaInfoSlice, 0, len(t.mapEpochStartHdrs))
for hash, hdr := range t.mapEpochStartHdrs {
if _, ok := t.mapFinalizedEpochs[hdr.GetEpoch()]; ok {
continue
}
currMetaInfo := &metaInfo{
hdr: hdr,
hash: hash,
}
sortedMetaInfo = append(sortedMetaInfo, currMetaInfo)
}
sort.Sort(sortedMetaInfo)
for _, currMetaInfo := range sortedMetaInfo {
if _, ok := t.mapFinalizedEpochs[currMetaInfo.hdr.GetEpoch()]; ok {
continue
}
canActivateEpochStart, finalityAttestingRound := t.checkIfTriggerCanBeActivated(currMetaInfo.hash, currMetaInfo.hdr)
if canActivateEpochStart && t.metaEpoch < currMetaInfo.hdr.GetEpoch() {
t.metaEpoch = currMetaInfo.hdr.GetEpoch()
t.isEpochStart = true
t.epochStartRound = currMetaInfo.hdr.GetRound()
t.epochFinalityAttestingRound = finalityAttestingRound
t.epochMetaBlockHash = []byte(currMetaInfo.hash)
t.epochStartMeta = currMetaInfo.hdr
t.saveCurrentState(currMetaInfo.hdr.GetRound())
t.epochStartNotifier.NotifyEpochChangeConfirmed(t.metaEpoch)
msg := fmt.Sprintf("EPOCH %d BEGINS IN ROUND (%d)", t.metaEpoch, t.epochStartRound)
log.Debug(display.Headline(msg, "", "#"))
log.Debug("trigger.updateTriggerFromMeta", "isEpochStart", t.isEpochStart)
logger.SetCorrelationEpoch(t.metaEpoch)
t.clearMissingMiniBlocksMap(t.metaEpoch)
t.clearMissingValidatorsInfoMap(t.metaEpoch)
}
// save all final-valid epoch start blocks
if canActivateEpochStart {
t.mapFinalizedEpochs[currMetaInfo.hdr.GetEpoch()] = currMetaInfo.hash
t.saveEpochStartMeta(currMetaInfo.hdr)
}
}
}
func (t *trigger) saveEpochStartMeta(metaHdr data.HeaderHandler) {
if check.IfNil(metaHdr) {
return
}
epochStartIdentifier := core.EpochStartIdentifier(metaHdr.GetEpoch())
metaBuff, err := t.marshaller.Marshal(metaHdr)
if err != nil {
log.Debug("updateTriggerFromMeta marshal", "error", err.Error())
return
}
err = t.metaHdrStorage.Put([]byte(epochStartIdentifier), metaBuff)
if err != nil {
log.Debug("updateTriggerMeta put into metaHdrStorage", "error", err.Error())
}
err = t.triggerStorage.Put([]byte(epochStartIdentifier), metaBuff)
if err != nil {
log.Debug("updateTriggerMeta put into triggerStorage", "error", err.Error())
}
}
// call only if mutex is locked before
func (t *trigger) isMetaBlockValid(hash string, metaHdr data.HeaderHandler) bool {
currHdr := metaHdr
for i := metaHdr.GetNonce() - 1; i >= metaHdr.GetNonce()-t.validity; i-- {
neededHdr, err := t.getHeaderWithNonceAndHash(i, currHdr.GetPrevHash())
if err != nil {
log.Debug("isMetaBlockValid.getHeaderWithNonceAndHash", "hash", hash, "error", err.Error())
return false
}
err = t.headerValidator.IsHeaderConstructionValid(currHdr, neededHdr)
if err != nil {
log.Debug("isMetaBlockValid.IsHeaderConstructionValid", "hash", hash, "error", err.Error())
return false
}
currHdr = neededHdr
}
return true
}
func (t *trigger) isMetaBlockFinal(_ string, metaHdr data.HeaderHandler) (bool, uint64) {
nextBlocksVerified := uint64(0)
finalityAttestingRound := metaHdr.GetRound()
currHdr := metaHdr
for nonce := metaHdr.GetNonce() + 1; nonce <= metaHdr.GetNonce()+t.finality; nonce++ {
currHash, err := core.CalculateHash(t.marshaller, t.hasher, currHdr)
if err != nil {
continue
}
neededHdr, err := t.getHeaderWithNonceAndPrevHash(nonce, currHash)
if err != nil {
continue
}
currHdr = neededHdr
finalityAttestingRound = currHdr.GetRound()
nextBlocksVerified += 1
}
if nextBlocksVerified < t.finality {
log.Debug("isMetaBlockFinal", "nextBlocksVerified", nextBlocksVerified, "finality", t.finality)
for nonce := currHdr.GetNonce() + 1; nonce <= currHdr.GetNonce()+t.finality; nonce++ {
go t.requestHandler.RequestMetaHeaderByNonce(nonce)
}
return false, 0
}
return true, finalityAttestingRound
}
// call only if mutex is locked before
func (t *trigger) checkIfTriggerCanBeActivated(hash string, metaHdr data.HeaderHandler) (bool, uint64) {
isMetaHdrValid := t.isMetaBlockValid(hash, metaHdr)
if !isMetaHdrValid {
return false, 0
}
missingMiniBlocksHashes, blockBody, err := t.peerMiniBlocksSyncer.SyncMiniBlocks(metaHdr)
if err != nil {
t.addMissingMiniBlocks(metaHdr.GetEpoch(), missingMiniBlocksHashes)
log.Debug("checkIfTriggerCanBeActivated.SyncMiniBlocks", "num missing mini blocks", len(missingMiniBlocksHashes), "error", err)
return false, 0
}
if metaHdr.GetEpoch() >= t.enableEpochsHandler.RefactorPeersMiniBlocksEnableEpoch() {
missingValidatorsInfoHashes, validatorsInfo, err := t.peerMiniBlocksSyncer.SyncValidatorsInfo(blockBody)
if err != nil {
t.addMissingValidatorsInfo(metaHdr.GetEpoch(), missingValidatorsInfoHashes)
log.Debug("checkIfTriggerCanBeActivated.SyncValidatorsInfo", "num missing validators info", len(missingValidatorsInfoHashes), "error", err)
return false, 0
}
for validatorInfoHash, validatorInfo := range validatorsInfo {
t.currentEpochValidatorInfoPool.AddValidatorInfo([]byte(validatorInfoHash), validatorInfo)
}
}
t.epochStartNotifier.NotifyAllPrepare(metaHdr, blockBody)
isMetaHdrFinal, finalityAttestingRound := t.isMetaBlockFinal(hash, metaHdr)
return isMetaHdrFinal, finalityAttestingRound
}
func (t *trigger) addMissingMiniBlocks(epoch uint32, missingMiniBlocksHashes [][]byte) {
t.mutMissingMiniBlocks.Lock()
defer t.mutMissingMiniBlocks.Unlock()
for _, hash := range missingMiniBlocksHashes {
t.mapMissingMiniBlocks[string(hash)] = epoch
log.Debug("trigger.addMissingMiniBlocks", "epoch", epoch, "hash", hash)
}
}
func (t *trigger) addMissingValidatorsInfo(epoch uint32, missingValidatorsInfoHashes [][]byte) {
t.mutMissingValidatorsInfo.Lock()
defer t.mutMissingValidatorsInfo.Unlock()
for _, hash := range missingValidatorsInfoHashes {
t.mapMissingValidatorsInfo[string(hash)] = epoch
log.Debug("trigger.addMissingValidatorsInfo", "epoch", epoch, "hash", hash)
}
}
// call only if mutex is locked before
func (t *trigger) getHeaderWithNonceAndHashFromMaps(nonce uint64, neededHash []byte) data.HeaderHandler {
metaHdrHashesWithNonce := t.mapNonceHashes[nonce]
for _, hash := range metaHdrHashesWithNonce {
if !bytes.Equal(neededHash, []byte(hash)) {
continue
}
neededHdr := t.mapHashHdr[hash]
if !check.IfNil(neededHdr) {
return neededHdr
}
}
return nil
}
// call only if mutex is locked before
func (t *trigger) getHeaderWithHashFromPool(neededHash []byte) data.HeaderHandler {
peekedData, _ := t.headersPool.GetHeaderByHash(neededHash)
neededHdr, ok := peekedData.(*block.MetaBlock)
if ok {
t.mapHashHdr[string(neededHash)] = neededHdr
t.mapNonceHashes[neededHdr.Nonce] = append(t.mapNonceHashes[neededHdr.Nonce], string(neededHash))
return neededHdr
}
return nil
}
// call only if mutex is locked before
func (t *trigger) getHeaderWithHashFromStorage(neededHash []byte) data.HeaderHandler {
storageData, err := t.metaHdrStorage.Get(neededHash)
if err == nil {
var neededHdr block.MetaBlock
err = t.marshaller.Unmarshal(&neededHdr, storageData)
if err == nil {
t.mapHashHdr[string(neededHash)] = &neededHdr
t.mapNonceHashes[neededHdr.Nonce] = append(t.mapNonceHashes[neededHdr.Nonce], string(neededHash))
return &neededHdr
}
}
return nil
}
// call only if mutex is locked before
func (t *trigger) getHeaderWithNonceAndHash(nonce uint64, neededHash []byte) (data.HeaderHandler, error) {
metaHdr := t.getHeaderWithNonceAndHashFromMaps(nonce, neededHash)
if !check.IfNil(metaHdr) {
return metaHdr, nil
}
metaHdr = t.getHeaderWithHashFromPool(neededHash)
if !check.IfNil(metaHdr) {
return metaHdr, nil
}
metaHdr = t.getHeaderWithHashFromStorage(neededHash)
if !check.IfNil(metaHdr) {
return metaHdr, nil
}
go t.requestHandler.RequestMetaHeader(neededHash)
return nil, epochStart.ErrMetaHdrNotFound
}
// call only if mutex is locked before
func (t *trigger) getHeaderWithNonceAndPrevHashFromMaps(nonce uint64, prevHash []byte) data.HeaderHandler {
lowestRound := uint64(math.MaxUint64)
var chosenMeta data.HeaderHandler = &block.MetaBlock{}
metaHdrHashesWithNonce := t.mapNonceHashes[nonce]
for _, hash := range metaHdrHashesWithNonce {
hdrWithNonce := t.mapHashHdr[hash]
if check.IfNil(hdrWithNonce) {
continue
}
if !bytes.Equal(hdrWithNonce.GetPrevHash(), prevHash) {
continue
}
if lowestRound > hdrWithNonce.GetRound() {
lowestRound = hdrWithNonce.GetRound()
chosenMeta = hdrWithNonce
}
}
if lowestRound == uint64(math.MaxUint64) {
return nil
}
return chosenMeta
}
// call only if mutex is locked before
func (t *trigger) getHeaderWithNonceAndPrevHashFromCache(nonce uint64, prevHash []byte) data.HeaderHandler {
headers, hashes, err := t.headersPool.GetHeadersByNonceAndShardId(nonce, core.MetachainShardId)
if err != nil {
return nil
}
lowestRound := uint64(math.MaxUint64)
chosenMeta := &block.MetaBlock{}
for i, header := range headers {
if !bytes.Equal(header.GetPrevHash(), prevHash) {
continue
}
hdrWithNonce, ok := header.(*block.MetaBlock)
if !ok {
continue
}
if lowestRound > hdrWithNonce.GetRound() {
lowestRound = hdrWithNonce.GetRound()
chosenMeta = hdrWithNonce
}
t.mapHashHdr[string(hashes[i])] = hdrWithNonce
t.mapNonceHashes[hdrWithNonce.Nonce] = append(t.mapNonceHashes[hdrWithNonce.Nonce], string(hashes[i]))
}
if lowestRound == uint64(math.MaxUint64) {
return nil
}
return chosenMeta
}
// call only if mutex is locked before
func (t *trigger) getHeaderWithNonceAndPrevHash(nonce uint64, prevHash []byte) (data.HeaderHandler, error) {
metaHdr := t.getHeaderWithNonceAndPrevHashFromMaps(nonce, prevHash)
if !check.IfNil(metaHdr) {
return metaHdr, nil
}
metaHdr = t.getHeaderWithNonceAndPrevHashFromCache(nonce, prevHash)
if !check.IfNil(metaHdr) {
return metaHdr, nil
}
return nil, epochStart.ErrMetaHdrNotFound
}
func (t *trigger) getAllFinishedStartOfEpochMetaHdrs() []data.HeaderHandler {
finishedMetaHdrs := make([]data.HeaderHandler, 0, len(t.mapFinalizedEpochs))
for _, hash := range t.mapFinalizedEpochs {
metaHdr := t.mapEpochStartHdrs[hash]
finishedMetaHdrs = append(finishedMetaHdrs, metaHdr)
}
return finishedMetaHdrs
}
// SetProcessed sets start of epoch to false and cleans underlying structure
func (t *trigger) SetProcessed(header data.HeaderHandler, _ data.BodyHandler) {
t.mutTrigger.Lock()
defer t.mutTrigger.Unlock()
shardHdr, ok := header.(data.ShardHeaderHandler)
if !ok {
return
}
if !shardHdr.IsStartOfEpochBlock() {
return
}
t.appStatusHandler.SetUInt64Value(common.MetricRoundAtEpochStart, shardHdr.GetRound())
t.appStatusHandler.SetUInt64Value(common.MetricNonceAtEpochStart, shardHdr.GetNonce())
t.epoch = shardHdr.GetEpoch()
if t.metaEpoch < t.epoch {
t.metaEpoch = t.epoch
t.epochMetaBlockHash = shardHdr.GetEpochStartMetaHash()
}
t.isEpochStart = false
t.newEpochHdrReceived = false
t.epochStartShardHeader = shardHdr
finishedStartOfEpochMetaHdrs := t.getAllFinishedStartOfEpochMetaHdrs()
t.epochStartNotifier.NotifyAll(shardHdr)
t.mapHashHdr = make(map[string]data.HeaderHandler)
t.mapNonceHashes = make(map[uint64][]string)
t.mapEpochStartHdrs = make(map[string]data.HeaderHandler)
t.mapFinalizedEpochs = make(map[uint32]string)
t.saveCurrentState(header.GetRound())
log.Debug("trigger.SetProcessed", "isEpochStart", t.isEpochStart)
shardHdrBuff, errNotCritical := t.marshaller.Marshal(shardHdr)
if errNotCritical != nil {
log.Warn("SetProcessed marshal error", "error", errNotCritical)
}
epochStartIdentifier := core.EpochStartIdentifier(shardHdr.GetEpoch())
errNotCritical = t.shardHdrStorage.Put([]byte(epochStartIdentifier), shardHdrBuff)
if errNotCritical != nil {
logLevel := logger.LogWarning
if errors.IsClosingError(errNotCritical) {