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

     1  package cache
     2  
     3  import (
     4  	lru "github.com/hashicorp/golang-lru"
     5  	slashpb "github.com/prysmaticlabs/prysm/proto/slashing"
     6  )
     7  
     8  var (
     9  	// highestAttCacheSize defines the max number of sets of highest attestation in cache.
    10  	highestAttCacheSize = 3000
    11  )
    12  
    13  // HighestAttestationCache is used to store per validator id highest attestation in cache.
    14  type HighestAttestationCache struct {
    15  	cache *lru.Cache
    16  }
    17  
    18  // NewHighestAttestationCache initializes the cache.
    19  func NewHighestAttestationCache(size int, onEvicted func(key interface{}, value interface{})) (*HighestAttestationCache, error) {
    20  	if size != 0 {
    21  		highestAttCacheSize = size
    22  	}
    23  	cache, err := lru.NewWithEvict(highestAttCacheSize, onEvicted)
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  	return &HighestAttestationCache{cache: cache}, nil
    28  }
    29  
    30  // Get returns an ok bool and the cached value for the requested validator id key, if any.
    31  func (c *HighestAttestationCache) Get(setKey uint64) (map[uint64]*slashpb.HighestAttestation, bool) {
    32  	item, exists := c.cache.Get(setKey)
    33  	if exists && item != nil {
    34  		return item.(map[uint64]*slashpb.HighestAttestation), true
    35  	}
    36  	return nil, false
    37  }
    38  
    39  // Set the response in the cache.
    40  func (c *HighestAttestationCache) Set(setKey uint64, highest *slashpb.HighestAttestation) {
    41  	set, ok := c.Get(setKey)
    42  	if ok {
    43  		set[highest.ValidatorId] = highest
    44  	} else {
    45  		set = map[uint64]*slashpb.HighestAttestation{
    46  			highest.ValidatorId: highest,
    47  		}
    48  		c.cache.Add(setKey, set)
    49  	}
    50  }
    51  
    52  // Delete removes a validator id from the cache and returns if it existed or not.
    53  // Performs the onEviction function before removal.
    54  func (c *HighestAttestationCache) Delete(setKey uint64) bool {
    55  	return c.cache.Remove(setKey)
    56  }
    57  
    58  // Has returns true if the key exists in the cache.
    59  func (c *HighestAttestationCache) Has(setKey uint64) bool {
    60  	return c.cache.Contains(setKey)
    61  }
    62  
    63  // Clear removes all keys from the ValidatorCache.
    64  func (c *HighestAttestationCache) Clear() {
    65  	c.cache.Purge()
    66  }
    67  
    68  // Purge removes all keys from cache and evicts all current data.
    69  func (c *HighestAttestationCache) Purge() {
    70  	log.Info("Saving all highest attestation cache data to DB, please wait for completion.")
    71  	c.cache.Purge()
    72  }