-
Notifications
You must be signed in to change notification settings - Fork 199
/
indexHashedNodesCoordinator.go
1163 lines (980 loc) · 34.8 KB
/
indexHashedNodesCoordinator.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 sharding
import (
"bytes"
"fmt"
"sort"
"sync"
"sync/atomic"
logger "github.com/ElrondNetwork/elrond-go-logger"
"github.com/ElrondNetwork/elrond-go/core"
atomicFlags "github.com/ElrondNetwork/elrond-go/core/atomic"
"github.com/ElrondNetwork/elrond-go/core/check"
"github.com/ElrondNetwork/elrond-go/data"
"github.com/ElrondNetwork/elrond-go/data/block"
"github.com/ElrondNetwork/elrond-go/data/state"
"github.com/ElrondNetwork/elrond-go/hashing"
"github.com/ElrondNetwork/elrond-go/marshal"
"github.com/ElrondNetwork/elrond-go/storage"
)
var _ NodesCoordinator = (*indexHashedNodesCoordinator)(nil)
var _ PublicKeysSelector = (*indexHashedNodesCoordinator)(nil)
const (
keyFormat = "%s_%v_%v_%v"
defaultSelectionChances = uint32(1)
)
// TODO: move this to config parameters
const nodeCoordinatorStoredEpochs = 3
type validatorWithShardID struct {
validator Validator
shardID uint32
}
type validatorList []Validator
// Len will return the length of the validatorList
func (v validatorList) Len() int { return len(v) }
// Swap will interchange the objects on input indexes
func (v validatorList) Swap(i, j int) { v[i], v[j] = v[j], v[i] }
// Less will return true if object on index i should appear before object in index j
// Sorting of validators should be by index and public key
func (v validatorList) Less(i, j int) bool {
if v[i].Index() == v[j].Index() {
return bytes.Compare(v[i].PubKey(), v[j].PubKey()) < 0
}
return v[i].Index() < v[j].Index()
}
// TODO: add a parameter for shardID when acting as observer
type epochNodesConfig struct {
nbShards uint32
shardID uint32
eligibleMap map[uint32][]Validator
waitingMap map[uint32][]Validator
selectors map[uint32]RandomSelector
leavingMap map[uint32][]Validator
newList []Validator
mutNodesMaps sync.RWMutex
}
type indexHashedNodesCoordinator struct {
shardIDAsObserver uint32
currentEpoch uint32
shardConsensusGroupSize int
metaConsensusGroupSize int
numTotalEligible uint64
selfPubKey []byte
savedStateKey []byte
marshalizer marshal.Marshalizer
hasher hashing.Hasher
shuffler NodesShuffler
epochStartRegistrationHandler EpochStartEventNotifier
bootStorer storage.Storer
nodesConfig map[uint32]*epochNodesConfig
mutNodesConfig sync.RWMutex
mutSavedStateKey sync.RWMutex
nodesCoordinatorHelper NodesCoordinatorHelper
consensusGroupCacher Cacher
loadingFromDisk atomic.Value
shuffledOutHandler ShuffledOutHandler
startEpoch uint32
publicKeyToValidatorMap map[string]*validatorWithShardID
waitingListFixEnableEpoch uint32
flagWaitingListFix atomicFlags.Flag
}
// NewIndexHashedNodesCoordinator creates a new index hashed group selector
func NewIndexHashedNodesCoordinator(arguments ArgNodesCoordinator) (*indexHashedNodesCoordinator, error) {
err := checkArguments(arguments)
if err != nil {
return nil, err
}
nodesConfig := make(map[uint32]*epochNodesConfig, nodeCoordinatorStoredEpochs)
nodesConfig[arguments.Epoch] = &epochNodesConfig{
nbShards: arguments.NbShards,
shardID: arguments.ShardIDAsObserver,
eligibleMap: make(map[uint32][]Validator),
waitingMap: make(map[uint32][]Validator),
selectors: make(map[uint32]RandomSelector),
leavingMap: make(map[uint32][]Validator),
newList: make([]Validator, 0),
}
savedKey := arguments.Hasher.Compute(string(arguments.SelfPublicKey))
ihgs := &indexHashedNodesCoordinator{
marshalizer: arguments.Marshalizer,
hasher: arguments.Hasher,
shuffler: arguments.Shuffler,
epochStartRegistrationHandler: arguments.EpochStartNotifier,
bootStorer: arguments.BootStorer,
selfPubKey: arguments.SelfPublicKey,
nodesConfig: nodesConfig,
currentEpoch: arguments.Epoch,
savedStateKey: savedKey,
shardConsensusGroupSize: arguments.ShardConsensusGroupSize,
metaConsensusGroupSize: arguments.MetaConsensusGroupSize,
consensusGroupCacher: arguments.ConsensusGroupCache,
shardIDAsObserver: arguments.ShardIDAsObserver,
shuffledOutHandler: arguments.ShuffledOutHandler,
startEpoch: arguments.StartEpoch,
publicKeyToValidatorMap: make(map[string]*validatorWithShardID),
waitingListFixEnableEpoch: arguments.WaitingListFixEnabledEpoch,
}
ihgs.loadingFromDisk.Store(false)
ihgs.nodesCoordinatorHelper = ihgs
err = ihgs.setNodesPerShards(arguments.EligibleNodes, arguments.WaitingNodes, nil, arguments.Epoch)
if err != nil {
return nil, err
}
ihgs.fillPublicKeyToValidatorMap()
err = ihgs.saveState(ihgs.savedStateKey)
if err != nil {
log.Error("saving initial nodes coordinator config failed",
"error", err.Error())
}
log.Info("new nodes config is set for epoch", "epoch", arguments.Epoch)
currentNodesConfig := ihgs.nodesConfig[arguments.Epoch]
if currentNodesConfig == nil {
return nil, fmt.Errorf("%w epoch=%v", ErrEpochNodesConfigDoesNotExist, arguments.Epoch)
}
currentConfig := nodesConfig[arguments.Epoch]
if currentConfig == nil {
return nil, fmt.Errorf("%w epoch=%v", ErrEpochNodesConfigDoesNotExist, arguments.Epoch)
}
displayNodesConfiguration(
currentConfig.eligibleMap,
currentConfig.waitingMap,
currentConfig.leavingMap,
make(map[uint32][]Validator),
currentConfig.nbShards)
ihgs.epochStartRegistrationHandler.RegisterHandler(ihgs)
return ihgs, nil
}
func checkArguments(arguments ArgNodesCoordinator) error {
if arguments.ShardConsensusGroupSize < 1 || arguments.MetaConsensusGroupSize < 1 {
return ErrInvalidConsensusGroupSize
}
if arguments.NbShards < 1 {
return ErrInvalidNumberOfShards
}
if arguments.ShardIDAsObserver >= arguments.NbShards && arguments.ShardIDAsObserver != core.MetachainShardId {
return ErrInvalidShardId
}
if check.IfNil(arguments.Hasher) {
return ErrNilHasher
}
if len(arguments.SelfPublicKey) == 0 {
return ErrNilPubKey
}
if check.IfNil(arguments.Shuffler) {
return ErrNilShuffler
}
if check.IfNil(arguments.BootStorer) {
return ErrNilBootStorer
}
if check.IfNilReflect(arguments.ConsensusGroupCache) {
return ErrNilCacher
}
if check.IfNil(arguments.Marshalizer) {
return ErrNilMarshalizer
}
if check.IfNil(arguments.ShuffledOutHandler) {
return ErrNilShuffledOutHandler
}
return nil
}
// setNodesPerShards loads the distribution of nodes per shard into the nodes management component
func (ihgs *indexHashedNodesCoordinator) setNodesPerShards(
eligible map[uint32][]Validator,
waiting map[uint32][]Validator,
leaving map[uint32][]Validator,
epoch uint32,
) error {
ihgs.mutNodesConfig.Lock()
defer ihgs.mutNodesConfig.Unlock()
nodesConfig, ok := ihgs.nodesConfig[epoch]
if !ok {
log.Warn("Did not find nodesConfig", "epoch", epoch)
nodesConfig = &epochNodesConfig{}
}
nodesConfig.mutNodesMaps.Lock()
defer nodesConfig.mutNodesMaps.Unlock()
if eligible == nil || waiting == nil {
return ErrNilInputNodesMap
}
nodesList := eligible[core.MetachainShardId]
if len(nodesList) < ihgs.metaConsensusGroupSize {
return ErrSmallMetachainEligibleListSize
}
numTotalEligible := uint64(len(nodesList))
for shardId := uint32(0); shardId < uint32(len(eligible)-1); shardId++ {
nbNodesShard := len(eligible[shardId])
if nbNodesShard < ihgs.shardConsensusGroupSize {
return ErrSmallShardEligibleListSize
}
numTotalEligible += uint64(nbNodesShard)
}
var err error
// nbShards holds number of shards without meta
nodesConfig.nbShards = uint32(len(eligible) - 1)
nodesConfig.eligibleMap = eligible
nodesConfig.waitingMap = waiting
nodesConfig.leavingMap = leaving
nodesConfig.shardID = ihgs.computeShardForSelfPublicKey(nodesConfig)
nodesConfig.selectors, err = ihgs.createSelectors(nodesConfig)
if err != nil {
return err
}
ihgs.nodesConfig[epoch] = nodesConfig
ihgs.numTotalEligible = numTotalEligible
return nil
}
// ComputeAdditionalLeaving - computes extra leaving validators based on computation at the start of epoch
func (ihgs *indexHashedNodesCoordinator) ComputeAdditionalLeaving(_ []*state.ShardValidatorInfo) (map[uint32][]Validator, error) {
return make(map[uint32][]Validator), nil
}
// ComputeConsensusGroup will generate a list of validators based on the the eligible list
// and each eligible validator weight/chance
func (ihgs *indexHashedNodesCoordinator) ComputeConsensusGroup(
randomness []byte,
round uint64,
shardID uint32,
epoch uint32,
) (validatorsGroup []Validator, err error) {
var selector RandomSelector
var eligibleList []Validator
log.Trace("computing consensus group for",
"epoch", epoch,
"shardID", shardID,
"randomness", randomness,
"round", round)
if len(randomness) == 0 {
return nil, ErrNilRandomness
}
ihgs.mutNodesConfig.RLock()
nodesConfig, ok := ihgs.nodesConfig[epoch]
if ok {
if shardID >= nodesConfig.nbShards && shardID != core.MetachainShardId {
log.Warn("shardID is not ok", "shardID", shardID, "nbShards", nodesConfig.nbShards)
ihgs.mutNodesConfig.RUnlock()
return nil, ErrInvalidShardId
}
selector = nodesConfig.selectors[shardID]
eligibleList = nodesConfig.eligibleMap[shardID]
}
ihgs.mutNodesConfig.RUnlock()
if !ok {
return nil, fmt.Errorf("%w epoch=%v", ErrEpochNodesConfigDoesNotExist, epoch)
}
key := []byte(fmt.Sprintf(keyFormat, string(randomness), round, shardID, epoch))
validators := ihgs.searchConsensusForKey(key)
if validators != nil {
return validators, nil
}
consensusSize := ihgs.ConsensusGroupSize(shardID)
randomness = []byte(fmt.Sprintf("%d-%s", round, randomness))
log.Debug("computeValidatorsGroup",
"randomness", randomness,
"consensus size", consensusSize,
"eligible list length", len(eligibleList),
"epoch", epoch,
"round", round,
"shardID", shardID)
tempList, err := selectValidators(selector, randomness, uint32(consensusSize), eligibleList)
if err != nil {
return nil, err
}
size := 0
for _, v := range tempList {
size += v.Size()
}
ihgs.consensusGroupCacher.Put(key, tempList, size)
return tempList, nil
}
func (ihgs *indexHashedNodesCoordinator) searchConsensusForKey(key []byte) []Validator {
value, ok := ihgs.consensusGroupCacher.Get(key)
if ok {
consensusGroup, typeOk := value.([]Validator)
if typeOk {
return consensusGroup
}
}
return nil
}
// GetValidatorWithPublicKey gets the validator with the given public key
func (ihgs *indexHashedNodesCoordinator) GetValidatorWithPublicKey(publicKey []byte) (Validator, uint32, error) {
if len(publicKey) == 0 {
return nil, 0, ErrNilPubKey
}
ihgs.mutNodesConfig.RLock()
v, ok := ihgs.publicKeyToValidatorMap[string(publicKey)]
ihgs.mutNodesConfig.RUnlock()
if ok {
return v.validator, v.shardID, nil
}
return nil, 0, ErrValidatorNotFound
}
// GetConsensusValidatorsPublicKeys calculates the validators consensus group for a specific shard, randomness and round number,
// returning their public keys
func (ihgs *indexHashedNodesCoordinator) GetConsensusValidatorsPublicKeys(
randomness []byte,
round uint64,
shardID uint32,
epoch uint32,
) ([]string, error) {
consensusNodes, err := ihgs.ComputeConsensusGroup(randomness, round, shardID, epoch)
if err != nil {
return nil, err
}
pubKeys := make([]string, 0)
for _, v := range consensusNodes {
pubKeys = append(pubKeys, string(v.PubKey()))
}
return pubKeys, nil
}
// GetAllEligibleValidatorsPublicKeys will return all validators public keys for all shards
func (ihgs *indexHashedNodesCoordinator) GetAllEligibleValidatorsPublicKeys(epoch uint32) (map[uint32][][]byte, error) {
validatorsPubKeys := make(map[uint32][][]byte)
ihgs.mutNodesConfig.RLock()
nodesConfig, ok := ihgs.nodesConfig[epoch]
ihgs.mutNodesConfig.RUnlock()
if !ok {
return nil, fmt.Errorf("%w epoch=%v", ErrEpochNodesConfigDoesNotExist, epoch)
}
nodesConfig.mutNodesMaps.RLock()
defer nodesConfig.mutNodesMaps.RUnlock()
for shardID, shardEligible := range nodesConfig.eligibleMap {
for i := 0; i < len(shardEligible); i++ {
validatorsPubKeys[shardID] = append(validatorsPubKeys[shardID], shardEligible[i].PubKey())
}
}
return validatorsPubKeys, nil
}
// GetAllWaitingValidatorsPublicKeys will return all validators public keys for all shards
func (ihgs *indexHashedNodesCoordinator) GetAllWaitingValidatorsPublicKeys(epoch uint32) (map[uint32][][]byte, error) {
validatorsPubKeys := make(map[uint32][][]byte)
ihgs.mutNodesConfig.RLock()
nodesConfig, ok := ihgs.nodesConfig[epoch]
ihgs.mutNodesConfig.RUnlock()
if !ok {
return nil, fmt.Errorf("%w epoch=%v", ErrEpochNodesConfigDoesNotExist, epoch)
}
nodesConfig.mutNodesMaps.RLock()
defer nodesConfig.mutNodesMaps.RUnlock()
for shardID, shardWaiting := range nodesConfig.waitingMap {
for i := 0; i < len(shardWaiting); i++ {
validatorsPubKeys[shardID] = append(validatorsPubKeys[shardID], shardWaiting[i].PubKey())
}
}
return validatorsPubKeys, nil
}
// GetAllLeavingValidatorsPublicKeys will return all leaving validators public keys for all shards
func (ihgs *indexHashedNodesCoordinator) GetAllLeavingValidatorsPublicKeys(epoch uint32) (map[uint32][][]byte, error) {
validatorsPubKeys := make(map[uint32][][]byte)
ihgs.mutNodesConfig.RLock()
nodesConfig, ok := ihgs.nodesConfig[epoch]
ihgs.mutNodesConfig.RUnlock()
if !ok {
return nil, fmt.Errorf("%w epoch=%v", ErrEpochNodesConfigDoesNotExist, epoch)
}
nodesConfig.mutNodesMaps.RLock()
defer nodesConfig.mutNodesMaps.RUnlock()
for shardID, shardLeaving := range nodesConfig.leavingMap {
for i := 0; i < len(shardLeaving); i++ {
validatorsPubKeys[shardID] = append(validatorsPubKeys[shardID], shardLeaving[i].PubKey())
}
}
return validatorsPubKeys, nil
}
// GetValidatorsIndexes will return validators indexes for a block
func (ihgs *indexHashedNodesCoordinator) GetValidatorsIndexes(
publicKeys []string,
epoch uint32,
) ([]uint64, error) {
signersIndexes := make([]uint64, 0)
validatorsPubKeys, err := ihgs.GetAllEligibleValidatorsPublicKeys(epoch)
if err != nil {
return nil, err
}
ihgs.mutNodesConfig.RLock()
nodesConfig := ihgs.nodesConfig[epoch]
ihgs.mutNodesConfig.RUnlock()
for _, pubKey := range publicKeys {
for index, value := range validatorsPubKeys[nodesConfig.shardID] {
if bytes.Equal([]byte(pubKey), value) {
signersIndexes = append(signersIndexes, uint64(index))
}
}
}
if len(publicKeys) != len(signersIndexes) {
strHaving := "having the following keys: \n"
for index, value := range validatorsPubKeys[nodesConfig.shardID] {
strHaving += fmt.Sprintf(" index %d key %s\n", index, logger.DisplayByteSlice(value))
}
strNeeded := "needed the following keys: \n"
for _, pubKey := range publicKeys {
strNeeded += fmt.Sprintf(" key %s\n", logger.DisplayByteSlice([]byte(pubKey)))
}
log.Error("public keys not found\n"+strHaving+"\n"+strNeeded+"\n",
"len pubKeys", len(publicKeys),
"len signers", len(signersIndexes),
)
return nil, ErrInvalidNumberPubKeys
}
return signersIndexes, nil
}
// EpochStartPrepare is called when an epoch start event is observed, but not yet confirmed/committed.
// Some components may need to do some initialisation on this event
func (ihgs *indexHashedNodesCoordinator) EpochStartPrepare(metaHdr data.HeaderHandler, body data.BodyHandler) {
if !metaHdr.IsStartOfEpochBlock() {
log.Error("could not process EpochStartPrepare on nodesCoordinator - not epoch start block")
return
}
if _, ok := metaHdr.(*block.MetaBlock); !ok {
log.Error("could not process EpochStartPrepare on nodesCoordinator - not metaBlock")
return
}
randomness := metaHdr.GetPrevRandSeed()
newEpoch := metaHdr.GetEpoch()
if check.IfNil(body) && newEpoch == ihgs.currentEpoch {
log.Debug("nil body provided for epoch start prepare, it is normal in case of revertStateToBlock")
return
}
allValidatorInfo, err := createValidatorInfoFromBody(body, ihgs.marshalizer, ihgs.numTotalEligible)
if err != nil {
log.Error("could not create validator info from body - do nothing on nodesCoordinator epochStartPrepare")
return
}
ihgs.updateEpochFlags(newEpoch)
ihgs.mutNodesConfig.RLock()
previousConfig := ihgs.nodesConfig[ihgs.currentEpoch]
if previousConfig == nil {
log.Error("previous nodes config is nil")
ihgs.mutNodesConfig.RUnlock()
return
}
//TODO: remove the copy if no changes are done to the maps
copiedPrevious := &epochNodesConfig{}
copiedPrevious.eligibleMap = copyValidatorMap(previousConfig.eligibleMap)
copiedPrevious.waitingMap = copyValidatorMap(previousConfig.waitingMap)
copiedPrevious.nbShards = previousConfig.nbShards
ihgs.mutNodesConfig.RUnlock()
// TODO: compare with previous nodesConfig if exists
newNodesConfig, err := ihgs.computeNodesConfigFromList(copiedPrevious, allValidatorInfo)
if err != nil {
log.Error("could not compute nodes config from list - do nothing on nodesCoordinator epochStartPrepare")
return
}
if copiedPrevious.nbShards != newNodesConfig.nbShards {
log.Warn("number of shards does not match",
"previous epoch", ihgs.currentEpoch,
"previous number of shards", copiedPrevious.nbShards,
"new epoch", newEpoch,
"new number of shards", newNodesConfig.nbShards)
}
additionalLeavingMap, err := ihgs.nodesCoordinatorHelper.ComputeAdditionalLeaving(allValidatorInfo)
if err != nil {
log.Error("could not compute additionalLeaving Nodes - do nothing on nodesCoordinator epochStartPrepare")
return
}
unStakeLeavingList := ihgs.createSortedListFromMap(newNodesConfig.leavingMap)
additionalLeavingList := ihgs.createSortedListFromMap(additionalLeavingMap)
shufflerArgs := ArgsUpdateNodes{
Eligible: newNodesConfig.eligibleMap,
Waiting: newNodesConfig.waitingMap,
NewNodes: newNodesConfig.newList,
UnStakeLeaving: unStakeLeavingList,
AdditionalLeaving: additionalLeavingList,
Rand: randomness,
NbShards: newNodesConfig.nbShards,
Epoch: newEpoch,
}
resUpdateNodes, err := ihgs.shuffler.UpdateNodeLists(shufflerArgs)
if err != nil {
log.Error("could not compute UpdateNodeLists - do nothing on nodesCoordinator epochStartPrepare", "err", err.Error())
return
}
leavingNodesMap, stillRemainingNodesMap := createActuallyLeavingPerShards(
newNodesConfig.leavingMap,
additionalLeavingMap,
resUpdateNodes.Leaving,
)
err = ihgs.setNodesPerShards(resUpdateNodes.Eligible, resUpdateNodes.Waiting, leavingNodesMap, newEpoch)
if err != nil {
log.Error("set nodes per shard failed", "error", err.Error())
}
ihgs.fillPublicKeyToValidatorMap()
err = ihgs.saveState(randomness)
if err != nil {
log.Error("saving nodes coordinator config failed", "error", err.Error())
}
displayNodesConfiguration(
resUpdateNodes.Eligible,
resUpdateNodes.Waiting,
leavingNodesMap,
stillRemainingNodesMap,
newNodesConfig.nbShards)
ihgs.mutSavedStateKey.Lock()
ihgs.savedStateKey = randomness
ihgs.mutSavedStateKey.Unlock()
ihgs.consensusGroupCacher.Clear()
}
func (ihgs *indexHashedNodesCoordinator) fillPublicKeyToValidatorMap() {
ihgs.mutNodesConfig.Lock()
defer ihgs.mutNodesConfig.Unlock()
index := 0
epochList := make([]uint32, len(ihgs.nodesConfig))
mapAllValidators := make(map[uint32]map[string]*validatorWithShardID)
for epoch, epochConfig := range ihgs.nodesConfig {
epochConfig.mutNodesMaps.RLock()
mapAllValidators[epoch] = ihgs.createPublicKeyToValidatorMap(epochConfig.eligibleMap, epochConfig.waitingMap)
epochConfig.mutNodesMaps.RUnlock()
epochList[index] = epoch
index++
}
sort.Slice(epochList, func(i, j int) bool {
return epochList[i] < epochList[j]
})
ihgs.publicKeyToValidatorMap = make(map[string]*validatorWithShardID)
for _, epoch := range epochList {
validatorsForEpoch := mapAllValidators[epoch]
for pubKey, vInfo := range validatorsForEpoch {
ihgs.publicKeyToValidatorMap[pubKey] = vInfo
}
}
}
func (ihgs *indexHashedNodesCoordinator) createSortedListFromMap(validatorsMap map[uint32][]Validator) []Validator {
sortedList := make([]Validator, 0)
for _, validators := range validatorsMap {
sortedList = append(sortedList, validators...)
}
sort.Sort(validatorList(sortedList))
return sortedList
}
// GetChance will return default chance
func (ihgs *indexHashedNodesCoordinator) GetChance(_ uint32) uint32 {
return defaultSelectionChances
}
func (ihgs *indexHashedNodesCoordinator) computeNodesConfigFromList(
previousEpochConfig *epochNodesConfig,
validatorInfos []*state.ShardValidatorInfo,
) (*epochNodesConfig, error) {
eligibleMap := make(map[uint32][]Validator)
waitingMap := make(map[uint32][]Validator)
leavingMap := make(map[uint32][]Validator)
newNodesList := make([]Validator, 0)
if ihgs.flagWaitingListFix.IsSet() && previousEpochConfig == nil {
return nil, ErrNilPreviousEpochConfig
}
if len(validatorInfos) == 0 {
log.Warn("computeNodesConfigFromList - validatorInfos len is 0")
}
for _, validatorInfo := range validatorInfos {
chance := ihgs.nodesCoordinatorHelper.GetChance(validatorInfo.TempRating)
currentValidator, err := NewValidator(validatorInfo.PublicKey, chance, validatorInfo.Index)
if err != nil {
return nil, err
}
switch validatorInfo.List {
case string(core.WaitingList):
waitingMap[validatorInfo.ShardId] = append(waitingMap[validatorInfo.ShardId], currentValidator)
case string(core.EligibleList):
eligibleMap[validatorInfo.ShardId] = append(eligibleMap[validatorInfo.ShardId], currentValidator)
case string(core.LeavingList):
log.Debug("leaving node validatorInfo", "pk", validatorInfo.PublicKey)
leavingMap[validatorInfo.ShardId] = append(leavingMap[validatorInfo.ShardId], currentValidator)
ihgs.addValidatorToPreviousMap(
previousEpochConfig,
eligibleMap,
waitingMap,
currentValidator,
validatorInfo.ShardId)
case string(core.NewList):
log.Debug("new node registered", "pk", validatorInfo.PublicKey)
newNodesList = append(newNodesList, currentValidator)
case string(core.InactiveList):
log.Debug("inactive validator", "pk", validatorInfo.PublicKey)
case string(core.JailedList):
log.Debug("jailed validator", "pk", validatorInfo.PublicKey)
}
}
sort.Sort(validatorList(newNodesList))
for _, eligibleList := range eligibleMap {
sort.Sort(validatorList(eligibleList))
}
for _, waitingList := range waitingMap {
sort.Sort(validatorList(waitingList))
}
for _, leavingList := range leavingMap {
sort.Sort(validatorList(leavingList))
}
if len(eligibleMap) == 0 {
return nil, fmt.Errorf("%w eligible map size is zero. No validators found", ErrMapSizeZero)
}
nbShards := len(eligibleMap) - 1
newNodesConfig := &epochNodesConfig{
eligibleMap: eligibleMap,
waitingMap: waitingMap,
leavingMap: leavingMap,
newList: newNodesList,
nbShards: uint32(nbShards),
}
return newNodesConfig, nil
}
func (ihgs *indexHashedNodesCoordinator) addValidatorToPreviousMap(
previousEpochConfig *epochNodesConfig,
eligibleMap map[uint32][]Validator,
waitingMap map[uint32][]Validator,
currentValidator *validator,
currentValidatorShardId uint32) {
if !ihgs.flagWaitingListFix.IsSet() {
eligibleMap[currentValidatorShardId] = append(eligibleMap[currentValidatorShardId], currentValidator)
return
}
found, shardId := searchInMap(previousEpochConfig.eligibleMap, currentValidator.PubKey())
if found {
log.Debug("leaving node found in", "list", "eligible", "shardId", shardId)
eligibleMap[shardId] = append(eligibleMap[currentValidatorShardId], currentValidator)
return
}
found, shardId = searchInMap(previousEpochConfig.waitingMap, currentValidator.PubKey())
if found {
log.Debug("leaving node found in", "list", "waiting", "shardId", shardId)
waitingMap[shardId] = append(waitingMap[currentValidatorShardId], currentValidator)
return
}
}
// EpochStartAction is called upon a start of epoch event.
// NodeCoordinator has to get the nodes assignment to shards using the shuffler.
func (ihgs *indexHashedNodesCoordinator) EpochStartAction(hdr data.HeaderHandler) {
newEpoch := hdr.GetEpoch()
epochToRemove := int32(newEpoch) - nodeCoordinatorStoredEpochs
needToRemove := epochToRemove >= 0
ihgs.currentEpoch = newEpoch
err := ihgs.saveState(ihgs.savedStateKey)
if err != nil {
log.Error("saving nodes coordinator config failed", "error", err.Error())
}
ihgs.mutNodesConfig.Lock()
if needToRemove {
for epoch := range ihgs.nodesConfig {
if epoch <= uint32(epochToRemove) {
delete(ihgs.nodesConfig, epoch)
}
}
}
ihgs.mutNodesConfig.Unlock()
}
// NotifyOrder returns the notification order for a start of epoch event
func (ihgs *indexHashedNodesCoordinator) NotifyOrder() uint32 {
return core.NodesCoordinatorOrder
}
// GetSavedStateKey returns the key for the last nodes coordinator saved state
func (ihgs *indexHashedNodesCoordinator) GetSavedStateKey() []byte {
ihgs.mutSavedStateKey.RLock()
key := ihgs.savedStateKey
ihgs.mutSavedStateKey.RUnlock()
return key
}
// ShardIdForEpoch returns the nodesCoordinator configured ShardId for specified epoch if epoch configuration exists,
// otherwise error
func (ihgs *indexHashedNodesCoordinator) ShardIdForEpoch(epoch uint32) (uint32, error) {
ihgs.mutNodesConfig.RLock()
nodesConfig, ok := ihgs.nodesConfig[epoch]
ihgs.mutNodesConfig.RUnlock()
if !ok {
return 0, fmt.Errorf("%w epoch=%v", ErrEpochNodesConfigDoesNotExist, epoch)
}
return nodesConfig.shardID, nil
}
// ShuffleOutForEpoch verifies if the shards changed in the new epoch and calls the shuffleOutHandler
func (ihgs *indexHashedNodesCoordinator) ShuffleOutForEpoch(epoch uint32) {
log.Debug("shuffle out called for", "epoch", epoch)
ihgs.mutNodesConfig.Lock()
nodesConfig := ihgs.nodesConfig[epoch]
ihgs.mutNodesConfig.Unlock()
if nodesConfig == nil {
log.Warn("shuffleOutForEpoch failed",
"epoch", epoch,
"error", ErrEpochNodesConfigDoesNotExist)
return
}
if isValidator(nodesConfig, ihgs.selfPubKey) {
err := ihgs.shuffledOutHandler.Process(nodesConfig.shardID)
if err != nil {
log.Warn("shuffle out process failed", "err", err)
}
}
}
func isValidator(config *epochNodesConfig, pk []byte) bool {
if config == nil {
return false
}
config.mutNodesMaps.RLock()
defer config.mutNodesMaps.RUnlock()
found := false
found, _ = searchInMap(config.eligibleMap, pk)
if found {
return true
}
found, _ = searchInMap(config.waitingMap, pk)
return found
}
func searchInMap(validatorMap map[uint32][]Validator, pk []byte) (bool, uint32) {
for shardId, validatorsInShard := range validatorMap {
for _, val := range validatorsInShard {
if bytes.Equal(val.PubKey(), pk) {
return true, shardId
}
}
}
return false, 0
}
// GetConsensusWhitelistedNodes return the whitelisted nodes allowed to send consensus messages, for each of the shards
func (ihgs *indexHashedNodesCoordinator) GetConsensusWhitelistedNodes(
epoch uint32,
) (map[string]struct{}, error) {
var err error
shardEligible := make(map[string]struct{})
publicKeysPrevEpoch := make(map[uint32][][]byte)
prevEpochConfigExists := false
if epoch > ihgs.startEpoch {
publicKeysPrevEpoch, err = ihgs.GetAllEligibleValidatorsPublicKeys(epoch - 1)
if err == nil {
prevEpochConfigExists = true
} else {
log.Warn("get consensus whitelisted nodes", "error", err.Error())
}
}
var prevEpochShardId uint32
if prevEpochConfigExists {
prevEpochShardId, err = ihgs.ShardIdForEpoch(epoch - 1)
if err == nil {
for _, pubKey := range publicKeysPrevEpoch[prevEpochShardId] {
shardEligible[string(pubKey)] = struct{}{}
}
} else {
log.Trace("not critical error getting shardID for epoch", "epoch", epoch-1, "error", err)
}
}
publicKeysNewEpoch, errGetEligible := ihgs.GetAllEligibleValidatorsPublicKeys(epoch)
if errGetEligible != nil {
return nil, errGetEligible
}
epochShardId, errShardIdForEpoch := ihgs.ShardIdForEpoch(epoch)
if errShardIdForEpoch != nil {
return nil, errShardIdForEpoch
}
for _, pubKey := range publicKeysNewEpoch[epochShardId] {
shardEligible[string(pubKey)] = struct{}{}
}
return shardEligible, nil
}
func (ihgs *indexHashedNodesCoordinator) createPublicKeyToValidatorMap(
eligible map[uint32][]Validator,
waiting map[uint32][]Validator,
) map[string]*validatorWithShardID {
publicKeyToValidatorMap := make(map[string]*validatorWithShardID)
for shardId, shardEligible := range eligible {
for i := 0; i < len(shardEligible); i++ {
publicKeyToValidatorMap[string(shardEligible[i].PubKey())] = &validatorWithShardID{
validator: shardEligible[i],
shardID: shardId,
}
}
}
for shardId, shardWaiting := range waiting {
for i := 0; i < len(shardWaiting); i++ {
publicKeyToValidatorMap[string(shardWaiting[i].PubKey())] = &validatorWithShardID{
validator: shardWaiting[i],
shardID: shardId,
}
}
}
return publicKeyToValidatorMap
}
func (ihgs *indexHashedNodesCoordinator) computeShardForSelfPublicKey(nodesConfig *epochNodesConfig) uint32 {
pubKey := ihgs.selfPubKey
selfShard := ihgs.shardIDAsObserver
epNodesConfig, ok := ihgs.nodesConfig[ihgs.currentEpoch]
if ok {
log.Trace("computeShardForSelfPublicKey found existing config",
"shard", epNodesConfig.shardID,
)
selfShard = epNodesConfig.shardID
}
found, shardId := searchInMap(nodesConfig.eligibleMap, pubKey)
if found {
log.Trace("computeShardForSelfPublicKey found validator in eligible",
"epoch", ihgs.currentEpoch,
"shard", shardId,
"validator PK", pubKey,
)
return shardId
}
found, shardId = searchInMap(nodesConfig.waitingMap, pubKey)
if found {
log.Trace("computeShardForSelfPublicKey found validator in waiting",
"epoch", ihgs.currentEpoch,
"shard", shardId,
"validator PK", pubKey,
)
return shardId
}
found, shardId = searchInMap(nodesConfig.leavingMap, pubKey)
if found {
log.Trace("computeShardForSelfPublicKey found validator in leaving",
"epoch", ihgs.currentEpoch,
"shard", shardId,
"validator PK", pubKey,
)
return shardId
}
log.Trace("computeShardForSelfPublicKey returned default",
"shard", selfShard,
)
return selfShard
}
// ConsensusGroupSize returns the consensus group size for a specific shard
func (ihgs *indexHashedNodesCoordinator) ConsensusGroupSize(
shardID uint32,
) int {
if shardID == core.MetachainShardId {
return ihgs.metaConsensusGroupSize
}
return ihgs.shardConsensusGroupSize
}
// GetNumTotalEligible returns the number of total eligible accross all shards from current setup
func (ihgs *indexHashedNodesCoordinator) GetNumTotalEligible() uint64 {