github.com/prysmaticlabs/prysm@v1.4.4/slasher/cache/validators_cache.go (about)

     1  package cache
     2  
     3  import (
     4  	lru "github.com/hashicorp/golang-lru"
     5  	"github.com/prometheus/client_golang/prometheus"
     6  	"github.com/prometheus/client_golang/prometheus/promauto"
     7  	types "github.com/prysmaticlabs/eth2-types"
     8  )
     9  
    10  var (
    11  	// validatorsCacheSize defines the max number of validators public keys the cache can hold.
    12  	validatorsCacheSize = 300000
    13  	// Metrics for the validator cache.
    14  	validatorsCacheHit = promauto.NewCounter(prometheus.CounterOpts{
    15  		Name: "validators_cache_hit",
    16  		Help: "The total number of cache hits on the validators cache.",
    17  	})
    18  	validatorsCacheMiss = promauto.NewCounter(prometheus.CounterOpts{
    19  		Name: "validators_cache_miss",
    20  		Help: "The total number of cache misses on the validators cache.",
    21  	})
    22  )
    23  
    24  // PublicKeyCache is used to store the public keys needed for signature verification.
    25  type PublicKeyCache struct {
    26  	cache *lru.Cache
    27  }
    28  
    29  // NewPublicKeyCache initializes the cache.
    30  func NewPublicKeyCache(size int, onEvicted func(key interface{}, value interface{})) (*PublicKeyCache, error) {
    31  	if size != 0 {
    32  		validatorsCacheSize = size
    33  	}
    34  	cache, err := lru.NewWithEvict(validatorsCacheSize, onEvicted)
    35  	if err != nil {
    36  		return nil, err
    37  	}
    38  	return &PublicKeyCache{cache: cache}, nil
    39  }
    40  
    41  // Get returns an ok bool and the cached value for the requested validator id key, if any.
    42  func (c *PublicKeyCache) Get(validatorIndex types.ValidatorIndex) ([]byte, bool) {
    43  	item, exists := c.cache.Get(validatorIndex)
    44  	if exists && item != nil {
    45  		validatorsCacheHit.Inc()
    46  		return item.([]byte), true
    47  	}
    48  
    49  	validatorsCacheMiss.Inc()
    50  	return nil, false
    51  }
    52  
    53  // Set the response in the cache.
    54  func (c *PublicKeyCache) Set(validatorIndex types.ValidatorIndex, publicKey []byte) {
    55  	_ = c.cache.Add(validatorIndex, publicKey)
    56  }
    57  
    58  // Delete removes a validator id from the cache and returns if it existed or not.
    59  // Performs the onEviction function before removal.
    60  func (c *PublicKeyCache) Delete(validatorIndex types.ValidatorIndex) bool {
    61  	return c.cache.Remove(validatorIndex)
    62  }
    63  
    64  // Has returns true if the key exists in the cache.
    65  func (c *PublicKeyCache) Has(validatorIndex types.ValidatorIndex) bool {
    66  	return c.cache.Contains(validatorIndex)
    67  }
    68  
    69  // Clear removes all keys from the ValidatorCache.
    70  func (c *PublicKeyCache) Clear() {
    71  	c.cache.Purge()
    72  }