diff --git a/consensus/consensus.go b/consensus/consensus.go index 1c8fd8cd1..f1ced01d5 100644 --- a/consensus/consensus.go +++ b/consensus/consensus.go @@ -88,7 +88,7 @@ type Consensus struct { Log log.Logger - uniqueIDInstance *utils.UniqueValidatorId + uniqueIDInstance *utils.UniqueValidatorID } // BlockConsensusStatus used to keep track of the consensus status of multiple blocks received so far @@ -173,7 +173,7 @@ func NewConsensus(ip, port, ShardID string, peers []p2p.Peer, leader p2p.Peer) * } consensus.Log = log.New() - consensus.uniqueIDInstance = utils.GetUniqueValidatorIdInstance() + consensus.uniqueIDInstance = utils.GetUniqueValidatorIDInstance() return &consensus } @@ -242,7 +242,7 @@ func (consensus *Consensus) AddPeers(peers []p2p.Peer) int { _, ok := consensus.validators.Load(utils.GetUniqueIdFromPeer(peer)) if !ok { if peer.ValidatorID == -1 { - peer.ValidatorID = int(consensus.uniqueIDInstance.GetUniqueId()) + peer.ValidatorID = int(consensus.uniqueIDInstance.GetUniqueID()) } consensus.validators.Store(utils.GetUniqueIdFromPeer(peer), peer) consensus.PublicKeys = append(consensus.PublicKeys, peer.PubKey) diff --git a/utils/singleton.go b/utils/singleton.go index ec49ad898..fa2ffc9c8 100644 --- a/utils/singleton.go +++ b/utils/singleton.go @@ -7,22 +7,25 @@ import ( "sync/atomic" ) -type UniqueValidatorId struct { - uniqueId uint32 +// UniqueValidatorID defines the structure of unique validator ID +type UniqueValidatorID struct { + uniqueID uint32 } -var instance *UniqueValidatorId +var instance *UniqueValidatorID var once sync.Once -func GetUniqueValidatorIdInstance() *UniqueValidatorId { +// GetUniqueValidatorIDInstance returns a singleton instance +func GetUniqueValidatorIDInstance() *UniqueValidatorID { once.Do(func() { - instance = &UniqueValidatorId{ - uniqueId: 0, + instance = &UniqueValidatorID{ + uniqueID: 0, } }) return instance } -func (s *UniqueValidatorId) GetUniqueId() uint32 { - return atomic.AddUint32(&s.uniqueId, 1) +// GetUniqueID returns a unique ID and increment the internal variable +func (s *UniqueValidatorID) GetUniqueID() uint32 { + return atomic.AddUint32(&s.uniqueID, 1) } diff --git a/utils/singleton_test.go b/utils/singleton_test.go index 0117f6423..0f2a0b9ec 100644 --- a/utils/singleton_test.go +++ b/utils/singleton_test.go @@ -6,10 +6,10 @@ import ( "time" ) -var NumThreads int = 20 +var NumThreads = 20 func TestSingleton(t *testing.T) { - si := GetUniqueValidatorIdInstance() + si := GetUniqueValidatorIDInstance() var wg sync.WaitGroup t.Log("unique ID provided by singleton instance") @@ -18,7 +18,7 @@ func TestSingleton(t *testing.T) { wg.Add(1) go func() { defer wg.Done() - t.Logf("id:%v\n", si.GetUniqueId()) + t.Logf("id:%v\n", si.GetUniqueID()) time.Sleep(time.Millisecond) }()