github.com/prysmaticlabs/prysm@v1.4.4/slasher/beaconclient/validator_retrieval.go (about)

     1  package beaconclient
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/pkg/errors"
     7  	types "github.com/prysmaticlabs/eth2-types"
     8  	ethpb "github.com/prysmaticlabs/prysm/proto/eth/v1alpha1"
     9  	"go.opencensus.io/trace"
    10  )
    11  
    12  // FindOrGetPublicKeys gets public keys from cache or request validators public
    13  // keys from a beacon node via gRPC.
    14  func (s *Service) FindOrGetPublicKeys(
    15  	ctx context.Context,
    16  	validatorIndices []types.ValidatorIndex,
    17  ) (map[types.ValidatorIndex][]byte, error) {
    18  	ctx, span := trace.StartSpan(ctx, "beaconclient.FindOrGetPublicKeys")
    19  	defer span.End()
    20  
    21  	validators := make(map[types.ValidatorIndex][]byte, len(validatorIndices))
    22  	notFound := 0
    23  	for _, validatorIndex := range validatorIndices {
    24  		pub, exists := s.publicKeyCache.Get(validatorIndex)
    25  		if exists {
    26  			validators[validatorIndex] = pub
    27  			continue
    28  		}
    29  		// inline removal of cached elements from slice
    30  		validatorIndices[notFound] = validatorIndex
    31  		notFound++
    32  	}
    33  	// trim the slice to its new size
    34  	validatorIndices = validatorIndices[:notFound]
    35  
    36  	if len(validators) > 0 {
    37  		log.Tracef(
    38  			"Retrieved validators public keys from cache: %v",
    39  			validators,
    40  		)
    41  	}
    42  
    43  	if notFound == 0 {
    44  		return validators, nil
    45  	}
    46  	vc, err := s.cfg.BeaconClient.ListValidators(ctx, &ethpb.ListValidatorsRequest{
    47  		Indices: validatorIndices,
    48  	})
    49  	if err != nil {
    50  		return nil, errors.Wrapf(err, "could not request validators public key: %d", validatorIndices)
    51  	}
    52  	for _, v := range vc.ValidatorList {
    53  		validators[v.Index] = v.Validator.PublicKey
    54  		s.publicKeyCache.Set(v.Index, v.Validator.PublicKey)
    55  	}
    56  	log.Tracef(
    57  		"Retrieved validators id public key map: %v",
    58  		validators,
    59  	)
    60  	return validators, nil
    61  }