pub use crate::adapter::{ CHUNK_GRANDPARENT_ANCHOR_HEIGHT_OFFSET, EpochManagerAdapter, epoch_chunk_producers_for_shard, }; use crate::metrics::{ DYNAMIC_RESHARDING_SCHEDULED_EPOCH_HEIGHT, EARLY_KICKOUT_BLACKLIST_SIZE, EARLY_KICKOUT_CHUNK_PRODUCER_REASSIGNED, EARLY_KICKOUT_SAFETY_VALVE_FIRED, PROTOCOL_VERSION_NEXT, PROTOCOL_VERSION_VOTES, RESHARDING_ASSIGNMENT_STRATEGY, }; pub use crate::reward_calculator::NUM_SECONDS_IN_A_YEAR; pub use crate::reward_calculator::RewardCalculator; use epoch_info_aggregator::EpochInfoAggregator; use itertools::Itertools; use near_cache::SyncLruCache; use near_chain_configs::{Genesis, GenesisConfig}; use near_primitives::epoch_block_info::BlockInfo; use near_primitives::epoch_info::{EpochInfo, RngSeed}; use near_primitives::epoch_manager::{ AllEpochConfig, DynamicReshardingConfig, EpochConfig, EpochConfigStore, EpochSummary, ShardLayoutConfig, }; use near_primitives::errors::EpochError; use near_primitives::hash::CryptoHash; use near_primitives::shard_layout::{ShardLayout, ShardUId}; use near_primitives::sharding::ShardChunkHeader; use near_primitives::stateless_validation::validator_assignment::ChunkValidatorAssignments; use near_primitives::trie_split::TrieSplit; use near_primitives::types::validator_stake::ValidatorStake; use near_primitives::types::{ AccountId, ApprovalStake, Balance, BlockChunkValidatorStats, BlockHeight, ChunkStats, EpochId, EpochInfoProvider, NonZeroEpochHeight, ProtocolVersion, ShardId, ValidatorId, ValidatorInfoIdentifier, ValidatorKickoutReason, ValidatorStats, }; use near_primitives::utils::get_block_shard_id; use near_primitives::version::ProtocolFeature; use near_primitives::views::{ CurrentEpochValidatorInfo, EpochValidatorInfo, NextEpochValidatorInfo, ValidatorKickoutView, }; use near_store::adapter::StoreAdapter; use near_store::adapter::epoch_store::{EpochStoreAdapter, EpochStoreUpdateAdapter}; use near_store::{DBCol, Store}; use num_rational::BigRational; use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use primitive_types::U256; use reward_calculator::ValidatorOnlineThresholds; pub use shard_assignment::AssignmentStrategy; use std::collections::{BTreeMap, HashMap, HashSet}; #[cfg(feature = "test_features")] use std::marker::PhantomData; use std::path::Path; use std::sync::Arc; pub use validator_selection::proposals_to_epoch_info; use validator_stats::get_sortable_validator_online_ratio; mod adapter; pub mod epoch_info_aggregator; pub mod epoch_sync; mod genesis; mod metrics; mod reward_calculator; pub mod shard_assignment; pub mod shard_tracker; pub mod test_utils; #[cfg(test)] mod tests; mod validator_selection; mod validator_stats; const EPOCH_CACHE_SIZE: usize = 50; const CHUNK_VALIDATORS_CACHE_SIZE: usize = 1000; const CHUNK_PRODUCER_BLACKLIST_CACHE_SIZE: usize = 128; const AGGREGATOR_SAVE_PERIOD: u64 = 1000; const EARLY_KICKOUT_MIN_MISSES: u64 = 100; const EARLY_KICKOUT_PRODUCTION_THRESHOLD_NUMERATOR: u64 = 80; const EARLY_KICKOUT_PRODUCTION_THRESHOLD_DENOMINATOR: u64 = 100; /// Grace window at the start of each epoch: no chunk producer is blacklisted until the /// anchor is at least this many blocks into the epoch. Absorbs upgrade-restart downtime. const EARLY_KICKOUT_EPOCH_GRACE_BLOCKS: u64 = 1000; /// Miss floor for the blacklist. Always the production constant unless this is a /// `test_features` build; see the `early_kickout_test_thresholds` module below. #[cfg(not(feature = "test_features"))] fn early_kickout_min_misses() -> u64 { EARLY_KICKOUT_MIN_MISSES } /// Start-of-epoch grace. Always the production constant unless this is a `test_features` /// build; see the `early_kickout_test_thresholds` module below. #[cfg(not(feature = "test_features"))] fn early_kickout_epoch_grace_blocks() -> u64 { EARLY_KICKOUT_EPOCH_GRACE_BLOCKS } /// Test-only overrides for the two early-kickout thresholds. /// /// Misses accumulate from epoch start, but the blacklist stays suppressed until the anchor is /// past the 1000-block grace, so the earliest exclusion on a real chain is ~1000 blocks in, /// which a test-loop chain cannot afford. These knobs let a test shrink both so the gate /// trips in tens of blocks. The thread-local defaults are the production constants, so /// any build carrying `test_features` (the CI test runs enable it workspace-wide) /// behaves identically until a test explicitly installs an override. /// /// Thread-local, not process-global, on purpose: `cargo test` runs test functions on /// parallel threads within one process, while a test-loop chain executes entirely on the /// thread that drives its event loop. Thread-local state therefore isolates each test /// exactly, where a global would leak a lowered grace into every concurrently running /// test-loop test and silently start reassigning producers there. #[cfg(feature = "test_features")] mod early_kickout_test_thresholds { use super::{EARLY_KICKOUT_EPOCH_GRACE_BLOCKS, EARLY_KICKOUT_MIN_MISSES}; use std::cell::Cell; thread_local! { static MIN_MISSES: Cell = const { Cell::new(EARLY_KICKOUT_MIN_MISSES) }; static EPOCH_GRACE_BLOCKS: Cell = const { Cell::new(EARLY_KICKOUT_EPOCH_GRACE_BLOCKS) }; } pub(super) fn min_misses() -> u64 { MIN_MISSES.get() } pub(super) fn epoch_grace_blocks() -> u64 { EPOCH_GRACE_BLOCKS.get() } pub(super) fn swap(min_misses: u64, epoch_grace_blocks: u64) -> (u64, u64) { (MIN_MISSES.replace(min_misses), EPOCH_GRACE_BLOCKS.replace(epoch_grace_blocks)) } } #[cfg(feature = "test_features")] fn early_kickout_min_misses() -> u64 { early_kickout_test_thresholds::min_misses() } #[cfg(feature = "test_features")] fn early_kickout_epoch_grace_blocks() -> u64 { early_kickout_test_thresholds::epoch_grace_blocks() } /// Restores the early-kickout thresholds this thread had before /// [`set_early_kickout_thresholds_for_testing`] was called. Dropping on unwind is what /// keeps a panicking test from leaking its lowered thresholds into the next test when /// the harness reuses the thread (`--test-threads=1`). /// /// Deliberately `!Send`: the override lives in thread-local state, so a guard dropped on /// a different thread would restore THAT thread's thresholds and leave the installing /// thread lowered forever — exactly the leak the guard exists to prevent. #[cfg(feature = "test_features")] #[must_use = "the override only lasts as long as this guard is alive"] pub struct EarlyKickoutThresholdGuard { prev_min_misses: u64, prev_epoch_grace_blocks: u64, _not_send: PhantomData<*const ()>, } #[cfg(feature = "test_features")] impl Drop for EarlyKickoutThresholdGuard { fn drop(&mut self) { early_kickout_test_thresholds::swap(self.prev_min_misses, self.prev_epoch_grace_blocks); } } /// Overrides the early-kickout thresholds for the CALLING THREAD, which for a test-loop /// test is the thread the whole chain runs on. `None` keeps the production constant. Call /// before creating any `EpochManager` and hold the returned guard for the whole test. Every /// thread that uses a manager must keep the same thresholds, because the blacklist cache does /// not include them. /// /// Never expose this through a runtime control (e.g. an adversarial RPC): overriding on a /// live node would give each thread its own consensus math. #[cfg(feature = "test_features")] pub fn set_early_kickout_thresholds_for_testing( min_misses: Option, epoch_grace_blocks: Option, ) -> EarlyKickoutThresholdGuard { let (prev_min_misses, prev_epoch_grace_blocks) = early_kickout_test_thresholds::swap( min_misses.unwrap_or(EARLY_KICKOUT_MIN_MISSES), epoch_grace_blocks.unwrap_or(EARLY_KICKOUT_EPOCH_GRACE_BLOCKS), ); EarlyKickoutThresholdGuard { prev_min_misses, prev_epoch_grace_blocks, _not_send: PhantomData } } /// The guard's restore-on-drop is itself a safety mechanism (it is what keeps a panicking /// test from leaking lowered thresholds into the next test on the same thread), so it gets /// direct coverage here rather than relying on the e2e tests' happy path. #[cfg(all(test, feature = "test_features"))] mod early_kickout_threshold_override_tests { use super::{ EARLY_KICKOUT_EPOCH_GRACE_BLOCKS, EARLY_KICKOUT_MIN_MISSES, early_kickout_epoch_grace_blocks, early_kickout_min_misses, set_early_kickout_thresholds_for_testing, }; use std::panic::{AssertUnwindSafe, catch_unwind}; #[test] fn test_override_and_restore() { assert_eq!(early_kickout_min_misses(), EARLY_KICKOUT_MIN_MISSES); assert_eq!(early_kickout_epoch_grace_blocks(), EARLY_KICKOUT_EPOCH_GRACE_BLOCKS); { let _guard = set_early_kickout_thresholds_for_testing(Some(5), Some(20)); assert_eq!(early_kickout_min_misses(), 5); assert_eq!(early_kickout_epoch_grace_blocks(), 20); } assert_eq!(early_kickout_min_misses(), EARLY_KICKOUT_MIN_MISSES); assert_eq!(early_kickout_epoch_grace_blocks(), EARLY_KICKOUT_EPOCH_GRACE_BLOCKS); } #[test] fn test_none_keeps_production_constant() { let _guard = set_early_kickout_thresholds_for_testing(Some(7), None); assert_eq!(early_kickout_min_misses(), 7); assert_eq!(early_kickout_epoch_grace_blocks(), EARLY_KICKOUT_EPOCH_GRACE_BLOCKS); } #[test] fn test_nested_overrides_restore_lifo() { let _outer = set_early_kickout_thresholds_for_testing(Some(5), Some(20)); { let _inner = set_early_kickout_thresholds_for_testing(Some(3), Some(10)); assert_eq!(early_kickout_min_misses(), 3); assert_eq!(early_kickout_epoch_grace_blocks(), 10); } assert_eq!(early_kickout_min_misses(), 5); assert_eq!(early_kickout_epoch_grace_blocks(), 20); } #[test] fn test_panic_unwind_restores_thresholds() { let result = catch_unwind(AssertUnwindSafe(|| { let _guard = set_early_kickout_thresholds_for_testing(Some(5), Some(20)); panic!("panic with a live guard"); })); assert!(result.is_err()); assert_eq!(early_kickout_min_misses(), EARLY_KICKOUT_MIN_MISSES); assert_eq!(early_kickout_epoch_grace_blocks(), EARLY_KICKOUT_EPOCH_GRACE_BLOCKS); } } /// Per-shard observability for the blacklist computation. Emitted once at the /// seeder (the production write path); the accessor recomputes on every read and /// must not emit, or it would double-count. pub struct BlacklistShardStats { /// RAW pre-safety-valve count of producers that met the blacklist criteria. pub raw_candidate_count: usize, /// The kept least-bad producer when the safety valve fired (all distinct producers /// on the shard were candidates, so exactly one least-bad producer was kept), else /// None. Carries the id so the seeder can log it without recomputing (the accessor /// must not log). pub kept: Option, } impl BlacklistShardStats { /// The keep-one safety valve fired iff a producer was kept. pub fn safety_valve_fired(&self) -> bool { self.kept.is_some() } } /// Result of [`compute_chunk_producer_blacklist`]: the applied blacklist plus /// per-shard stats for observability. pub struct ChunkProducerBlacklist { pub blacklist: HashMap>, /// Only shards where at least one producer was a candidate (raw_candidate_count > 0). pub shard_stats: HashMap, } impl ChunkProducerBlacklist { fn empty() -> Self { ChunkProducerBlacklist { blacklist: HashMap::new(), shard_stats: HashMap::new() } } } /// The block a set of chunks is anchored at, plus its last-final block. The last-final block /// is the kickout blacklist's basis. See [`EpochManager::seed_chunk_producers`]. struct SeedAnchor { hash: CryptoHash, height: BlockHeight, final_hash: CryptoHash, final_height: BlockHeight, } /// The anchor's own epoch, whose validator set the anchored chunks are sampled from. struct SampleEpoch<'a> { epoch_id: &'a EpochId, epoch_info: &'a EpochInfo, shard_layout: &'a ShardLayout, } /// Per-shard chunk-producer blacklist from the aggregator's shard_tracker stats. /// A validator is blacklisted on a shard when, within the current epoch: /// - missed >= EARLY_KICKOUT_MIN_MISSES (missed = expected - produced) /// - produced * 100 < expected * 80 (production ratio < 80%) /// Safety valve: if blacklisting would remove every distinct producer on a shard, /// exactly one least-bad producer (highest produced/expected ratio) is kept eligible. pub fn compute_chunk_producer_blacklist( shard_tracker: &HashMap>, epoch_info: &EpochInfo, shard_layout: &ShardLayout, ) -> ChunkProducerBlacklist { let mut blacklist = HashMap::new(); let mut shard_stats = HashMap::new(); for (shard_id, validators) in shard_tracker { let Ok(shard_index) = shard_layout.get_shard_index(*shard_id) else { continue }; let Some(settlement) = epoch_info.chunk_producers_settlement().get(shard_index) else { continue; }; // distinct chunk producers for this shard. shard_tracker also holds endorsement-only // entries (chunk validators that never produced); they must not be blacklist candidates // or skew the safety-valve denominator. let producers: HashSet = settlement.iter().copied().collect(); let mut blacklisted = HashSet::new(); for (&validator_id, stats) in validators { if !producers.contains(&validator_id) { continue; } let (produced, expected) = (stats.produced(), stats.expected()); let missed = expected.saturating_sub(produced); // u128 keeps the ratio comparison overflow-proof. if missed >= early_kickout_min_misses() && (produced as u128) * (EARLY_KICKOUT_PRODUCTION_THRESHOLD_DENOMINATOR as u128) < (expected as u128) * (EARLY_KICKOUT_PRODUCTION_THRESHOLD_NUMERATOR as u128) { blacklisted.insert(validator_id); } } let raw_candidate_count = blacklisted.len(); if raw_candidate_count == 0 { continue; } // Safety valve: never blacklist every distinct producer on a shard. When all of // them are candidates, keep exactly one eligible = LEAST-BAD (highest // produced/expected). Pick over `blacklisted` (a subset of shard_tracker, so stats // exist) — NEVER index `producers`. Deterministic TOTAL order (consensus-critical, // identical on every node, never HashSet iteration order): let kept = if blacklisted.len() == producers.len() { let keep = *blacklisted .iter() .max_by(|a, b| { let (sa, sb) = (&validators[*a], &validators[*b]); let (pa, ea) = (sa.produced() as u128, sa.expected() as u128); let (pb, eb) = (sb.produced() as u128, sb.expected() as u128); (pa * eb) .cmp(&(pb * ea)) // higher produced/expected ratio (integer cross-mult, no float) .then(eb.cmp(&ea)) // tiebreak: fewer expected .then((**b).cmp(&**a)) // tiebreak: lower validator_id }) .expect("safety-valve branch: blacklisted is non-empty"); blacklisted.remove(&keep); Some(keep) } else { None }; shard_stats.insert(*shard_id, BlacklistShardStats { raw_candidate_count, kept }); // A 1-producer shard becomes empty after keep-one -> nothing to blacklist, skip. if !blacklisted.is_empty() { blacklist.insert(*shard_id, blacklisted); } } ChunkProducerBlacklist { blacklist, shard_stats } } /// Per-shard blacklist for `target_epoch_id` (the anchor's own epoch), or empty when either: /// /// - The aggregator belongs to a different epoch: the anchor's last-final block is still in /// the previous epoch, which holds for the first two anchors of an epoch at steady /// finality and longer while finality lags. The two bases legitimately differ — the stats /// must be finality-derived so every node seeds byte-identical rows, while the sample /// epoch must be the anchor's own epoch because the protocol ties a chunk's producer to /// the chunk's epoch. Cross-epoch stats would also be meaningless: `ValidatorId` is an /// epoch-local index, so the previous epoch's stats would blacklist whoever happens to /// occupy those indices in the target epoch. /// - The basis is still within the start-of-epoch grace window (`blocks_into_epoch` = /// last-final height − the aggregator's epoch-start height). /// /// Shared by the record-block seeder and the `get_chunk_producer_blacklist` accessor so the /// reset and grace checks can't drift between them. pub(crate) fn blacklist_for_epoch( aggregator: &EpochInfoAggregator, target_epoch_id: &EpochId, epoch_info: &EpochInfo, shard_layout: &ShardLayout, blocks_into_epoch: BlockHeight, ) -> ChunkProducerBlacklist { // Both checks are redundant in production: `chunk_producer_blacklist_at_anchor` returns // on them before its walk. Kept as defense in depth for direct callers. if aggregator.epoch_id != *target_epoch_id { return ChunkProducerBlacklist::empty(); } if blocks_into_epoch < early_kickout_epoch_grace_blocks() { return ChunkProducerBlacklist::empty(); } compute_chunk_producer_blacklist(&aggregator.shard_tracker, epoch_info, shard_layout) } /// Result of [`EpochManager::record_block_info`]: the writes to commit, plus what callers /// need to know about the block before the commit. #[must_use] pub struct EpochManagerUpdate { pub store_update: EpochStoreUpdateAdapter<'static>, /// Set when the block is the last block of its epoch, i.e. when /// `is_next_block_epoch_start` holds for it. pub epoch_end: Option, } /// Protocol versions of the two epochs after the epoch that a block ends. pub struct EpochEnd { pub next_epoch_protocol_version: ProtocolVersion, pub next_next_epoch_protocol_version: ProtocolVersion, } /// In the current architecture, various components have access to the same /// shared mutable instance of [`EpochManager`]. This handle manages locking /// required for such access. /// /// It's up to the caller to ensure that there are no logical races when using /// `.write` access. #[derive(Clone)] pub struct EpochManagerHandle { inner: Arc>, } impl EpochManagerHandle { pub fn write(&self) -> RwLockWriteGuard<'_, EpochManager> { self.inner.write() } pub fn read(&self) -> RwLockReadGuard<'_, EpochManager> { self.inner.read() } } impl EpochInfoProvider for EpochManagerHandle { fn validator_stake( &self, epoch_id: &EpochId, account_id: &AccountId, ) -> Result, EpochError> { let epoch_manager = self.read(); let epoch_info = epoch_manager.get_epoch_info(epoch_id)?; Ok(epoch_info.get_validator_id(account_id).map(|id| epoch_info.validator_stake(*id))) } fn validator_total_stake(&self, epoch_id: &EpochId) -> Result { let epoch_manager = self.read(); let epoch_info = epoch_manager.get_epoch_info(epoch_id)?; Ok(epoch_info .validators_iter() .fold(Balance::ZERO, |sum, info| sum.checked_add(info.stake()).unwrap())) } fn minimum_stake(&self, prev_block_hash: &CryptoHash) -> Result { let epoch_manager = self.read(); epoch_manager.minimum_stake(prev_block_hash) } fn chain_id(&self) -> String { let epoch_manager = self.read(); epoch_manager.config.chain_id().into() } fn shard_layout(&self, epoch_id: &EpochId) -> Result { let epoch_manager = self.read(); epoch_manager.get_shard_layout(epoch_id) } } /// Tracks epoch information across different forks, such as validators. /// Note: that even after garbage collection, the data about genesis epoch should be in the store. pub struct EpochManager { store: EpochStoreAdapter, /// Current epoch config. config: AllEpochConfig, reward_calculator: RewardCalculator, /// Epoch validators ordered by `block_producer_settlement`. epoch_validators_ordered: SyncLruCache>, /// Unique validators ordered by `block_producer_settlement`. epoch_validators_ordered_unique: SyncLruCache>, /// Unique chunk producers. epoch_chunk_producers_unique: SyncLruCache>, /// Aggregator that keeps statistics about the current epoch. It’s data are /// synced up to the last final block. The information are updated by /// [`Self::update_epoch_info_aggregator_upto_final`] method. To get /// statistics up to a last block use /// [`Self::get_epoch_info_aggregator_upto_last`] method. epoch_info_aggregator: EpochInfoAggregator, /// Largest final height. Monotonically increasing. largest_final_height: BlockHeight, /// Cache for chunk_validators chunk_validators_cache: SyncLruCache<(EpochId, ShardId, BlockHeight), Arc>, /// Cache for chunk producer blacklists, keyed by last final block hash. Used to avoid /// repeated epoch walks when fork siblings share a last final block. chunk_producer_blacklists: SyncLruCache>, /// Counts loop iterations inside of aggregate_epoch_info_from method. /// Used for tests as a bit of white-box testing. #[cfg(test)] epoch_info_aggregator_loop_counter: std::sync::atomic::AtomicUsize, } impl EpochManager { /// Creates a new instance of `EpochManager` from the given `store`, `genesis_config`, and `home_dir`. /// For production environments such as mainnet ant testnet, the epoch config files will be ignored. /// In the test environment, the epoch config files will be loaded from the `home_dir` if it is not `None`. pub fn new_arc_handle( store: Store, genesis_config: &GenesisConfig, home_dir: Option<&Path>, ) -> Arc { let chain_id = genesis_config.chain_id.as_str(); if chain_id == near_primitives::chains::MAINNET || chain_id == near_primitives::chains::TESTNET { // Do not load epoch config files for mainnet and testnet. let epoch_config_store = EpochConfigStore::for_chain_id(chain_id, None).unwrap(); return Self::new_arc_handle_from_epoch_config_store( store, genesis_config, epoch_config_store, ); } let config_dir = home_dir.map(|home_dir| home_dir.join("epoch_configs")); let epoch_config_store = if config_dir.as_ref().map_or(false, |dir| dir.exists()) { EpochConfigStore::for_chain_id(chain_id, config_dir).unwrap() } else if chain_id.starts_with("test-chain-") { let epoch_config = EpochConfig::from(genesis_config); EpochConfigStore::test(BTreeMap::from_iter(vec![( genesis_config.protocol_version, Arc::new(epoch_config), )])) } else { let epoch_config = Genesis::test_epoch_config( genesis_config.num_block_producer_seats, genesis_config.shard_layout.clone(), genesis_config.epoch_length, ); EpochConfigStore::test(BTreeMap::from_iter(vec![( genesis_config.protocol_version, Arc::new(epoch_config), )])) }; Self::new_arc_handle_from_epoch_config_store(store, genesis_config, epoch_config_store) } pub fn new_arc_handle_from_epoch_config_store( store: Store, genesis_config: &GenesisConfig, epoch_config_store: EpochConfigStore, ) -> Arc { let store = store.epoch_store(); let epoch_length = genesis_config.epoch_length; let reward_calculator = RewardCalculator::new(genesis_config, epoch_length); // Sanity check: transaction validity period should not exceed two epochs. // This is required for the continuous epoch sync proof feature to work correctly. // // With continuous epoch sync, we update the proof to epoch T-2 while processing first block in epoch T. // When a new node does epoch sync, it needs to have at least `transaction_validity_period` number // of block headers. // See function find_target_epoch_to_produce_proof_for for more details. for (protocol_version, epoch_config) in epoch_config_store.iter() { assert!( genesis_config.transaction_validity_period <= epoch_config.epoch_length * 2, "protocol_version: {}, tx_validity_period: {}, epoch_length: {}", protocol_version, genesis_config.transaction_validity_period, epoch_config.epoch_length ); } let all_epoch_config = AllEpochConfig::from_epoch_config_store( genesis_config.chain_id.as_str(), epoch_length, epoch_config_store, genesis_config.protocol_version, genesis_config.shard_layout.clone(), ); Arc::new( Self::new(store, all_epoch_config, reward_calculator, genesis_config.validators()) .unwrap() .into_handle(), ) } pub fn new( store: EpochStoreAdapter, config: AllEpochConfig, reward_calculator: RewardCalculator, validators: Vec, ) -> Result { let epoch_info_aggregator = store.get_epoch_info_aggregator().unwrap_or_default(); let mut epoch_manager = EpochManager { store, config, reward_calculator, epoch_validators_ordered: SyncLruCache::new(EPOCH_CACHE_SIZE), epoch_validators_ordered_unique: SyncLruCache::new(EPOCH_CACHE_SIZE), epoch_chunk_producers_unique: SyncLruCache::new(EPOCH_CACHE_SIZE), chunk_validators_cache: SyncLruCache::new(CHUNK_VALIDATORS_CACHE_SIZE), chunk_producer_blacklists: SyncLruCache::new(CHUNK_PRODUCER_BLACKLIST_CACHE_SIZE), epoch_info_aggregator, #[cfg(test)] epoch_info_aggregator_loop_counter: Default::default(), largest_final_height: 0, }; if !epoch_manager.has_epoch_info(&EpochId::default())? { epoch_manager.initialize_genesis_epoch_info(validators)?; } Ok(epoch_manager) } pub fn into_handle(self) -> EpochManagerHandle { let inner = Arc::new(RwLock::new(self)); EpochManagerHandle { inner } } pub fn init_after_epoch_sync( &mut self, store_update: &mut EpochStoreUpdateAdapter, prev_epoch_first_block_info: &BlockInfo, prev_epoch_prev_last_block_info: &BlockInfo, prev_epoch_last_block_info: &BlockInfo, prev_epoch_id: &EpochId, prev_epoch_info: &EpochInfo, epoch_id: &EpochId, epoch_info: &EpochInfo, next_epoch_id: &EpochId, next_epoch_info: &EpochInfo, ) { // TODO(#11931): We need to initialize the aggregator to the previous epoch, because // we move the aggregator forward in the previous epoch we do not have previous epoch's // blocks to compute the aggregator data. See issue for details. Consider a cleaner way. self.epoch_info_aggregator = EpochInfoAggregator::new(*prev_epoch_id, *prev_epoch_prev_last_block_info.prev_hash()); store_update.set_epoch_info_aggregator(&self.epoch_info_aggregator); // Epoch sync replaces the chain data used by these blacklists. self.chunk_producer_blacklists.lock().clear(); store_update.set_block_info(prev_epoch_first_block_info); store_update.set_block_info(prev_epoch_prev_last_block_info); store_update.set_block_info(prev_epoch_last_block_info); store_update.set_epoch_info(prev_epoch_id, prev_epoch_info); store_update.set_epoch_info(epoch_id, epoch_info); store_update.set_epoch_info(next_epoch_id, next_epoch_info); } /// When computing validators to kickout, we exempt some validators first so that /// the total stake of exempted validators exceed a threshold. This is to make sure /// we don't kick out too many validators in case of network instability. /// We also make sure that these exempted validators were not kicked out in the last epoch, /// so it is guaranteed that they will stay as validators after this epoch. /// /// `accounts_sorted_by_online_ratio`: Validator accounts sorted by online ratio in ascending order. fn compute_exempted_kickout( epoch_info: &EpochInfo, accounts_sorted_by_online_ratio: &Vec, total_stake: Balance, exempt_perc: u8, prev_validator_kickout: &HashMap, ) -> HashSet { // We want to make sure the total stake of validators that will be kicked out in this epoch doesn't exceed // config.validator_max_kickout_stake_ratio of total stake. // To achieve that, we sort all validators by their average uptime (average of block and chunk // uptime) and add validators to `exempted_validators` one by one, from high uptime to low uptime, // until the total excepted stake exceeds the ratio of total stake that we need to keep. // Later when we perform the check to kick out validators, we don't kick out validators in // exempted_validators. let mut exempted_validators = HashSet::new(); let min_keep_stake = Balance::from_yoctonear( (U256::from(total_stake.as_yoctonear()) * U256::from(exempt_perc as u128) / U256::from(100u128)) .as_u128(), ); let mut exempted_stake = Balance::ZERO; for account_id in accounts_sorted_by_online_ratio.into_iter().rev() { if exempted_stake >= min_keep_stake { break; } if !prev_validator_kickout.contains_key(account_id) { let validator_stake = epoch_info .get_validator_by_account(account_id) .map(|v| v.stake()) .unwrap_or_default(); exempted_stake = exempted_stake.checked_add(validator_stake).unwrap(); exempted_validators.insert(account_id.clone()); } } exempted_validators } /// Computes the set of validators to reward with stats and validators to kick out with reason. /// /// # Parameters /// epoch_info /// block_validator_tracker /// chunk_validator_tracker /// /// slashed: set of slashed validators /// prev_validator_kickout: previously kicked out /// /// # Returns /// (set of validators to reward with stats, set of validators to kickout) /// /// - Slashed validators are ignored (they are handled separately) /// - The total stake of validators that will be kicked out will not exceed /// config.validator_max_kickout_stake_perc of total stake of all validators. This is /// to ensure we don't kick out too many validators in case of network instability. /// - A validator is kicked out if he produced too few blocks or chunks /// - If all validators are either previously kicked out or to be kicked out, we choose one not to /// kick out fn compute_validators_to_reward_and_kickout( config: &EpochConfig, epoch_info: &EpochInfo, block_validator_tracker: &HashMap, chunk_stats_tracker: &HashMap>, spice_endorsement_tracker: &HashMap, prev_validator_kickout: &HashMap, ) -> (HashMap, HashMap) { let block_producer_kickout_threshold = config.block_producer_kickout_threshold; let chunk_producer_kickout_threshold = config.chunk_producer_kickout_threshold; let chunk_validator_only_kickout_threshold = config.chunk_validator_only_kickout_threshold; let mut validator_block_chunk_stats = HashMap::new(); let mut total_stake = Balance::ZERO; let mut maximum_block_prod = 0; let mut max_validator = None; for (i, v) in epoch_info.validators_iter().enumerate() { let account_id = v.account_id(); let block_stats = block_validator_tracker .get(&(i as u64)) .unwrap_or(&ValidatorStats { expected: 0, produced: 0 }) .clone(); let mut chunk_stats = ChunkStats::default(); for (_, tracker) in chunk_stats_tracker { if let Some(stat) = tracker.get(&(i as u64)) { *chunk_stats.expected_mut() += stat.expected(); *chunk_stats.produced_mut() += stat.produced(); chunk_stats.endorsement_stats_mut().produced += stat.endorsement_stats().produced; chunk_stats.endorsement_stats_mut().expected += stat.endorsement_stats().expected; } } // On spice epochs endorsements are not embedded per-shard, so the // per-shard tracker above is empty; the endorsement stats come from // the epoch's last block header instead. if let Some(stat) = spice_endorsement_tracker.get(&(i as u64)) { chunk_stats.endorsement_stats_mut().produced += stat.produced; chunk_stats.endorsement_stats_mut().expected += stat.expected; } total_stake = total_stake.checked_add(v.stake()).unwrap(); let is_already_kicked_out = prev_validator_kickout.contains_key(account_id); if (max_validator.is_none() || block_stats.produced > maximum_block_prod) && !is_already_kicked_out { maximum_block_prod = block_stats.produced; max_validator = Some(account_id.clone()); } validator_block_chunk_stats .insert(account_id.clone(), BlockChunkValidatorStats { block_stats, chunk_stats }); } // Compares validator accounts by applying comparators in the following order: // First by online ratio, if equal then by stake, if equal then by account id. let validator_comparator = |left: &(BigRational, &AccountId), right: &(BigRational, &AccountId)| { let cmp_online_ratio = left.0.cmp(&right.0); cmp_online_ratio.then_with(|| { // Note: The unwrap operations below must not fail because the accounts ids are // taken from the validators in the same epoch info above. let cmp_stake = epoch_info .get_validator_stake(left.1) .unwrap() .cmp(&epoch_info.get_validator_stake(right.1).unwrap()); cmp_stake.then_with(|| { let cmp_account_id = left.1.cmp(&right.1); cmp_account_id }) }) }; let mut sorted_validators = validator_block_chunk_stats .iter() .map(|(account, stats)| (get_sortable_validator_online_ratio(stats), account)) .collect_vec(); sorted_validators.sort_by(validator_comparator); let accounts_sorted_by_online_ratio = sorted_validators.into_iter().map(|(_, account)| account.clone()).collect_vec(); let exempt_perc = 100_u8.checked_sub(config.validator_max_kickout_stake_perc).unwrap_or_default(); let exempted_validators = Self::compute_exempted_kickout( epoch_info, &accounts_sorted_by_online_ratio, total_stake, exempt_perc, prev_validator_kickout, ); let mut all_kicked_out = true; let mut validator_kickout = HashMap::new(); for (account_id, stats) in &validator_block_chunk_stats { if exempted_validators.contains(account_id) { all_kicked_out = false; continue; } if stats.block_stats.less_than(block_producer_kickout_threshold) { validator_kickout.insert( account_id.clone(), ValidatorKickoutReason::NotEnoughBlocks { produced: stats.block_stats.produced, expected: stats.block_stats.expected, }, ); } if stats.chunk_stats.production_stats().less_than(chunk_producer_kickout_threshold) { validator_kickout.entry(account_id.clone()).or_insert_with(|| { ValidatorKickoutReason::NotEnoughChunks { produced: stats.chunk_stats.produced(), expected: stats.chunk_stats.expected(), } }); } let chunk_validator_only = stats.block_stats.expected == 0 && stats.chunk_stats.expected() == 0; if chunk_validator_only && stats .chunk_stats .endorsement_stats() .less_than(chunk_validator_only_kickout_threshold) { validator_kickout.entry(account_id.clone()).or_insert_with(|| { ValidatorKickoutReason::NotEnoughChunkEndorsements { produced: stats.chunk_stats.endorsement_stats().produced, expected: stats.chunk_stats.endorsement_stats().expected, } }); } let is_already_kicked_out = prev_validator_kickout.contains_key(account_id); if !validator_kickout.contains_key(account_id) { if !is_already_kicked_out { all_kicked_out = false; } } } if all_kicked_out { tracing::info!(target: "epoch_manager", ?max_validator, "we are about to kick out all validators in the next two epochs, so we are going to save one"); if let Some(validator) = max_validator { validator_kickout.remove(&validator); } } (validator_block_chunk_stats, validator_kickout) } fn collect_blocks_info( &self, last_block_info: &Arc, ) -> Result { let epoch_info = self.get_epoch_info(last_block_info.epoch_id())?; let next_epoch_id = self.get_next_epoch_id_from_info(last_block_info)?; let next_epoch_info = self.get_epoch_info(&next_epoch_id)?; let EpochInfoAggregator { block_tracker: block_validator_tracker, shard_tracker: chunk_validator_tracker, all_proposals, version_tracker, .. } = self.epoch_info_aggregator_upto_block(Arc::clone(last_block_info))?; let mut proposals = vec![]; let total_block_producer_stake: Balance = epoch_info .block_producers_settlement() .iter() .copied() .collect::>() .iter() .fold(Balance::ZERO, |sum, &id| { sum.checked_add(epoch_info.validator_stake(id)).unwrap() }); // Next protocol version calculation. // Implements https://github.com/near/NEPs/blob/master/specs/ChainSpec/Upgradability.md let mut versions = HashMap::new(); for (validator_id, version) in &version_tracker { let (validator_id, version) = (*validator_id, *version); let stake = epoch_info.validator_stake(validator_id); let version_entry = versions.entry(version).or_insert(Balance::ZERO); *version_entry = version_entry.checked_add(stake).unwrap(); } PROTOCOL_VERSION_VOTES.reset(); for (version, stake) in &versions { let stake_percent = (U256::from(stake.as_yoctonear()) * U256::from(100u128) / U256::from(total_block_producer_stake.as_yoctonear())) .as_u128() as i64; PROTOCOL_VERSION_VOTES.with_label_values(&[&version.to_string()]).set(stake_percent); tracing::info!(target: "epoch_manager", ?version, ?stake_percent, "protocol version voting"); } let protocol_version = next_epoch_info.protocol_version(); let config = self.config.for_protocol_version(protocol_version); // Note: non-deterministic iteration is fine here, there can be only one // version with large enough stake. let next_next_epoch_version = if let Some((version, stake)) = versions.into_iter().max_by_key(|&(_version, stake)| stake) { let numer = *config.protocol_upgrade_stake_threshold.numer() as u128; let denom = *config.protocol_upgrade_stake_threshold.denom() as u128; let threshold = Balance::from_yoctonear( (U256::from(total_block_producer_stake.as_yoctonear()) * U256::from(numer) / U256::from(denom)) .as_u128(), ); if stake > threshold { version } else { protocol_version } } else { protocol_version }; PROTOCOL_VERSION_NEXT.set(next_next_epoch_version as i64); tracing::info!(target: "epoch_manager", ?next_next_epoch_version, "protocol version voting"); let mut validator_kickout = HashMap::new(); // Kickout validators voting for an old version. for (validator_id, version) in version_tracker { if version >= next_next_epoch_version { continue; } let validator = epoch_info.get_validator(validator_id); validator_kickout.insert( validator.take_account_id(), ValidatorKickoutReason::ProtocolVersionTooOld { version, network_version: next_next_epoch_version, }, ); } // Kickout unstaked validators. for (account_id, proposal) in all_proposals { if proposal.stake().is_zero() && !next_epoch_info .stake_change() .get(&account_id) .unwrap_or(&Balance::ZERO) .is_zero() { validator_kickout.insert(account_id, ValidatorKickoutReason::Unstaked); } proposals.push(proposal); } // The id of epoch T+1 is the hash of the last block of epoch T-1. let prev_epoch_last_block_hash = next_epoch_id.0; let prev_validator_kickout = next_epoch_info.validator_kickout(); // On spice epochs, chunk endorsements are accumulated per-validator on // the epoch's last block header rather than embedded per-shard. let spice_endorsement_tracker: HashMap = last_block_info .spice_chunk_endorsement_stats() .unwrap_or(&[]) .iter() .enumerate() .map(|(validator_id, stats)| { ( validator_id as ValidatorId, ValidatorStats { produced: u64::from(stats.produced), expected: u64::from(stats.expected), }, ) }) .collect(); let config = self.config.for_protocol_version(epoch_info.protocol_version()); // Compute kick outs for validators who are offline. let (validator_block_chunk_stats, kickout) = Self::compute_validators_to_reward_and_kickout( &config, &epoch_info, &block_validator_tracker, &chunk_validator_tracker, &spice_endorsement_tracker, prev_validator_kickout, ); validator_kickout.extend(kickout); tracing::debug!( target: "epoch_manager", ?proposals, ?validator_kickout, ?block_validator_tracker, ?chunk_validator_tracker, "all proposals, kickouts, block tracker, shard tracker" ); Ok(EpochSummary { prev_epoch_last_block_hash, all_proposals: proposals, validator_kickout, validator_block_chunk_stats, next_next_epoch_version, }) } /// Compute the shard layout for the epoch after the next one. /// If static layout is defined in `next_next_epoch_config`, that will be used. /// If dynamic resharding is enabled it will either: /// a) derive a new layout based on the split defined in `block_info`, or /// b) return `next_shard_layout` (if there is no split specified there). /// /// Parameters: /// - `current_epoch_config`: config for the current epoch (N) /// - `current_protocol_version`: protocol version for epoch N /// - `next_next_epoch_config`: config for epoch N+2 /// - `next_shard_layout`: shard layout for epoch N+1 /// - `block_info`: block info for the last block of epoch N pub fn next_next_shard_layout( &self, current_epoch_config: &EpochConfig, current_protocol_version: ProtocolVersion, next_next_epoch_config: &EpochConfig, next_shard_layout: &ShardLayout, block_info: &BlockInfo, ) -> Result { // We are checking `next_next_epoch_config` for the sake of compatibility: static // resharding operated under the assumption that shard layout for epoch X is stored // in epoch config for epoch X. This is different from dynamic resharding approach, // where resharding parameters stored in epoch config for epoch X determine the layout // for epoch X+2. // Dynamic resharding won't be enabled until epoch N+2, use the static layout. if let Some(shard_layout) = next_next_epoch_config.static_shard_layout() { return Ok(shard_layout); } // Dynamic resharding is not yet enabled, but will become enabled in epoch N+1 or N+2. // Re-use the layout for N+1, as no resharding could happen in this transitory phase. if current_epoch_config.dynamic_resharding_config().is_none() { return Ok(next_shard_layout.clone()); } let Some((shard_id, boundary_account)) = block_info.shard_split() else { return Ok(next_shard_layout.clone()); }; // Skip the split if the shard no longer exists in the next layout // (e.g. it was already split in a previous epoch). This should never happen // given the resharding cooldown invariant. if !next_shard_layout.shard_ids().any(|id| id == *shard_id) { tracing::warn!( target: "epoch_manager", ?shard_id, %boundary_account, "dynamic resharding: shard no longer exists in next layout, skipping split" ); return Ok(next_shard_layout.clone()); } tracing::info!( target: "epoch_manager", ?shard_id, %boundary_account, "dynamic resharding: shard selected for split, deriving new layout" ); // The layout being derived takes effect two epochs after the one being finalized. // Best-effort: a metrics-only lookup must not fail the layout derivation. if let Ok(epoch_info) = self.get_epoch_info(block_info.epoch_id()) { let scheduled_epoch_height = epoch_info.epoch_height() + 2; let shard_uid = ShardUId::from_shard_id_and_layout(*shard_id, next_shard_layout); DYNAMIC_RESHARDING_SCHEDULED_EPOCH_HEIGHT .with_label_values(&[shard_uid.to_string().as_str(), boundary_account.as_str()]) .set(scheduled_epoch_height as i64); } let new_layout = next_shard_layout .derive_v3(boundary_account.clone(), || { self.get_shard_layout_history(current_protocol_version, None) }) .map_err(|err| EpochError::ShardingError(err.to_string()))?; Ok(new_layout) } /// Get all static shard layouts from the given `latest_protocol_version` (inclusive) back to /// `earliest_protocol_version` (or genesis version if `None`), ordered from newest to oldest. /// Protocol versions for which dynamic resharding is enabled are skipped. fn get_shard_layout_history( &self, latest_protocol_version: ProtocolVersion, earliest_protocol_version: Option, ) -> Vec { let mut layouts = Vec::new(); let earliest_protocol_version = earliest_protocol_version.unwrap_or_else(|| self.config.genesis_protocol_version()); for version in (earliest_protocol_version..=latest_protocol_version).rev() { // Skip protocol versions with dynamic layout let Some(layout) = self.get_static_shard_layout_for_protocol_version(version) else { continue; }; // avoid duplicates if layout doesn't change if layouts.last() != Some(&layout) { layouts.push(layout); } } layouts } /// Checks if resharding can be scheduled in 2 epochs from now (assuming `block_hash` belongs /// to the current epoch), based on `min_epochs_between_resharding`. /// /// Returns `true` if no resharding occurred in the last `min_epochs_between_resharding` /// epochs (including the next one). fn can_reshard( &self, block_hash: &CryptoHash, min_epochs_between_resharding: NonZeroEpochHeight, ) -> Result { let block_info = self.get_block_info(block_hash)?; let next_epoch_id = self.get_next_epoch_id_from_info(&block_info)?; let next_epoch_info = self.get_epoch_info(&next_epoch_id)?; // last_resharding() returns `None` if no resharding happened since dynamic resharding // has been enabled. It is theoretically possible that a static resharding was scheduled // right before enabling dynamic resharding, but we assume this didn't happen. let can_reshard = next_epoch_info.last_resharding().is_none_or(|last_resharding| { next_epoch_info.epoch_height() - last_resharding >= min_epochs_between_resharding.get() }); Ok(can_reshard) } /// Finalize epoch (T), where `block_info` is its last block. /// Store ID and `EpochInfo` for epoch (T + 2). fn finalize_epoch( &self, store_update: &mut EpochStoreUpdateAdapter, block_info: &Arc, rng_seed: RngSeed, ) -> Result { let epoch_summary = self.collect_blocks_info(block_info)?; let epoch_info = self.get_epoch_info(block_info.epoch_id())?; let epoch_protocol_version = epoch_info.protocol_version(); let epoch_config = self.get_epoch_config(epoch_protocol_version); let validator_stake = epoch_info.validators_iter().map(|r| r.account_and_stake()).collect::>(); let next_epoch_id = self.get_next_epoch_id_from_info(block_info)?; let next_epoch_info = self.get_epoch_info(&next_epoch_id)?; store_update.set_epoch_validator_info(block_info.epoch_id(), &epoch_summary); let EpochSummary { all_proposals, validator_kickout, mut validator_block_chunk_stats, next_next_epoch_version, .. } = epoch_summary; let (validator_reward, minted_amount) = { // The id of epoch T+1 is the hash of the last block of epoch T-1. let last_block_in_last_epoch = self.get_block_info(&next_epoch_id.0)?; assert!(block_info.timestamp_nanosec() > last_block_in_last_epoch.timestamp_nanosec()); let epoch_duration = block_info.timestamp_nanosec() - last_block_in_last_epoch.timestamp_nanosec(); for (account_id, reason) in &validator_kickout { if matches!( reason, ValidatorKickoutReason::NotEnoughBlocks { .. } | ValidatorKickoutReason::NotEnoughChunks { .. } | ValidatorKickoutReason::NotEnoughChunkEndorsements { .. } ) { validator_block_chunk_stats.remove(account_id); } } // We use the chunk validator kickout threshold as the cutoff threshold for the // endorsement ratio to remap the ratio to 0 or 1. let online_thresholds = ValidatorOnlineThresholds { online_min_threshold: epoch_config.online_min_threshold, online_max_threshold: epoch_config.online_max_threshold, endorsement_cutoff_threshold: Some( epoch_config.chunk_validator_only_kickout_threshold, ), }; self.reward_calculator.calculate_reward( validator_block_chunk_stats, &validator_stake, *block_info.total_supply(), epoch_protocol_version, epoch_duration, online_thresholds, epoch_config.max_inflation_rate, ) }; let next_next_epoch_config = self.config.for_protocol_version(next_next_epoch_version); let next_shard_layout = self.get_shard_layout(&next_epoch_id)?; let next_next_shard_layout = self.next_next_shard_layout( &epoch_config, epoch_protocol_version, &next_next_epoch_config, &next_shard_layout, block_info, )?; let has_same_shard_layout = next_next_shard_layout == next_shard_layout; let last_resharding = (!has_same_shard_layout) .then(|| next_epoch_info.epoch_height() + 1) .or_else(|| next_epoch_info.last_resharding()); let strategy = AssignmentStrategy::select(&next_shard_layout, &next_next_shard_layout); RESHARDING_ASSIGNMENT_STRATEGY.with_label_values(&[strategy.metrics_label()]).inc(); let next_next_epoch_info = match proposals_to_epoch_info( &next_next_epoch_config, rng_seed, &next_epoch_info, all_proposals, validator_kickout, validator_reward, minted_amount, next_next_epoch_version, next_next_shard_layout.clone(), &strategy, last_resharding, ) { Ok(next_next_epoch_info) => next_next_epoch_info, Err(EpochError::ThresholdError { stake_sum, num_seats }) => { tracing::warn!(target: "epoch_manager", %stake_sum, %num_seats, "not enough stake for required number of seats (all validators tried to unstake?)"); let mut epoch_info = EpochInfo::clone(&next_epoch_info); *epoch_info.epoch_height_mut() += 1; epoch_info } Err(EpochError::NotEnoughValidators { num_validators, num_shards }) => { tracing::warn!(target: "epoch_manager", %num_validators, %num_shards, "not enough validators for required number of shards (all validators tried to unstake?)"); let mut epoch_info = EpochInfo::clone(&next_epoch_info); *epoch_info.epoch_height_mut() += 1; epoch_info } Err(err) => return Err(err), }; let next_next_epoch_id = EpochId(*block_info.hash()); tracing::debug!( target: "epoch_manager", next_next_epoch_height = %next_next_epoch_info.epoch_height(), ?next_next_epoch_id, next_next_protocol_version = %next_next_epoch_info.protocol_version(), ?next_next_shard_layout, ?next_next_epoch_config, ); // This epoch info is computed for the epoch after next (T+2), // where epoch_id of it is the hash of last block in this epoch (T). let epoch_end = EpochEnd { next_epoch_protocol_version: next_epoch_info.protocol_version(), next_next_epoch_protocol_version: next_next_epoch_info.protocol_version(), }; store_update.set_epoch_info(&next_next_epoch_id, &next_next_epoch_info); Ok(epoch_end) } pub fn record_block_info( &mut self, mut block_info: BlockInfo, rng_seed: RngSeed, ) -> Result { // Check that genesis block doesn't have any proposals. let prev_validator_proposals = block_info.proposals_iter().collect::>(); assert!(block_info.height() > 0 || prev_validator_proposals.is_empty()); tracing::debug!(target: "epoch_manager", height = block_info.height(), proposals = ?prev_validator_proposals, "record_block_info"); let current_hash = *block_info.hash(); let mut store_update = self.store.store_update(); let epoch_end; // A block that header sync recorded already has its rows; read its `EpochEnd` from them. if self.has_block_info(¤t_hash)? { epoch_end = self.get_epoch_end(¤t_hash)?; } else { if block_info.is_genesis() { // This is genesis block, we special case as new epoch. assert_eq!(block_info.proposals_iter().len(), 0); let pre_genesis_epoch_id = EpochId::default(); let genesis_epoch_info = self.get_epoch_info(&pre_genesis_epoch_id)?; let genesis_height = block_info.height(); store_update.set_block_info(&block_info); store_update.set_epoch_info(&EpochId(current_hash), &genesis_epoch_info); // Chunks anchored at genesis (height genesis + 2) belong to the // first real epoch (`EpochId::default()`), whose validator set is // the genesis epoch info; chunks at genesis + 1 and below have no // grandparent and use the canonical sampler. let genesis_shard_layout = self.get_shard_layout(&pre_genesis_epoch_id)?; self.seed_chunk_producers( &mut store_update, &SeedAnchor { hash: current_hash, height: genesis_height, final_hash: CryptoHash::default(), final_height: genesis_height, }, SampleEpoch { epoch_id: &pre_genesis_epoch_id, epoch_info: genesis_epoch_info.as_ref(), shard_layout: &genesis_shard_layout, }, )?; // Both epochs after genesis use the genesis epoch info, saved above. epoch_end = Some(EpochEnd { next_epoch_protocol_version: genesis_epoch_info.protocol_version(), next_next_epoch_protocol_version: genesis_epoch_info.protocol_version(), }); } else { let prev_block_info = self.get_block_info(block_info.prev_hash())?; let mut is_epoch_start = false; if prev_block_info.is_genesis() { // This is first real block, starts the new epoch. *block_info.epoch_id_mut() = EpochId::default(); *block_info.epoch_first_block_mut() = current_hash; is_epoch_start = true; } else if self.is_next_block_in_next_epoch(&prev_block_info)? { // Current block is in the new epoch, finalize the one in prev_block. *block_info.epoch_id_mut() = self.get_next_epoch_id_from_info(&prev_block_info)?; *block_info.epoch_first_block_mut() = current_hash; is_epoch_start = true; } else { // Same epoch as parent, copy epoch_id and epoch_start_height. *block_info.epoch_id_mut() = *prev_block_info.epoch_id(); *block_info.epoch_first_block_mut() = *prev_block_info.epoch_first_block(); } let block_info = Arc::new(block_info); // Save current block info. store_update.set_block_info(&block_info); // Seed chunk producers anchored at this block (chunks at height + 2) // so every driver (chain, replay, tests) records them; the aggregator // and the consensus reader read these rows for the block's grandchildren. { let epoch_id = *block_info.epoch_id(); let epoch_info = self.get_epoch_info(&epoch_id)?; let shard_layout = self.get_shard_layout(&epoch_id)?; self.seed_chunk_producers( &mut store_update, &SeedAnchor { hash: *block_info.hash(), height: block_info.height(), final_hash: *block_info.last_final_block_hash(), final_height: block_info.last_finalized_height(), }, SampleEpoch { epoch_id: &epoch_id, epoch_info: epoch_info.as_ref(), shard_layout: &shard_layout, }, )?; } if block_info.last_finalized_height() > self.largest_final_height { self.largest_final_height = block_info.last_finalized_height(); // Update epoch info aggregator. We only update the if // there is a change in the last final block. This way we // never need to rollback any information in // self.epoch_info_aggregator. self.update_epoch_info_aggregator_upto_final( block_info.last_final_block_hash(), &mut store_update, )?; } // If this is the last block in the epoch, finalize this epoch. epoch_end = if self.is_next_block_in_next_epoch(&block_info)? { Some(self.finalize_epoch(&mut store_update, &block_info, rng_seed)?) } else { None }; if is_epoch_start { store_update.set_epoch_start(block_info.epoch_id(), block_info.height()); } } } Ok(EpochManagerUpdate { store_update, epoch_end }) } /// [`EpochEnd`] of a block whose `BlockInfo` row is committed. fn get_epoch_end(&self, block_hash: &CryptoHash) -> Result, EpochError> { let block_info = self.get_block_info(block_hash)?; if !self.is_next_block_in_next_epoch(&block_info)? { return Ok(None); } let next_epoch_id = self.get_next_epoch_id_from_info(&block_info)?; let next_next_epoch_id = EpochId(*block_hash); Ok(Some(EpochEnd { next_epoch_protocol_version: self.get_epoch_info(&next_epoch_id)?.protocol_version(), next_next_epoch_protocol_version: self .get_epoch_info(&next_next_epoch_id)? .protocol_version(), })) } /// Returns settlement of all block producers in current epoch pub fn get_all_block_producers_settlement( &self, epoch_id: &EpochId, ) -> Result, EpochError> { self.epoch_validators_ordered.get_or_try_put(*epoch_id, |epoch_id| { let epoch_info = self.get_epoch_info(epoch_id)?; let result = epoch_info .block_producers_settlement() .iter() .map(|&validator_id| epoch_info.get_validator(validator_id)) .collect(); Ok(result) }) } /// Returns all unique block producers in current epoch sorted by account_id. pub fn get_all_block_producers_ordered( &self, epoch_id: &EpochId, ) -> Result, EpochError> { self.epoch_validators_ordered_unique.get_or_try_put(*epoch_id, |epoch_id| { let settlement = self.get_all_block_producers_settlement(epoch_id)?; let mut validators: HashSet = HashSet::default(); let result = settlement .iter() .filter(|validator_stake| { let account_id = validator_stake.account_id(); validators.insert(account_id.clone()) }) .cloned() .collect(); Ok(result) }) } /// Returns settlement of all chunk producers in the current epoch. pub fn get_all_chunk_producers( &self, epoch_id: &EpochId, ) -> Result, EpochError> { self.epoch_chunk_producers_unique.get_or_try_put(*epoch_id, |epoch_id| { let mut producers: HashSet = HashSet::default(); // Collect unique chunk producers. let epoch_info = self.get_epoch_info(epoch_id)?; for chunk_producers in epoch_info.chunk_producers_settlement() { producers.extend(chunk_producers); } Ok(producers.iter().map(|producer_id| epoch_info.get_validator(*producer_id)).collect()) }) } /// Returns the list of chunk_validators for the given shard_id and height and set of account ids. /// Generation of chunk_validators and their order is deterministic for given shard_id and height. /// We cache the generated chunk_validators. pub fn get_chunk_validator_assignments( &self, epoch_id: &EpochId, shard_id: ShardId, height: BlockHeight, ) -> Result, EpochError> { let cache_key = (*epoch_id, shard_id, height); if let Some(chunk_validators) = self.chunk_validators_cache.get(&cache_key) { return Ok(chunk_validators); } let requested_cache_key = cache_key; let mut result = None; let epoch_info = self.get_epoch_info(epoch_id)?; let shard_layout = self.get_shard_layout(epoch_id)?; let chunk_validators_per_shard = epoch_info.sample_chunk_validators(height); for (shard_index, chunk_validators) in chunk_validators_per_shard.into_iter().enumerate() { let chunk_validators = chunk_validators .into_iter() .map(|(validator_id, assignment_weight)| { (epoch_info.get_validator(validator_id).take_account_id(), assignment_weight) }) .collect(); let shard_id = shard_layout.get_shard_id(shard_index)?; let value = Arc::new(ChunkValidatorAssignments::new(chunk_validators)); let cache_key = (*epoch_id, shard_id, height); // Preserve the result on the off-chance that the cache is fully // replaced before we finish populating it and try to read the // result from the cache. if cache_key == requested_cache_key { result = Some(Arc::clone(&value)); } self.chunk_validators_cache.put(cache_key, value); } if let Some(result) = result { return Ok(result); } Err(EpochError::ChunkValidatorSelectionError(format!( "Invalid shard ID {} for height {}, epoch {:?} for chunk validation", shard_id, height, epoch_id, ))) } pub fn get_all_block_approvers_ordered( &self, parent_hash: &CryptoHash, current_epoch_id: EpochId, next_epoch_id: EpochId, ) -> Result, EpochError> { let mut settlement = self.get_all_block_producers_settlement(¤t_epoch_id)?.to_vec(); let settlement_epoch_boundary = settlement.len(); let block_info = self.get_block_info(parent_hash)?; if self.next_block_need_approvals_from_next_epoch(&block_info)? { settlement .extend(self.get_all_block_producers_settlement(&next_epoch_id)?.iter().cloned()); } let mut result = vec![]; let mut validators: HashMap = HashMap::default(); for (ord, validator_stake) in settlement.into_iter().enumerate() { let account_id = validator_stake.account_id(); match validators.get(account_id) { None => { validators.insert(account_id.clone(), result.len()); result .push(validator_stake.get_approval_stake(ord >= settlement_epoch_boundary)); } Some(old_ord) => { if ord >= settlement_epoch_boundary { result[*old_ord].stake_next_epoch = validator_stake.stake(); }; } }; } Ok(result) } /// Returns validator for given account id for given epoch. /// We don't require caller to know about EpochIds. Doesn't account for slashing. pub fn get_validator_by_account_id( &self, epoch_id: &EpochId, account_id: &AccountId, ) -> Result { let epoch_info = self.get_epoch_info(epoch_id)?; epoch_info .get_validator_by_account(account_id) .ok_or_else(|| EpochError::NotAValidator(account_id.clone(), *epoch_id)) } pub fn get_epoch_id(&self, block_hash: &CryptoHash) -> Result { Ok(*self.get_block_info(block_hash)?.epoch_id()) } pub fn get_next_epoch_id(&self, block_hash: &CryptoHash) -> Result { let block_info = self.get_block_info(block_hash)?; self.get_next_epoch_id_from_info(&block_info) } pub fn get_epoch_info_from_hash( &self, block_hash: &CryptoHash, ) -> Result, EpochError> { let epoch_id = self.get_epoch_id(block_hash)?; self.get_epoch_info(&epoch_id) } /// Returns true if next block after the given `block_hash` is in the new epoch. pub fn is_next_block_epoch_start(&self, block_hash: &CryptoHash) -> Result { let block_info = self.get_block_info(block_hash)?; self.is_next_block_in_next_epoch(&block_info) } /// Like `is_next_block_epoch_start`, but works for blocks not yet in the store. /// Used during block production to decide whether to include `shard_split` in the header. /// /// Parameters: /// - `block_height`: the height of the block being produced /// - `parent_hash`: hash of the parent block (the block we're building on top of) /// - `last_final_block_hash`: hash of the last final block after this block is produced pub fn is_produced_block_last_in_epoch( &self, block_height: BlockHeight, parent_hash: &CryptoHash, last_final_block_hash: &CryptoHash, ) -> Result { // If the block being produced starts a new epoch, it can't also be the // last block of that epoch (the epoch just started). This check is // needed because `is_next_block_in_next_epoch_impl` uses the parent's // epoch boundaries and would incorrectly return true when the parent // is the last block of the previous epoch. if self.is_next_block_epoch_start(parent_hash)? { return Ok(false); } let last_final_block_height = self.get_block_info(last_final_block_hash)?.height(); let parent_info = self.get_block_info(parent_hash)?; let epoch_first_block_info = self.get_block_info(parent_info.epoch_first_block())?; self.is_next_block_in_next_epoch_impl( block_height, last_final_block_height, &epoch_first_block_info, ) } /// Like `is_produced_block_last_in_epoch`, but checks if the **next** block will be last /// in the epoch, not the one currently produced. Due to how block finalization works, this /// method **can produce false positives**, but will never return a false negative. /// Used to check if proposed_split should be computed for a shard. /// /// Parameters: /// - `block_height`: the height of the block being produced /// - `parent_hash`: hash of the parent block (the block we're building on top of) pub fn is_next_block_possibly_last_in_epoch( &self, block_height: BlockHeight, parent_hash: &CryptoHash, ) -> Result { // Avoid checking the wrong epoch if parent is the last block of an epoch. if self.is_next_block_epoch_start(parent_hash)? { return Ok(false); } let parent_info = self.get_block_info(parent_hash)?; let epoch_first_block_info = self.get_block_info(parent_info.epoch_first_block())?; // At block_height+1, last_final_height is at most block_height-1. // This can lead to false positive result, if previous block doesn't get finalized // before the next block is produced, but it will never give a false negative. let max_last_final_height = block_height.saturating_sub(1); self.is_next_block_in_next_epoch_impl( block_height + 1, max_last_final_height, &epoch_first_block_info, ) } pub fn get_next_epoch_id_from_prev_block( &self, parent_hash: &CryptoHash, ) -> Result { if self.is_next_block_epoch_start(parent_hash)? { // Because we ID epochs based on the last block of T - 2, this is ID for next next epoch. Ok(EpochId(*parent_hash)) } else { self.get_next_epoch_id(parent_hash) } } pub fn get_epoch_start_height( &self, block_hash: &CryptoHash, ) -> Result { let epoch_first_block = *self.get_block_info(block_hash)?.epoch_first_block(); Ok(self.get_block_info(&epoch_first_block)?.height()) } /// Compute stake return info based on the last block hash of the epoch that is just finalized /// return the hashmap of account id to max_of_stakes, which is used in the calculation of account /// updates. /// /// # Returns /// If successful, a triple of (hashmap of account id to max of stakes in the past three epochs, /// validator rewards in the last epoch, double sign slashing for the past epoch). pub fn compute_stake_return_info( &self, last_block_hash: &CryptoHash, ) -> Result<(HashMap, HashMap), EpochError> { let next_next_epoch_id = EpochId(*last_block_hash); let validator_reward = self.get_epoch_info(&next_next_epoch_id)?.validator_reward().clone(); let next_epoch_id = self.get_next_epoch_id(last_block_hash)?; let epoch_id = self.get_epoch_id(last_block_hash)?; tracing::debug!(target: "epoch_manager", epoch_id = ?next_next_epoch_id, prev_epoch_id = ?next_epoch_id, prev_prev_epoch_id= ?epoch_id, ); // Since stake changes for epoch T are stored in epoch info for T+2, the one stored by epoch_id // is the prev_prev_stake_change. let prev_prev_stake_change = self.get_epoch_info(&epoch_id)?.stake_change().clone(); let prev_stake_change = self.get_epoch_info(&next_epoch_id)?.stake_change().clone(); let stake_change = self.get_epoch_info(&next_next_epoch_id)?.stake_change().clone(); tracing::debug!(target: "epoch_manager", ?prev_prev_stake_change, ?prev_stake_change, ?stake_change, ); let all_stake_changes = prev_prev_stake_change.iter().chain(&prev_stake_change).chain(&stake_change); let all_keys: HashSet<&AccountId> = all_stake_changes.map(|(key, _)| key).collect(); let mut stake_info = HashMap::new(); for account_id in all_keys { let new_stake = *stake_change.get(account_id).unwrap_or(&Balance::ZERO); let prev_stake = *prev_stake_change.get(account_id).unwrap_or(&Balance::ZERO); let prev_prev_stake = *prev_prev_stake_change.get(account_id).unwrap_or(&Balance::ZERO); let max_of_stakes = vec![prev_prev_stake, prev_stake, new_stake].into_iter().max().unwrap(); stake_info.insert(account_id.clone(), max_of_stakes); } tracing::debug!(target: "epoch_manager", ?stake_info, ?validator_reward); Ok((stake_info, validator_reward)) } /// Get validators for current epoch and next epoch. /// WARNING: this function calls EpochManager::get_epoch_info_aggregator_upto_last /// underneath which can be very expensive. pub fn get_validator_info( &self, epoch_identifier: ValidatorInfoIdentifier, ) -> Result { let epoch_id = match epoch_identifier { ValidatorInfoIdentifier::EpochId(ref id) => *id, ValidatorInfoIdentifier::BlockHash(ref b) => self.get_epoch_id(b)?, }; let cur_epoch_info = self.get_epoch_info(&epoch_id)?; let epoch_height = cur_epoch_info.epoch_height(); let epoch_start_height = self.store.get_epoch_start(&epoch_id)?; // This ugly code arises because of the incompatible types between `block_tracker` in `EpochInfoAggregator` // and `validator_block_chunk_stats` in `EpochSummary`. Rust currently has no support for Either type // in std. let (current_validators, next_epoch_id, all_proposals) = match &epoch_identifier { ValidatorInfoIdentifier::EpochId(id) => { let cur_shard_layout = self.get_shard_layout(&epoch_id)?; let mut validator_to_shard = (0..cur_epoch_info.validators_len()) .map(|_| HashSet::default()) .collect::>>(); for (shard_index, validators) in cur_epoch_info.chunk_producers_settlement().into_iter().enumerate() { let shard_id = cur_shard_layout.get_shard_id(shard_index)?; for validator_id in validators { validator_to_shard[*validator_id as usize].insert(shard_id); } } let epoch_summary = self.store.get_epoch_validator_info(id)?; let cur_validators = cur_epoch_info .validators_iter() .enumerate() .map(|(validator_id, info)| { let validator_stats = epoch_summary .validator_block_chunk_stats .get(info.account_id()) .unwrap_or(&BlockChunkValidatorStats { block_stats: ValidatorStats { produced: 0, expected: 0 }, chunk_stats: ChunkStats { production: ValidatorStats { produced: 0, expected: 0 }, endorsement: ValidatorStats { produced: 0, expected: 0 }, }, }); let mut shards_produced = validator_to_shard[validator_id] .iter() .cloned() .collect::>(); shards_produced.sort(); // TODO: Compute the set of shards validated. let shards_endorsed = vec![]; let (account_id, public_key, stake) = info.destructure(); Ok(CurrentEpochValidatorInfo { is_slashed: false, // currently there is no slashing account_id, public_key, stake, // TODO: Maybe fill in the per shard info about the chunk produced for requests coming from RPC. num_produced_chunks_per_shard: vec![0; shards_produced.len()], num_expected_chunks_per_shard: vec![0; shards_produced.len()], num_produced_blocks: validator_stats.block_stats.produced, num_expected_blocks: validator_stats.block_stats.expected, num_produced_chunks: validator_stats.chunk_stats.produced(), num_expected_chunks: validator_stats.chunk_stats.expected(), num_produced_endorsements: validator_stats .chunk_stats .endorsement_stats() .produced, num_expected_endorsements: validator_stats .chunk_stats .endorsement_stats() .expected, // Same TODO as above for `num_produced_chunks_per_shard` num_produced_endorsements_per_shard: vec![0; shards_endorsed.len()], num_expected_endorsements_per_shard: vec![0; shards_endorsed.len()], shards_produced, shards_endorsed, }) }) .collect::, EpochError>>()?; ( cur_validators, EpochId(epoch_summary.prev_epoch_last_block_hash), epoch_summary.all_proposals.into_iter().map(Into::into).collect(), ) } ValidatorInfoIdentifier::BlockHash(h) => { // If we are here, `h` is hash of the latest block of the // current epoch. let aggregator = self.get_epoch_info_aggregator_upto_last(h)?; let cur_validators = cur_epoch_info .validators_iter() .enumerate() .map(|(validator_id, info)| { let block_stats = aggregator .block_tracker .get(&(validator_id as u64)) .unwrap_or(&ValidatorStats { produced: 0, expected: 0 }) .clone(); let mut chunks_stats_by_shard: HashMap = HashMap::new(); let mut chunk_stats = ChunkStats::default(); for (shard, tracker) in &aggregator.shard_tracker { if let Some(stats) = tracker.get(&(validator_id as u64)) { let produced = stats.produced(); let expected = stats.expected(); let endorsement_stats = stats.endorsement_stats(); *chunk_stats.produced_mut() += produced; *chunk_stats.expected_mut() += expected; chunk_stats.endorsement_stats_mut().produced += endorsement_stats.produced; chunk_stats.endorsement_stats_mut().expected += endorsement_stats.expected; let shard_stats = chunks_stats_by_shard.entry(*shard).or_default(); *shard_stats.produced_mut() += produced; *shard_stats.expected_mut() += expected; shard_stats.endorsement_stats_mut().produced += endorsement_stats.produced; shard_stats.endorsement_stats_mut().expected += endorsement_stats.expected; } } // Collect the shards for which the validator was *expected* to produce at least one chunk. let mut shards_produced = chunks_stats_by_shard .iter() .filter_map(|(shard, stats)| (stats.expected() > 0).then_some(*shard)) .collect_vec(); shards_produced.sort(); // Collect the shards for which the validator was *expected* to validate at least one chunk. let mut shards_endorsed = chunks_stats_by_shard .iter() .filter_map(|(shard, stats)| { (stats.endorsement_stats().expected > 0).then_some(*shard) }) .collect_vec(); shards_endorsed.sort(); let (account_id, public_key, stake) = info.destructure(); Ok(CurrentEpochValidatorInfo { is_slashed: false, // currently there is no slashing account_id, public_key, stake, num_produced_blocks: block_stats.produced, num_expected_blocks: block_stats.expected, num_produced_chunks: chunk_stats.produced(), num_expected_chunks: chunk_stats.expected(), num_produced_chunks_per_shard: shards_produced .iter() .map(|shard| { chunks_stats_by_shard .get(shard) .map_or(0, |stats| stats.produced()) }) .collect(), num_expected_chunks_per_shard: shards_produced .iter() .map(|shard| { chunks_stats_by_shard .get(shard) .map_or(0, |stats| stats.expected()) }) .collect(), num_produced_endorsements: chunk_stats.endorsement_stats().produced, num_expected_endorsements: chunk_stats.endorsement_stats().expected, num_produced_endorsements_per_shard: shards_endorsed .iter() .map(|shard| { chunks_stats_by_shard .get(shard) .map_or(0, |stats| stats.endorsement_stats().produced) }) .collect(), num_expected_endorsements_per_shard: shards_endorsed .iter() .map(|shard| { chunks_stats_by_shard .get(shard) .map_or(0, |stats| stats.endorsement_stats().expected) }) .collect(), shards_produced, shards_endorsed, }) }) .collect::, EpochError>>()?; let all_proposals = aggregator.all_proposals.iter().map(|(_, p)| p.clone().into()).collect(); let next_epoch_id = self.get_next_epoch_id(h)?; (cur_validators, next_epoch_id, all_proposals) } }; let next_epoch_info = self.get_epoch_info(&next_epoch_id)?; let next_shard_layout = self.get_shard_layout(&next_epoch_id)?; let mut next_validator_to_shard = (0..next_epoch_info.validators_len()) .map(|_| HashSet::default()) .collect::>>(); for (shard_index, validators) in next_epoch_info.chunk_producers_settlement().iter().enumerate() { let shard_id = next_shard_layout.get_shard_id(shard_index)?; for validator_id in validators { next_validator_to_shard[*validator_id as usize].insert(shard_id); } } let next_validators = next_epoch_info .validators_iter() .enumerate() .map(|(validator_id, info)| { let mut shards = next_validator_to_shard[validator_id] .clone() .into_iter() .collect::>(); shards.sort(); let (account_id, public_key, stake) = info.destructure(); NextEpochValidatorInfo { account_id, public_key, stake, shards } }) .collect(); let prev_epoch_kickout = next_epoch_info .validator_kickout() .clone() .into_iter() .collect::>() .into_iter() .map(|(account_id, reason)| ValidatorKickoutView { account_id, reason }) .collect(); Ok(EpochValidatorInfo { current_validators, next_validators, current_fishermen: vec![], next_fishermen: vec![], current_proposals: all_proposals, prev_epoch_kickout, epoch_start_height, epoch_height, validator_reward_paid_prev_epoch: cur_epoch_info.validator_reward().clone(), }) } /// Get minimum stake allowed at current block. Attempts to stake with a lower stake will be /// rejected. pub fn minimum_stake(&self, prev_block_hash: &CryptoHash) -> Result { let next_epoch_id = self.get_next_epoch_id_from_prev_block(prev_block_hash)?; let (protocol_version, seat_price) = { let epoch_info = self.get_epoch_info(&next_epoch_id)?; (epoch_info.protocol_version(), epoch_info.seat_price()) }; let config = self.config.for_protocol_version(protocol_version); let stake_divisor = { config.minimum_stake_divisor }; Ok(seat_price.checked_div(u128::from(stake_divisor)).unwrap()) } } /// Private utilities for EpochManager. impl EpochManager { /// Returns true if the next block after the given block will be in the next epoch. /// /// Parameters: /// - `block_height`: the height of the block /// - `last_final_height`: the height of the last final block for the block in question /// - `epoch_first_block`: the first block of the current epoch fn is_next_block_in_next_epoch_impl( &self, block_height: BlockHeight, last_final_height: BlockHeight, epoch_first_block_info: &BlockInfo, ) -> Result { let protocol_version = self.get_epoch_info(&epoch_first_block_info.epoch_id())?.protocol_version(); let epoch_length = self.config.for_protocol_version(protocol_version).epoch_length; let estimated_next_epoch_start = epoch_first_block_info.height() + epoch_length; if epoch_length <= 3 { // This is here to make epoch_manager tests pass. Needs to be removed, tracked in // https://github.com/nearprotocol/nearcore/issues/2522 return Ok(block_height + 1 >= estimated_next_epoch_start); } Ok(last_final_height + 3 >= estimated_next_epoch_start) } /// Returns true if the next block after `block_info` will be in the next epoch. pub(crate) fn is_next_block_in_next_epoch( &self, block_info: &BlockInfo, ) -> Result { if block_info.is_genesis() { return Ok(true); } // In SPICE, do not transition to the next epoch if the last certified // block's epoch is different from the current block epoch. This // prevents execution from lagging more than one epoch behind. if let Some(last_certified_block_epoch) = block_info.last_certified_block_epoch() { if last_certified_block_epoch != block_info.epoch_id() { return Ok(false); } } // The first block of an epoch reads itself here during its own record, before commit. if block_info.epoch_first_block() == block_info.hash() { return self.is_next_block_in_next_epoch_impl( block_info.height(), block_info.last_finalized_height(), block_info, ); } let epoch_first_block_info = self.get_block_info(block_info.epoch_first_block())?; self.is_next_block_in_next_epoch_impl( block_info.height(), block_info.last_finalized_height(), &epoch_first_block_info, ) } /// Returns true, if given current block info, next block must include the approvals from the next /// epoch (in addition to the approvals from the current epoch) fn next_block_need_approvals_from_next_epoch( &self, block_info: &BlockInfo, ) -> Result { if self.is_next_block_in_next_epoch(block_info)? { return Ok(false); } let epoch_length = { let protocol_version = self.get_epoch_info_from_hash(block_info.hash())?.protocol_version(); let config = self.config.for_protocol_version(protocol_version); config.epoch_length }; let estimated_next_epoch_start = self.get_block_info(block_info.epoch_first_block())?.height() + epoch_length; Ok(block_info.last_finalized_height() + 3 < estimated_next_epoch_start && block_info.height() + 3 >= estimated_next_epoch_start) } /// Returns epoch id for the next epoch (T+1), given an block info in current epoch (T). fn get_next_epoch_id_from_info(&self, block_info: &BlockInfo) -> Result { // The first block of an epoch reads itself here during its own record, before commit. if block_info.epoch_first_block() == block_info.hash() { return Ok(EpochId(*block_info.prev_hash())); } let first_block_info = self.get_block_info(block_info.epoch_first_block())?; Ok(EpochId(*first_block_info.prev_hash())) } pub fn get_epoch_config(&self, protocol_version: ProtocolVersion) -> EpochConfig { self.config.for_protocol_version(protocol_version) } pub fn get_shard_layout(&self, epoch_id: &EpochId) -> Result { let epoch_info = self.get_epoch_info(epoch_id)?; self.shard_layout_of_epoch_info(epoch_id, &epoch_info) } fn shard_layout_of_epoch_info( &self, epoch_id: &EpochId, epoch_info: &EpochInfo, ) -> Result { if let Some(shard_layout) = epoch_info.shard_layout() { Ok(shard_layout.clone()) } else { let protocol_version = epoch_info.protocol_version(); self.get_static_shard_layout_for_protocol_version(protocol_version).ok_or_else(|| { EpochError::ShardingError(format!( "shard layout missing. epoch_id={:?} protocol_version={}", epoch_id, protocol_version )) }) } } /// Get *static* shard layout for the given protocol version. If the protocol version uses /// dynamic resharding, there is no specific layout assigned to that version, so this method /// returns `None`. /// /// **Tip:** Consider using `get_shard_layout` instead. pub fn get_static_shard_layout_for_protocol_version( &self, protocol_version: ProtocolVersion, ) -> Option { self.config.for_protocol_version(protocol_version).static_shard_layout() } pub fn get_epoch_info(&self, epoch_id: &EpochId) -> Result, EpochError> { self.store.get_epoch_info(epoch_id) } fn has_epoch_info(&self, epoch_id: &EpochId) -> Result { match self.get_epoch_info(epoch_id) { Ok(_) => Ok(true), Err(EpochError::EpochOutOfBounds(_)) => Ok(false), Err(err) => Err(err), } } /// Whether the block's `BlockInfo` is committed. Callers can drop the returned update /// even after a successful record, and then the block counts as not recorded. /// Trade-off: a second recorder of the same block between a record returning and its /// caller committing is not deduplicated. Recording is deterministic and the writes /// are insert-only, so that costs duplicate work, not correctness. fn has_block_info(&self, hash: &CryptoHash) -> Result { match self.store.get_block_info(hash) { Ok(_) => Ok(true), Err(EpochError::MissingBlock(_)) => Ok(false), Err(err) => Err(err), } } pub fn get_block_info(&self, hash: &CryptoHash) -> Result, EpochError> { self.store.get_block_info(hash) } /// Updates epoch info aggregator to state as of `last_final_block_hash` /// block. /// /// The block hash passed as argument should be a final block so that the /// method can perform efficient incremental updates. Calling this method /// on a block which has not been finalized yet is likely to result in /// performance issues since handling forks will force it to traverse the /// entire epoch from scratch. /// /// The result of the aggregation is stored in `self.epoch_info_aggregator`. /// /// Saves the aggregator to `store_update` if epoch id changes or every /// [`AGGREGATOR_SAVE_PERIOD`] heights. pub fn update_epoch_info_aggregator_upto_final( &mut self, last_final_block_hash: &CryptoHash, store_update: &mut EpochStoreUpdateAdapter, ) -> Result<(), EpochError> { if let Some((aggregator, replace)) = self.aggregate_epoch_info_upto(last_final_block_hash)? { let save = if replace { self.epoch_info_aggregator = aggregator; true } else { self.epoch_info_aggregator.merge(aggregator); let block_info = self.get_block_info(last_final_block_hash)?; block_info.height() % AGGREGATOR_SAVE_PERIOD == 0 }; if save { store_update.set_epoch_info_aggregator(&self.epoch_info_aggregator); } } Ok(()) } /// Returns epoch info aggregate with state up to `last_block_hash`. /// /// The block hash passed as argument should be the latest block belonging /// to current epoch. Calling this method on any other block is likely to /// result in performance issues since handling something which is not past /// the final block will force it to traverse the entire epoch from scratch. /// /// This method does not change `self.epoch_info_aggregator`. pub fn get_epoch_info_aggregator_upto_last( &self, last_block_hash: &CryptoHash, ) -> Result { if last_block_hash == &self.epoch_info_aggregator.last_block_hash { return Ok(self.epoch_info_aggregator.clone()); } self.epoch_info_aggregator_upto_block(self.get_block_info(last_block_hash)?) } /// Like [`Self::get_epoch_info_aggregator_upto_last`], but takes the block itself, so it /// also works for a block that is not committed yet. The block must not be the sync point /// `self.epoch_info_aggregator.last_block_hash`. fn epoch_info_aggregator_upto_block( &self, block_info: Arc, ) -> Result { let (mut aggregator, replace) = self.aggregate_epoch_info_from(block_info)?; if !replace { aggregator.merge_prefix(&self.epoch_info_aggregator); } Ok(aggregator) } /// Aggregates epoch info between last final block and given block. /// /// More specifically, aggregates epoch information from block denoted by /// `self.epoch_info_aggregator.last_block_hash` (excluding that block) up /// to one denoted by `block_hash` (including that block). If the two /// blocks belong to different epochs, stops aggregating once it reaches /// start of epoch `block_hash` belongs to. /// /// The block hash passed as argument should be a latest final block or /// a descendant of a latest final block. Calling this method on any other /// block is likely to result in performance issues since handling forks /// will force it to traverse the entire epoch from scratch. /// /// If `block_hash` equals `self.epoch_info_aggregator.last_block_hash` /// returns None. Otherwise returns `Some((aggregator, full_info))` tuple. /// The first element of the pair is aggregator with collected information; /// the second specifies whether the returned aggregator includes full /// information about an epoch (such that it does not need to be merged with /// `self.epoch_info_aggregator`). That happens if the method reaches epoch /// boundary. fn aggregate_epoch_info_upto( &self, block_hash: &CryptoHash, ) -> Result, EpochError> { if block_hash == &self.epoch_info_aggregator.last_block_hash { return Ok(None); } self.aggregate_epoch_info_from(self.get_block_info(block_hash)?).map(Some) } /// The walk of [`Self::aggregate_epoch_info_upto`], starting at `block_info`, which must /// not be the sync point. fn aggregate_epoch_info_from( &self, mut block_info: Arc, ) -> Result<(EpochInfoAggregator, bool), EpochError> { let epoch_id = *block_info.epoch_id(); let epoch_info = self.get_epoch_info(&epoch_id)?; let shard_layout = self.get_shard_layout(&epoch_id)?; let mut aggregator = EpochInfoAggregator::new(epoch_id, *block_info.hash()); Ok(loop { #[cfg(test)] { self.epoch_info_aggregator_loop_counter .fetch_add(1, std::sync::atomic::Ordering::SeqCst); } let different_epoch = &epoch_id != block_info.epoch_id(); if different_epoch || block_info.is_genesis() { // We’ve reached the beginning of an epoch or a genesis block // without seeing self.epoch_info_aggregator.last_block_hash. // This implies self.epoch_info_aggregator.last_block_hash // belongs to different epoch or we’re on different fork (though // the latter should never happen). In either case, the // aggregator contains full epoch information. break (aggregator, true); } let prev_hash = *block_info.prev_hash(); let prev_block_info = match self.get_block_info(&prev_hash) { Ok(info) => Some(info), Err(EpochError::MissingBlock(_)) => None, Err(e) => return Err(e), }; let (prev_height, prev_epoch) = match &prev_block_info { Some(info) => (info.height(), *info.epoch_id()), None => { // In the case of epoch sync, we may not have the BlockInfo for the last final block // of the epoch. In this case, check for this special case. // TODO(11931): think of a better way to do this. let chain_store = self.store.chain_store(); let tip = chain_store.header_head().expect("Tip not found"); let block_header = chain_store .get_block_header(&tip.prev_block_hash) .expect("BlockHeader for prev block of tip not found in store"); if block_header.prev_hash() == block_info.hash() { (block_info.height() - 1, *block_info.epoch_id()) } else { return Err(EpochError::MissingBlock(prev_hash)); } } }; let chunk_producers = self.anchored_chunk_producers_for_aggregator( &epoch_id, &epoch_info, &shard_layout, prev_block_info.as_deref(), ); aggregator.update_tail( &block_info, &epoch_info, &shard_layout, prev_height, chunk_producers.as_ref(), ); if prev_hash == self.epoch_info_aggregator.last_block_hash { // We’ve reached sync point of the old aggregator. If old // aggregator was for a different epoch, we have full info in // our aggregator; otherwise we don’t. break (aggregator, epoch_id != prev_epoch); } // A missing parent is valid only if the walk stops before reaching it. block_info = prev_block_info.ok_or(EpochError::MissingBlock(prev_hash))?; }) } /// Chunk producers of the block built on `prev_block_info`, read from the rows seeded at /// its grandparent, so kickout stats count the producers consensus resolved. Returns /// `None` when EarlyKickout is off, the parent is missing or genesis, or the grandparent is /// missing or in another epoch. The caller then samples at `prev_height + 1`. A shard whose /// row is missing or names an unknown account is sampled at `anchor.height + 2`. fn anchored_chunk_producers_for_aggregator( &self, epoch_id: &EpochId, epoch_info: &EpochInfo, shard_layout: &ShardLayout, prev_block_info: Option<&BlockInfo>, ) -> Option> { if !ProtocolFeature::EarlyKickout.enabled(epoch_info.protocol_version()) { return None; } // Missing prev `BlockInfo` is the epoch-sync special case handled by // the caller; resolve that block with the legacy sampler. let prev_block_info = prev_block_info?; if prev_block_info.is_genesis() { return None; } let anchor = *prev_block_info.prev_hash(); let anchor_block_info = self.get_block_info(&anchor).ok()?; if anchor_block_info.epoch_id() != epoch_id { return None; } // Reproduce what the writer stored at the anchor: a sample at // `anchor.height + 2`, not the chunk height. They differ only when // `prev` skipped heights above `anchor` (e.g. post epoch-sync). let anchor_sample_height = anchor_block_info.height() + CHUNK_GRANDPARENT_ANCHOR_HEIGHT_OFFSET; let mut chunk_producers = HashMap::new(); for shard_id in shard_layout.shard_ids() { let key = get_block_shard_id(&anchor, shard_id); let validator_id = match self .store .store_ref() .get_ser::(DBCol::ChunkProducers, &key) { None => { // Tolerated on this stats path: canonical sampling is // exact wherever the kickout blacklist is empty (e.g. // epoch-sync boundary tails, or blocks recorded before this // column existed). The consensus reader // `get_chunk_producer_info_anchored` keeps the strict // `ChunkProducerNotInDB` guard. tracing::debug!( target: "epoch_tracker", ?anchor, %shard_id, "chunk producer row absent during aggregation, sampling canonically", ); epoch_info.sample_chunk_producer( shard_layout, shard_id, anchor_sample_height, )? } Some(stake) => match epoch_info.get_validator_id(stake.account_id()).copied() { Some(validator_id) => validator_id, None => { // A stored account outside `epoch_info` should not // happen in correct operation, but on this stats path // fall back to canonical sampling rather than panic. tracing::debug!( target: "epoch_tracker", ?anchor, %shard_id, "chunk producer not in epoch during aggregation, sampling canonically", ); epoch_info.sample_chunk_producer( shard_layout, shard_id, anchor_sample_height, )? } }, }; chunk_producers.insert(shard_id, validator_id); } Some(chunk_producers) } /// The kickout blacklist as of a given last-final basis (`final_hash`, /// `final_height`), for sampling in `epoch` (the anchor's own epoch). Single /// implementation of the basis shared by the seeder and the /// `get_chunk_producer_blacklist` accessor, so the two can't drift and the /// live read always agrees with the stored row. Empty at genesis (no /// last-final block yet). fn chunk_producer_blacklist_at_anchor( &self, final_hash: &CryptoHash, final_height: BlockHeight, epoch: &SampleEpoch<'_>, ) -> Result, EpochError> { if *final_hash == CryptoHash::default() { return Ok(Arc::new(ChunkProducerBlacklist::empty())); } // Skip the epoch walk when the blacklist is empty by rule. At the sync point, // use the aggregator: epoch sync may leave that block without `BlockInfo`. let final_epoch_id = if *final_hash == self.epoch_info_aggregator.last_block_hash { self.epoch_info_aggregator.epoch_id } else { *self.get_block_info(final_hash)?.epoch_id() }; if final_epoch_id != *epoch.epoch_id { return Ok(Arc::new(ChunkProducerBlacklist::empty())); } // Fork siblings can overwrite `DBCol::EpochStart`; derive the start from ancestry. // A missing last final block is an error, because treating it as grace could change // consensus. let epoch_start = self.get_epoch_start_height(final_hash)?; let blocks_into_epoch = final_height.saturating_sub(epoch_start); if blocks_into_epoch < early_kickout_epoch_grace_blocks() { return Ok(Arc::new(ChunkProducerBlacklist::empty())); } self.chunk_producer_blacklists.get_or_try_put(*final_hash, |_| { let aggregator = self.get_epoch_info_aggregator_upto_last(final_hash)?; Ok(Arc::new(blacklist_for_epoch( &aggregator, epoch.epoch_id, epoch.epoch_info, epoch.shard_layout, blocks_into_epoch, ))) }) } /// Seed `DBCol::ChunkProducers` for chunks anchored at `anchor.hash` (the /// grandparent anchor of chunks at height `anchor.height + /// CHUNK_GRANDPARENT_ANCHOR_HEIGHT_OFFSET`). No-op unless EarlyKickout is /// enabled for the anchor's own epoch (`epoch`). Producers are always sampled /// from the anchor's own epoch: `get_chunk_producer_info_anchored` consumes /// the row only when the chunk's epoch equals the anchor's epoch, so a /// last-of-epoch anchor's row (its grandchild at `height + 2` falls in the /// next epoch) is not read on any honest path — no cross-epoch prediction /// needed. (The row is not literally dead: the best-effort V2 resolver can /// read it with a sender-claimed epoch on the parent-missing branch. That /// non-consensus path is signature-gated and exists under either seeding /// layout; the layout choice only changes which shard-id keys carry rows.) /// /// Writes into `store_update` so the rows commit atomically with the block's /// `BlockInfo`. Gating on the anchor's *own* epoch (not the epoch after) /// avoids seeding dead rows for last-of-epoch anchors across an activation edge. /// /// The blacklist basis is the anchor's last-final block (`anchor.final_hash`), not the /// anchor itself: it is header-derived, so identical across nodes for a canonical anchor. /// That determinism is required because the seeded row is read verbatim by /// `get_chunk_producer_info_anchored`. It also keeps the walk off the growing not-yet-final /// suffix during a finality stall. fn seed_chunk_producers( &self, store_update: &mut EpochStoreUpdateAdapter, anchor: &SeedAnchor, epoch: SampleEpoch, ) -> Result<(), EpochError> { if !ProtocolFeature::EarlyKickout.enabled(epoch.epoch_info.protocol_version()) { return Ok(()); } // Via the shared helper, not the `get_chunk_producer_blacklist` adapter: the // adapter re-takes `self.read()` and would deadlock under the seeder's write lock. let computed = self.chunk_producer_blacklist_at_anchor( &anchor.final_hash, anchor.final_height, &epoch, )?; let ChunkProducerBlacklist { blacklist, shard_stats } = computed.as_ref(); // Emit only when seeding to avoid counting consensus reads. Clear retired shards // and zero shards without candidates, which are absent from `shard_stats`. EARLY_KICKOUT_BLACKLIST_SIZE.reset(); for shard_id in epoch.shard_layout.shard_ids() { let raw = shard_stats.get(&shard_id).map_or(0, |s| s.raw_candidate_count); EARLY_KICKOUT_BLACKLIST_SIZE .with_label_values(&[&shard_id.to_string()]) .set(raw as i64); } for (shard_id, stats) in shard_stats { if stats.safety_valve_fired() { EARLY_KICKOUT_SAFETY_VALVE_FIRED.with_label_values(&[&shard_id.to_string()]).inc(); if let Some(kept) = stats.kept { tracing::warn!( target: "early_kickout", %shard_id, kept = %epoch.epoch_info.validator_account_id(kept), "safety valve: kept least-bad producer" ); } } } self.seed_chunk_producer_rows( store_update, &anchor.hash, anchor.height, epoch.epoch_info, epoch.shard_layout, blacklist, ); Ok(()) } /// Sample each shard's chunk producer at the anchor offset, excluding the /// per-shard `blacklist`, and write the rows into `store_update`. Shared by /// the record-block and epoch-sync seeders, which differ only in how the /// blacklist is obtained. fn seed_chunk_producer_rows( &self, store_update: &mut EpochStoreUpdateAdapter, block_hash: &CryptoHash, block_height: BlockHeight, sample_epoch_info: &EpochInfo, sample_shard_layout: &ShardLayout, blacklist: &HashMap>, ) { let empty = HashSet::new(); let height = block_height + CHUNK_GRANDPARENT_ANCHOR_HEIGHT_OFFSET; for shard_id in sample_shard_layout.shard_ids() { let shard_blacklist = blacklist.get(&shard_id).unwrap_or(&empty); let sampled = sample_epoch_info.sample_chunk_producer_excluding( sample_shard_layout, shard_id, height, shard_blacklist, ); // The blacklist's safety valve (compute_chunk_producer_blacklist) never // excludes every producer on a shard, so the sampler must yield one for any // shard that has producers. A `None` here means the shard's settlement is // empty (nothing to seed) — anything else means the safety valve was // weakened and a shard was left with no eligible producer. debug_assert!( sampled.is_some() || sample_shard_layout .get_shard_index(shard_id) .ok() .and_then(|i| sample_epoch_info.chunk_producers_settlement().get(i)) .is_none_or(|s| s.is_empty()), "kickout seeder excluded every producer on shard {shard_id}", ); if let Some(validator_id) = sampled { let validator_stake = sample_epoch_info.get_validator(validator_id); // A slot was reassigned iff its plain (non-excluded) pick is itself blacklisted. // Testing `plain != sampled` would be wrong: the excluding sampler renormalizes the // eligible set, so it can pick a different producer even when the plain pick was fine. if !shard_blacklist.is_empty() { let plain = sample_epoch_info.sample_chunk_producer( sample_shard_layout, shard_id, height, ); if let Some(plain) = plain.filter(|p| shard_blacklist.contains(p)) { EARLY_KICKOUT_CHUNK_PRODUCER_REASSIGNED .with_label_values(&[&shard_id.to_string()]) .inc(); tracing::debug!( target: "epoch_manager", %shard_id, height, kicked = %sample_epoch_info.get_validator(plain).account_id(), reassigned_to = %validator_stake.account_id(), "early kickout: chunk producer slot reassigned", ); } } store_update.set_chunk_producer(block_hash, shard_id, &validator_stake); } } } /// Seed chunk producers for a block that is the first block of its epoch, so /// chunks anchored at it belong to that same epoch. Used by the epoch-sync /// path, which installs the current epoch's first `BlockInfo` outside /// `record_block_info`. /// /// Uses an empty blacklist: the first block of an epoch has no in-epoch stats /// yet. This also sidesteps the aggregator walk in `seed_chunk_producers` — /// the epoch-sync block lives only in the pending `store_update`, so a walk /// from it via `get_block_info` would fail with `MissingBlock`. fn seed_chunk_producers_for_first_block( &self, store_update: &mut EpochStoreUpdateAdapter, block_info: &BlockInfo, epoch_info: &EpochInfo, ) -> Result<(), EpochError> { let shard_layout = self.shard_layout_of_epoch_info(block_info.epoch_id(), epoch_info)?; if ProtocolFeature::EarlyKickout.enabled(epoch_info.protocol_version()) { self.seed_chunk_producer_rows( store_update, block_info.hash(), block_info.height(), epoch_info, &shard_layout, &HashMap::new(), ); } Ok(()) } /// Get the shard split to include in the block header, if any. /// /// This method is expected to be called during the production of the last block of an epoch. /// The returned split should be included in the header of the produced block. It will be used /// to derive layout for epoch `N+2` (where `N` is the current epoch). /// /// Parameters: /// - `protocol_version`: protocol version of the current epoch /// - `parent_hash`: hash of the parent of the block being produced /// - `chunk_headers`: chunk headers from the block, used to collect proposed shard splits /// /// Returns `Some((shard_id, boundary_account))` if a shard split should be scheduled. pub fn get_upcoming_shard_split( &self, protocol_version: ProtocolVersion, parent_hash: &CryptoHash, chunk_headers: &[ShardChunkHeader], ) -> Result, EpochError> { // Check if dynamic resharding is enabled let epoch_config = self.get_epoch_config(protocol_version); let dynamic_resharding_config = match &epoch_config.shard_layout_config { ShardLayoutConfig::Static { .. } => return Ok(None), ShardLayoutConfig::Dynamic { dynamic_resharding_config } => dynamic_resharding_config, }; // Check if resharding is allowed based on epoch constraints let can_reshard = self .can_reshard(&parent_hash, dynamic_resharding_config.min_epochs_between_resharding)?; if !can_reshard { return Ok(None); } // Collect proposed splits from chunk headers let mut proposed_splits = HashMap::new(); for chunk_header in chunk_headers { if let Some(split) = chunk_header.proposed_split() { proposed_splits.insert(chunk_header.shard_id(), split.clone()); } } // Pick the shard to split let Some((shard_id, split)) = pick_shard_to_split(&proposed_splits, dynamic_resharding_config) else { return Ok(None); }; Ok(Some((shard_id, split.boundary_account))) } } /// Pick which shard to split if there are proposed splits for multiple shards. /// Shards in `force_split_shards` have top priority. /// Otherwise, the shard with the highest memory usage is selected. /// /// Returns `None` if there are no proposed splits. pub fn pick_shard_to_split( proposed_splits: &HashMap, config: &DynamicReshardingConfig, ) -> Option<(ShardId, TrieSplit)> { if proposed_splits.is_empty() { return None; } for shard_id in &config.force_split_shards { if let Some(split) = proposed_splits.get(shard_id) { debug_assert!(!config.block_split_shards.contains(shard_id)); return Some((*shard_id, split.clone())); } } // We're using (total_memory, shard_id) tuple as key to enforce determinism in case two shards // have the exacts same memory usage (very unlikely in production, but can happen in tests). proposed_splits.iter().max_by_key(|(shard_id, split)| (split.total_memory(), *shard_id)).map( |(shard_id, split)| { debug_assert!(!config.block_split_shards.contains(shard_id)); (*shard_id, split.clone()) }, ) }