2020-03-05 06:19:35 +00:00
|
|
|
use crate::metrics;
|
|
|
|
use lru::LruCache;
|
2020-09-29 03:46:54 +00:00
|
|
|
use types::{beacon_state::CommitteeCache, Epoch, Hash256, ShufflingId};
|
2020-03-05 06:19:35 +00:00
|
|
|
|
|
|
|
/// The size of the LRU cache that stores committee caches for quicker verification.
|
|
|
|
///
|
|
|
|
/// Each entry should be `8 + 800,000 = 800,008` bytes in size with 100k validators. (8-byte hash +
|
|
|
|
/// 100k indices). Therefore, this cache should be approx `16 * 800,008 = 12.8 MB`. (Note: this
|
|
|
|
/// ignores a few extra bytes in the caches that should be insignificant compared to the indices).
|
|
|
|
const CACHE_SIZE: usize = 16;
|
|
|
|
|
|
|
|
/// Provides an LRU cache for `CommitteeCache`.
|
|
|
|
///
|
|
|
|
/// It has been named `ShufflingCache` because `CommitteeCacheCache` is a bit weird and looks like
|
|
|
|
/// a find/replace error.
|
|
|
|
pub struct ShufflingCache {
|
2020-09-29 03:46:54 +00:00
|
|
|
cache: LruCache<ShufflingId, CommitteeCache>,
|
2020-03-05 06:19:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl ShufflingCache {
|
|
|
|
pub fn new() -> Self {
|
|
|
|
Self {
|
|
|
|
cache: LruCache::new(CACHE_SIZE),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-29 03:46:54 +00:00
|
|
|
pub fn get(&mut self, key: &ShufflingId) -> Option<&CommitteeCache> {
|
|
|
|
let opt = self.cache.get(key);
|
2020-03-05 06:19:35 +00:00
|
|
|
|
|
|
|
if opt.is_some() {
|
|
|
|
metrics::inc_counter(&metrics::SHUFFLING_CACHE_HITS);
|
|
|
|
} else {
|
|
|
|
metrics::inc_counter(&metrics::SHUFFLING_CACHE_MISSES);
|
|
|
|
}
|
|
|
|
|
|
|
|
opt
|
|
|
|
}
|
|
|
|
|
2020-09-29 03:46:54 +00:00
|
|
|
pub fn contains(&self, key: &ShufflingId) -> bool {
|
|
|
|
self.cache.contains(key)
|
|
|
|
}
|
2020-03-05 06:19:35 +00:00
|
|
|
|
2020-09-29 03:46:54 +00:00
|
|
|
pub fn insert(&mut self, key: ShufflingId, committee_cache: &CommitteeCache) {
|
2020-03-05 06:19:35 +00:00
|
|
|
if !self.cache.contains(&key) {
|
|
|
|
self.cache.put(key, committee_cache.clone());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-09-29 03:46:54 +00:00
|
|
|
|
|
|
|
/// Contains the shuffling IDs for a beacon block.
|
|
|
|
pub struct BlockShufflingIds {
|
|
|
|
pub current: ShufflingId,
|
|
|
|
pub next: ShufflingId,
|
|
|
|
pub block_root: Hash256,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl BlockShufflingIds {
|
|
|
|
/// Returns the shuffling ID for the given epoch.
|
|
|
|
///
|
|
|
|
/// Returns `None` if `epoch` is prior to `self.current.shuffling_epoch`.
|
|
|
|
pub fn id_for_epoch(&self, epoch: Epoch) -> Option<ShufflingId> {
|
|
|
|
if epoch == self.current.shuffling_epoch {
|
|
|
|
Some(self.current.clone())
|
|
|
|
} else if epoch == self.next.shuffling_epoch {
|
|
|
|
Some(self.next.clone())
|
|
|
|
} else if epoch > self.next.shuffling_epoch {
|
|
|
|
Some(ShufflingId::from_components(epoch, self.block_root))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|