Check Head State For New Head Methods (#9676)

* check head state

* add tests
This commit is contained in:
Nishant Das 2021-09-27 16:27:11 +08:00 committed by GitHub
parent 376d248c22
commit 6eb158c16a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 2 deletions

View File

@ -293,7 +293,9 @@ func (s *Service) ChainHeads() ([][32]byte, []types.Slot) {
func (s *Service) HeadPublicKeyToValidatorIndex(ctx context.Context, pubKey [48]byte) (types.ValidatorIndex, bool) { func (s *Service) HeadPublicKeyToValidatorIndex(ctx context.Context, pubKey [48]byte) (types.ValidatorIndex, bool) {
s.headLock.RLock() s.headLock.RLock()
defer s.headLock.RUnlock() defer s.headLock.RUnlock()
if !s.hasHeadState() {
return 0, false
}
return s.headState(ctx).ValidatorIndexByPubkey(pubKey) return s.headState(ctx).ValidatorIndexByPubkey(pubKey)
} }
@ -301,7 +303,9 @@ func (s *Service) HeadPublicKeyToValidatorIndex(ctx context.Context, pubKey [48]
func (s *Service) HeadValidatorIndexToPublicKey(_ context.Context, index types.ValidatorIndex) ([48]byte, error) { func (s *Service) HeadValidatorIndexToPublicKey(_ context.Context, index types.ValidatorIndex) ([48]byte, error) {
s.headLock.RLock() s.headLock.RLock()
defer s.headLock.RUnlock() defer s.headLock.RUnlock()
if !s.hasHeadState() {
return [48]byte{}, nil
}
v, err := s.headValidatorAtIndex(index) v, err := s.headValidatorAtIndex(index)
if err != nil { if err != nil {
return [48]byte{}, err return [48]byte{}, err

View File

@ -313,6 +313,20 @@ func TestService_HeadPublicKeyToValidatorIndex(t *testing.T) {
require.Equal(t, types.ValidatorIndex(0), i) require.Equal(t, types.ValidatorIndex(0), i)
} }
func TestService_HeadPublicKeyToValidatorIndexNil(t *testing.T) {
c := &Service{}
c.head = nil
idx, e := c.HeadPublicKeyToValidatorIndex(context.Background(), [48]byte{})
require.Equal(t, false, e)
require.Equal(t, types.ValidatorIndex(0), idx)
c.head = &head{state: nil}
i, e := c.HeadPublicKeyToValidatorIndex(context.Background(), [48]byte{})
require.Equal(t, false, e)
require.Equal(t, types.ValidatorIndex(0), i)
}
func TestService_HeadValidatorIndexToPublicKey(t *testing.T) { func TestService_HeadValidatorIndexToPublicKey(t *testing.T) {
s, _ := util.DeterministicGenesisState(t, 10) s, _ := util.DeterministicGenesisState(t, 10)
c := &Service{} c := &Service{}
@ -326,3 +340,17 @@ func TestService_HeadValidatorIndexToPublicKey(t *testing.T) {
require.Equal(t, bytesutil.ToBytes48(v.PublicKey), p) require.Equal(t, bytesutil.ToBytes48(v.PublicKey), p)
} }
func TestService_HeadValidatorIndexToPublicKeyNil(t *testing.T) {
c := &Service{}
c.head = nil
p, err := c.HeadValidatorIndexToPublicKey(context.Background(), 0)
require.NoError(t, err)
require.Equal(t, [48]byte{}, p)
c.head = &head{state: nil}
p, err = c.HeadValidatorIndexToPublicKey(context.Background(), 0)
require.NoError(t, err)
require.Equal(t, [48]byte{}, p)
}