Skip to main content

solana_runtime/
bank.rs

1//! The `bank` module tracks client accounts and the progress of on-chain
2//! programs.
3//!
4//! A single bank relates to a block produced by a single leader and each bank
5//! except for the genesis bank points back to a parent bank.
6//!
7//! The bank is the main entrypoint for processing verified transactions with the function
8//! `Bank::process_transactions`
9//!
10//! It does this by loading the accounts using the reference it holds on the account store,
11//! and then passing those to an InvokeContext which handles loading the programs specified
12//! by the Transaction and executing it.
13//!
14//! The bank then stores the results to the accounts store.
15//!
16//! It then has APIs for retrieving if a transaction has been processed and it's status.
17//! See `get_signature_status` et al.
18//!
19//! Bank lifecycle:
20//!
21//! A bank is newly created and open to transactions. Transactions are applied
22//! until either the bank reached the tick count when the node is the leader for that slot, or the
23//! node has applied all transactions present in all `Entry`s in the slot.
24//!
25//! Once it is complete, the bank can then be frozen. After frozen, no more transactions can
26//! be applied or state changes made. At the frozen step, rent will be applied and various
27//! sysvar special accounts update to the new state of the system.
28//!
29//! After frozen, and the bank has had the appropriate number of votes on it, then it can become
30//! rooted. At this point, it will not be able to be removed from the chain and the
31//! state is finalized.
32//!
33//! It offers a high-level API that signs transactions
34//! on behalf of the caller, and a low-level API for when they have
35//! already been signed and verified.
36pub use {
37    crate::slot_params::DEFAULT_MAX_ENTRY_BYTES_PER_SLOT,
38    partitioned_epoch_rewards::KeyedRewardsAndNumPartitions, solana_leader_schedule::SlotLeader,
39    solana_reward_info::RewardType,
40};
41use {
42    crate::{
43        account_saver::collect_accounts_to_store,
44        alpenglow_epoch_type::AlpenglowEpochType,
45        bank::{
46            entry_bytes_budget::EntryBytesBudget,
47            metrics::*,
48            partitioned_epoch_rewards::{CachedVoteAccounts, EpochRewardStatus},
49        },
50        bank_forks::BankForks,
51        block_component_processor::{
52            BlockComponentProcessor,
53            vote_reward::epoch_inflation_account_state::EpochInflationAccountState,
54        },
55        epoch_stakes::{
56            BLSPubkeyToRankMap, DeserializableVersionedEpochStakes, NodeVoteAccounts,
57            VersionedEpochStakes,
58        },
59        inflation_rewards::points::InflationPointCalculationEvent,
60        installed_scheduler_pool::{BankWithScheduler, InstalledSchedulerRwLock},
61        leader_schedule_utils::leader_schedule_from_vote_accounts,
62        rent_collector::RentCollector,
63        reward_info::RewardInfo,
64        runtime_config::RuntimeConfig,
65        slot_params::{SlotParams, SlotParamsArchive},
66        stake_account::StakeAccount,
67        stake_history::StakeHistory as CowStakeHistory,
68        stake_weighted_timestamp::{
69            MAX_ALLOWABLE_DRIFT_PERCENTAGE_FAST, MAX_ALLOWABLE_DRIFT_PERCENTAGE_SLOW_V2,
70            MaxAllowableDrift, calculate_stake_weighted_timestamp,
71        },
72        stakes::{
73            DelegatedStakes, DeserializableDelegationStakes, SerdeStakesToStakeFormat, Stakes,
74            StakesCache,
75        },
76        status_cache::{SlotDelta, StatusCache},
77        sysvar_account::{create_account, create_account_with_bincode, from_account},
78        transaction_batch::{OwnedOrBorrowed, TransactionBatch},
79    },
80    accounts_lt_hash::AccountsLtHashAsyncProgress,
81    agave_bls_cert_verify::cert_verify::{self, Error as CertVerifyError},
82    agave_feature_set::{self as feature_set, FeatureSet},
83    agave_precompiles::{get_precompile, get_precompiles, is_precompile},
84    agave_reserved_account_keys::ReservedAccountKeys,
85    agave_snapshots::snapshot_hash::SnapshotHash,
86    agave_votor_messages::{
87        certificate::{CertSignature, Certificate, GenesisCert},
88        migration::GENESIS_CERTIFICATE_ACCOUNT,
89        unverified_vote_message::UnverifiedCertificate,
90        wire::{WireBlockCertMessage, WireCertSignature},
91    },
92    ahash::AHashSet,
93    log::*,
94    partitioned_epoch_rewards::PartitionedRewardsCalculation,
95    rayon::ThreadPool,
96    serde::{Deserialize, Serialize},
97    solana_account::{
98        Account, AccountSharedData, InheritableAccountFields, ReadableAccount, WritableAccount,
99    },
100    solana_accounts_db::{
101        account_locks::validate_account_locks,
102        account_storage_entry::AccountStorageEntry,
103        accounts::{AccountAddressFilter, Accounts},
104        accounts_db::{AccountsDb, AccountsDbConfig},
105        accounts_hash::AccountsLtHash,
106        accounts_index::IndexKey,
107        accounts_scan::ScanResult,
108        accounts_update_notifier_interface::AccountsUpdateNotifier,
109        ancestors::Ancestors,
110        blockhash_queue::BlockhashQueue,
111        storable_accounts::StorableAccounts,
112        utils::create_account_shared_data,
113    },
114    solana_builtins::{BUILTINS, STATELESS_BUILTINS},
115    solana_clock::{
116        BankId, Epoch, INITIAL_RENT_EPOCH, MAX_PROCESSING_AGE, MAX_TRANSACTION_FORWARDING_DELAY,
117        Slot, SlotIndex, UnixTimestamp,
118    },
119    solana_cluster_type::ClusterType,
120    solana_compute_budget::compute_budget::ComputeBudget,
121    solana_cost_model::cost_tracker::CostTracker,
122    solana_epoch_info::EpochInfo,
123    solana_epoch_schedule::EpochSchedule,
124    solana_feature_gate_interface as feature,
125    solana_fee::FeeFeatures,
126    solana_fee_calculator::FeeRateGovernor,
127    solana_fee_structure::{FeeDetails, FeeStructure},
128    solana_genesis_config::GenesisConfig,
129    solana_hard_forks::HardForks,
130    solana_hash::Hash,
131    solana_inflation::Inflation,
132    solana_keypair::Keypair,
133    solana_lattice_hash::lt_hash::LtHash,
134    solana_measure::{measure::Measure, measure_time, measure_us},
135    solana_message::{
136        AccountKeys, SanitizedMessage, VersionedMessage, inner_instruction::InnerInstructions,
137    },
138    solana_packet::PACKET_DATA_SIZE,
139    solana_precompile_error::PrecompileError,
140    solana_program_runtime::{
141        invoke_context::BuiltinFunctionRegisterer,
142        loaded_programs::{ProgramRuntimeEnvironment, ProgramRuntimeEnvironments},
143        program_cache_entry::ProgramCacheEntry,
144    },
145    solana_pubkey::Pubkey,
146    solana_rent::Rent,
147    solana_runtime_transaction::{
148        runtime_transaction::RuntimeTransaction, transaction_meta::TransactionConfiguration,
149        transaction_with_meta::TransactionWithMeta,
150    },
151    solana_sdk_ids::{bpf_loader_upgradeable, incinerator, native_loader, system_program},
152    solana_sha256_hasher::hashv,
153    solana_signature::Signature,
154    solana_slot_hashes::SlotHashes,
155    solana_slot_history::{Check, SlotHistory},
156    solana_stake_history::{StakeHistory, sysvar as stake_history},
157    solana_stake_interface::state::Delegation,
158    solana_svm::{
159        account_loader::LoadedTransaction,
160        account_overrides::AccountOverrides,
161        transaction_balances::{BalanceCollector, SvmTokenInfo},
162        transaction_commit_result::{CommittedTransaction, TransactionCommitResult},
163        transaction_error_metrics::TransactionErrorMetrics,
164        transaction_execution_result::{
165            TransactionExecutionDetails, TransactionLoadedAccountsStats,
166        },
167        transaction_processing_result::{
168            ProcessedTransaction, TransactionProcessingResult,
169            TransactionProcessingResultExtensions,
170        },
171        transaction_processor::{
172            ExecutionRecordingConfig, TransactionBatchProcessor, TransactionLogMessages,
173            TransactionProcessingConfig, TransactionProcessingEnvironment,
174        },
175    },
176    solana_svm_callback::{AccountState, InvokeContextCallback, TransactionProcessingCallback},
177    solana_svm_timings::{ExecuteTimingType, ExecuteTimings},
178    solana_svm_transaction::svm_message::SVMMessage,
179    solana_syscalls::create_program_runtime_environment,
180    solana_system_transaction as system_transaction,
181    solana_sysvar::{self as sysvar, last_restart_slot::LastRestartSlot},
182    solana_sysvar_id::SysvarId,
183    solana_transaction::{
184        Transaction, TransactionVerificationMode,
185        sanitized::{MAX_TX_ACCOUNT_LOCKS, MessageHash, SanitizedTransaction},
186        versioned::{TransactionVersion, VersionedTransaction},
187    },
188    solana_transaction_context::{
189        transaction::TransactionReturnData, transaction_accounts::KeyedAccountSharedData,
190    },
191    solana_transaction_error::{TransactionError, TransactionResult as Result},
192    solana_vote::{
193        vote_account::{VoteAccount, VoteAccounts, VoteAccountsHashMap},
194        vote_parser,
195    },
196    solana_vote_interface::state::VoteStateV4,
197    std::{
198        collections::{HashMap, HashSet},
199        fmt,
200        ops::AddAssign,
201        path::PathBuf,
202        slice,
203        sync::{
204            Arc, LazyLock, LockResult, Mutex, OnceLock, RwLock, RwLockReadGuard, RwLockWriteGuard,
205            Weak,
206            atomic::{
207                AtomicBool, AtomicI64, AtomicU64,
208                Ordering::{AcqRel, Acquire, Relaxed},
209            },
210        },
211        time::{Duration, Instant},
212    },
213    thiserror::Error,
214    wincode::{SchemaRead, SchemaWrite},
215};
216#[cfg(feature = "dev-context-only-utils")]
217use {
218    dashmap::DashSet,
219    qualifier_attr::{field_qualifiers, qualifiers},
220    rayon::iter::{IntoParallelRefIterator, ParallelIterator},
221    solana_accounts_db::accounts_db::{
222        ACCOUNTS_DB_CONFIG_FOR_BENCHMARKS, ACCOUNTS_DB_CONFIG_FOR_TESTING,
223    },
224    solana_nonce as nonce,
225    solana_nonce_account::{SystemAccountKind, get_system_account_kind},
226    solana_program_runtime::sysvar_cache::SysvarCache,
227    solana_svm::program_loader::load_program_with_pubkey,
228};
229
230mod accounts_lt_hash;
231mod address_lookup_table;
232pub mod bank_hash_details;
233pub mod builtins;
234mod check_transactions;
235pub mod entry_bytes_budget;
236mod fee_distribution;
237mod metrics;
238pub(crate) mod partitioned_epoch_rewards;
239mod recent_blockhashes_account;
240mod serde_snapshot;
241mod sysvar_cache;
242pub(crate) mod tests;
243
244pub const SECONDS_PER_YEAR: f64 = 365.25 * 24.0 * 60.0 * 60.0;
245
246pub const MAX_LEADER_SCHEDULE_STAKES: Epoch = 5;
247
248/// This will be guaranteed through the VAT rules,
249/// only the top 2000 validators by stake will be present in vote account structures.
250pub const MAX_ALPENGLOW_VOTE_ACCOUNTS: usize = 2000;
251
252/// Default 400ms-slot Validator Admission Ticket burn amount.
253///
254/// Use this for conservative genesis/test funding defaults. Runtime VAT
255/// filtering and burns must use the bank's effective slot params instead.
256pub const DEFAULT_VAT_TO_BURN_PER_EPOCH: u64 =
257    crate::slot_params::LEGACY_SLOT_PARAMS.vat_to_burn_per_epoch();
258
259/// The off-curve account where we store the Alpenglow clock. The clock sysvar has seconds
260/// resolution while the Alpenglow clock has nanosecond resolution.
261static NANOSECOND_CLOCK_ACCOUNT: LazyLock<Pubkey> = LazyLock::new(|| {
262    let (pubkey, _) =
263        Pubkey::find_program_address(&[b"alpenclock"], &agave_feature_set::alpenglow::id());
264    pubkey
265});
266
267pub type BankStatusCache = StatusCache<Result<()>>;
268#[cfg_attr(
269    feature = "frozen-abi",
270    frozen_abi(digest = "2RGYA9GpP1epajQ4CxQpCHMJPnLLBoseMbAyLJhTjsGS")
271)]
272pub type BankSlotDelta = SlotDelta<Result<()>>;
273
274#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
275pub struct SquashTiming {
276    pub squash_accounts_ms: u64,
277    pub squash_accounts_cache_ms: u64,
278    pub squash_cache_ms: u64,
279}
280
281impl AddAssign for SquashTiming {
282    fn add_assign(&mut self, rhs: Self) {
283        self.squash_accounts_ms += rhs.squash_accounts_ms;
284        self.squash_accounts_cache_ms += rhs.squash_accounts_cache_ms;
285        self.squash_cache_ms += rhs.squash_cache_ms;
286    }
287}
288
289#[derive(Clone, Debug, Default, PartialEq)]
290pub struct CollectorFeeDetails {
291    transaction_fee: u64,
292    priority_fee: u64,
293}
294
295impl CollectorFeeDetails {
296    pub(crate) fn accumulate(&mut self, fee_details: &FeeDetails) {
297        self.transaction_fee = self
298            .transaction_fee
299            .saturating_add(fee_details.transaction_fee());
300        self.priority_fee = self
301            .priority_fee
302            .saturating_add(fee_details.prioritization_fee());
303    }
304
305    pub fn total_transaction_fee(&self) -> u64 {
306        self.transaction_fee.saturating_add(self.priority_fee)
307    }
308
309    pub fn total_priority_fee(&self) -> u64 {
310        self.priority_fee
311    }
312}
313
314impl From<FeeDetails> for CollectorFeeDetails {
315    fn from(fee_details: FeeDetails) -> Self {
316        CollectorFeeDetails {
317            transaction_fee: fee_details.transaction_fee(),
318            priority_fee: fee_details.prioritization_fee(),
319        }
320    }
321}
322
323#[derive(Debug)]
324pub struct BankRc {
325    /// where all the Accounts are stored
326    pub accounts: Arc<Accounts>,
327
328    /// Previous checkpoint of this bank
329    pub(crate) parent: RwLock<Option<Arc<Bank>>>,
330
331    pub(crate) bank_id_generator: Arc<AtomicU64>,
332}
333
334impl BankRc {
335    #[cfg_attr(feature = "dev-context-only-utils", qualifiers(pub))]
336    pub(crate) fn new(accounts: Accounts) -> Self {
337        Self {
338            accounts: Arc::new(accounts),
339            parent: RwLock::new(None),
340            bank_id_generator: Arc::new(AtomicU64::new(0)),
341        }
342    }
343}
344
345pub struct LoadAndExecuteTransactionsOutput {
346    // Vector of results indicating whether a transaction was processed or could not
347    // be processed. Note processed transactions can still have failed!
348    pub processing_results: Vec<TransactionProcessingResult>,
349    // Processed transaction counts used to update bank transaction counts and
350    // for metrics reporting.
351    pub processed_counts: ProcessedTransactionCounts,
352    // Balances accumulated for TransactionStatusSender when transaction
353    // balance recording is enabled.
354    pub balance_collector: Option<BalanceCollector>,
355}
356
357#[derive(Debug, PartialEq)]
358pub struct TransactionSimulationResult {
359    pub result: Result<()>,
360    pub logs: TransactionLogMessages,
361    pub post_simulation_accounts: Vec<KeyedAccountSharedData>,
362    pub units_consumed: u64,
363    pub loaded_accounts_data_size: u32,
364    pub return_data: Option<TransactionReturnData>,
365    pub inner_instructions: Option<Vec<InnerInstructions>>,
366    pub fee: Option<u64>,
367    pub pre_balances: Option<Vec<u64>>,
368    pub post_balances: Option<Vec<u64>>,
369    pub pre_token_balances: Option<Vec<SvmTokenInfo>>,
370    pub post_token_balances: Option<Vec<SvmTokenInfo>>,
371}
372
373impl TransactionSimulationResult {
374    pub fn new_error(err: TransactionError) -> Self {
375        Self {
376            fee: None,
377            inner_instructions: None,
378            loaded_accounts_data_size: 0,
379            logs: vec![],
380            post_balances: None,
381            post_simulation_accounts: vec![],
382            post_token_balances: None,
383            pre_balances: None,
384            pre_token_balances: None,
385            result: Err(err),
386            return_data: None,
387            units_consumed: 0,
388        }
389    }
390}
391
392#[derive(Clone, Debug)]
393pub struct TransactionBalancesSet {
394    pub pre_balances: TransactionBalances,
395    pub post_balances: TransactionBalances,
396}
397
398impl TransactionBalancesSet {
399    pub fn new(pre_balances: TransactionBalances, post_balances: TransactionBalances) -> Self {
400        assert_eq!(pre_balances.len(), post_balances.len());
401        Self {
402            pre_balances,
403            post_balances,
404        }
405    }
406}
407pub type TransactionBalances = Vec<Vec<u64>>;
408
409pub type PreCommitResult<'a> = Result<Option<RwLockReadGuard<'a, Hash>>>;
410
411#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Default)]
412pub enum TransactionLogCollectorFilter {
413    All,
414    AllWithVotes,
415    #[default]
416    None,
417    OnlyMentionedAddresses,
418}
419
420#[derive(Debug, Default)]
421pub struct TransactionLogCollectorConfig {
422    pub mentioned_addresses: HashSet<Pubkey>,
423    pub filter: TransactionLogCollectorFilter,
424}
425
426#[derive(Clone, Debug, PartialEq, Eq)]
427pub struct TransactionLogInfo {
428    pub signature: Signature,
429    pub result: Result<()>,
430    pub is_vote: bool,
431    pub log_messages: TransactionLogMessages,
432}
433
434#[derive(Default, Debug)]
435pub struct TransactionLogCollector {
436    // All the logs collected for from this Bank.  Exact contents depend on the
437    // active `TransactionLogCollectorFilter`
438    pub logs: Vec<TransactionLogInfo>,
439
440    // For each `mentioned_addresses`, maintain a list of indices into `logs` to easily
441    // locate the logs from transactions that included the mentioned addresses.
442    pub mentioned_address_map: HashMap<Pubkey, Vec<usize>>,
443}
444
445impl TransactionLogCollector {
446    pub fn get_logs_for_address(
447        &self,
448        address: Option<&Pubkey>,
449    ) -> Option<Vec<TransactionLogInfo>> {
450        match address {
451            None => Some(self.logs.clone()),
452            Some(address) => self.mentioned_address_map.get(address).map(|log_indices| {
453                log_indices
454                    .iter()
455                    .filter_map(|i| self.logs.get(*i).cloned())
456                    .collect()
457            }),
458        }
459    }
460}
461
462#[derive(Error, Debug, Serialize, Deserialize)]
463pub enum VATHealthError {
464    #[error("vote account not found")]
465    VoteAccountNotFound,
466    #[error("missing BLS pubkey")]
467    NoBLSPubkey,
468    #[error("insufficient lamports in vote account: {0} < {1}")]
469    InsufficientFundsInVoteAccount(u64, u64),
470}
471
472/// Bank's common fields shared by all supported snapshot versions for deserialization.
473/// Sync fields with BankFieldsToSerialize! This is paired with it.
474/// All members are made public to remain Bank's members private and to make versioned deserializer workable on this
475/// Note that some fields are missing from the serializer struct. This is because of fields added later.
476/// Since it is difficult to insert fields to serialize/deserialize against existing code already deployed,
477/// new fields can be optionally serialized and optionally deserialized. At some point, the serialization and
478/// deserialization will use a new mechanism or otherwise be in sync more clearly.
479#[derive(Clone, Debug)]
480#[cfg_attr(
481    feature = "dev-context-only-utils",
482    field_qualifiers(
483        blockhash_queue(pub),
484        hash(pub),
485        parent_hash(pub),
486        parent_slot(pub),
487        hard_forks(pub),
488        transaction_count(pub),
489        tick_height(pub),
490        signature_count(pub),
491        capitalization(pub),
492        max_tick_height(pub),
493        hashes_per_tick(pub),
494        ticks_per_slot(pub),
495        ns_per_slot(pub),
496        genesis_creation_time(pub),
497        slots_per_year(pub),
498        slot(pub),
499        block_height(pub),
500        leader_id(pub),
501        fee_rate_governor(pub),
502        epoch_schedule(pub),
503        inflation(pub),
504        stakes(pub),
505        is_delta(pub),
506        accounts_data_len(pub),
507        versioned_epoch_stakes(pub),
508        accounts_lt_hash(pub),
509        bank_hash_stats(pub),
510        block_id(pub),
511    )
512)]
513pub struct BankFieldsToDeserialize {
514    pub(crate) blockhash_queue: BlockhashQueue,
515    pub(crate) hash: Hash,
516    pub(crate) parent_hash: Hash,
517    pub(crate) parent_slot: Slot,
518    pub(crate) hard_forks: HardForks,
519    pub(crate) transaction_count: u64,
520    pub(crate) tick_height: u64,
521    pub(crate) signature_count: u64,
522    pub(crate) capitalization: u64,
523    pub(crate) max_tick_height: u64,
524    pub(crate) hashes_per_tick: Option<u64>,
525    pub(crate) ticks_per_slot: u64,
526    pub(crate) ns_per_slot: u128,
527    pub(crate) genesis_creation_time: UnixTimestamp,
528    pub(crate) slots_per_year: f64,
529    pub(crate) slot: Slot,
530    pub(crate) block_height: u64,
531    pub(crate) leader_id: Pubkey,
532    pub(crate) fee_rate_governor: FeeRateGovernor,
533    pub(crate) epoch_schedule: EpochSchedule,
534    pub(crate) inflation: Inflation,
535    pub(crate) stakes: DeserializableDelegationStakes,
536    /// Transformed into `HashMap<Epoch, VersionedEpochStakes>` in `serde_snapshot` and passed to
537    /// `Bank::new_from_snapshot` as separate parameter for performance (conversion is time consuming)
538    pub(crate) versioned_epoch_stakes: Vec<(Epoch, DeserializableVersionedEpochStakes)>,
539    pub(crate) is_delta: bool,
540    pub(crate) accounts_data_len: u64,
541    pub(crate) accounts_lt_hash: AccountsLtHash,
542    pub(crate) bank_hash_stats: BankHashStats,
543    pub(crate) block_id: Option<Hash>, // Option wrapper can be removed in version after v4.1
544}
545
546#[cfg(feature = "dev-context-only-utils")]
547impl Default for BankFieldsToDeserialize {
548    fn default() -> Self {
549        Self {
550            blockhash_queue: BlockhashQueue::default(),
551            hash: Hash::default(),
552            parent_hash: Hash::default(),
553            parent_slot: Slot::default(),
554            hard_forks: HardForks::default(),
555            transaction_count: u64::default(),
556            tick_height: u64::default(),
557            signature_count: u64::default(),
558            capitalization: u64::default(),
559            max_tick_height: u64::default(),
560            hashes_per_tick: Option::<u64>::default(),
561            ticks_per_slot: u64::default(),
562            ns_per_slot: u128::default(),
563            genesis_creation_time: UnixTimestamp::default(),
564            slots_per_year: f64::default(),
565            slot: Slot::default(),
566            block_height: u64::default(),
567            leader_id: Pubkey::default(),
568            fee_rate_governor: FeeRateGovernor::default(),
569            epoch_schedule: EpochSchedule::default(),
570            inflation: Inflation::default(),
571            stakes: DeserializableDelegationStakes {
572                vote_accounts: VoteAccounts::default(),
573                stake_delegations: Vec::default(),
574                unused: u64::default(),
575                epoch: Epoch::default(),
576                stake_history: CowStakeHistory::default(),
577            },
578            versioned_epoch_stakes: Vec::default(),
579            is_delta: bool::default(),
580            accounts_data_len: u64::default(),
581            accounts_lt_hash: AccountsLtHash(LtHash::identity()),
582            bank_hash_stats: BankHashStats::default(),
583            block_id: Option::<Hash>::default(),
584        }
585    }
586}
587
588/// Bank's common fields shared by all supported snapshot versions for serialization.
589/// This was separated from BankFieldsToDeserialize to avoid cloning by using refs.
590/// So, sync fields with BankFieldsToDeserialize!
591/// all members are made public to keep Bank private and to make versioned serializer workable on this.
592/// Note that some fields are missing from the serializer struct. This is because of fields added later.
593/// Since it is difficult to insert fields to serialize/deserialize against existing code already deployed,
594/// new fields can be optionally serialized and optionally deserialized. At some point, the serialization and
595/// deserialization will use a new mechanism or otherwise be in sync more clearly.
596#[derive(Debug)]
597pub struct BankFieldsToSerialize {
598    pub blockhash_queue: BlockhashQueue,
599    pub hash: Hash,
600    pub parent_hash: Hash,
601    pub parent_slot: Slot,
602    pub hard_forks: HardForks,
603    pub transaction_count: u64,
604    pub tick_height: u64,
605    pub signature_count: u64,
606    pub capitalization: u64,
607    pub max_tick_height: u64,
608    pub hashes_per_tick: Option<u64>,
609    pub ticks_per_slot: u64,
610    pub ns_per_slot: u128,
611    pub genesis_creation_time: UnixTimestamp,
612    pub slots_per_year: f64,
613    pub slot: Slot,
614    pub block_height: u64,
615    pub leader_id: Pubkey,
616    pub fee_rate_governor: FeeRateGovernor,
617    pub epoch_schedule: EpochSchedule,
618    pub inflation: Inflation,
619    pub stakes: Stakes<StakeAccount<Delegation>>,
620    pub is_delta: bool,
621    pub accounts_data_len: u64,
622    pub versioned_epoch_stakes: HashMap<u64, VersionedEpochStakes>,
623    pub accounts_lt_hash: AccountsLtHash,
624    pub block_id: Hash,
625}
626
627// Can't derive PartialEq because RwLock doesn't implement PartialEq
628#[cfg(feature = "dev-context-only-utils")]
629impl PartialEq for Bank {
630    fn eq(&self, other: &Self) -> bool {
631        if std::ptr::eq(self, other) {
632            return true;
633        }
634        // Suppress rustfmt until https://github.com/rust-lang/rustfmt/issues/5920 is fixed ...
635        #[rustfmt::skip]
636        let Self {
637            rc: _,
638            status_cache: _,
639            store_transaction_signatures_in_status_cache,
640            blockhash_queue,
641            max_processing_age,
642            partitioned_rewards_stake_account_stores_per_block,
643            ancestors: _,
644            hash,
645            parent_hash,
646            parent_slot,
647            hard_forks,
648            transaction_count,
649            non_vote_transaction_count_since_restart: _,
650            transaction_error_count: _,
651            transaction_entries_count: _,
652            transactions_per_entry_max: _,
653            entry_bytes_consumed: _,
654            tick_height,
655            signature_count,
656            capitalization,
657            max_tick_height,
658            hashes_per_tick,
659            ticks_per_slot,
660            ns_per_slot,
661            genesis_creation_time,
662            slots_per_year,
663            slot_params: _,
664            slot,
665            bank_id: _,
666            epoch,
667            block_height,
668            leader,
669            fee_rate_governor,
670            rent_collector,
671            epoch_schedule,
672            inflation,
673            stakes_cache,
674            epoch_stakes,
675            is_delta,
676            #[cfg(feature = "dev-context-only-utils")]
677            hash_overrides,
678            accounts_lt_hash,
679            is_alpenglow,
680            // TODO: Confirm if all these fields are intentionally ignored!
681            rewards: _,
682            cluster_type: _,
683            transaction_debug_keys: _,
684            transaction_log_collector_config: _,
685            transaction_log_collector: _,
686            feature_set: _,
687            reserved_account_keys: _,
688            drop_callback: _,
689            freeze_started: _,
690            vote_only_bank: _,
691            cost_tracker: _,
692            accounts_data_size_initial: _,
693            accounts_data_size_delta_on_chain: _,
694            accounts_data_size_delta_off_chain: _,
695            epoch_reward_status: _,
696            transaction_processor: _,
697            check_program_deployment_slot: _,
698            collector_fee_details: _,
699            compute_budget: _,
700            transaction_account_lock_limit: _,
701            fee_structure: _,
702            accounts_lt_hash_async_progress: _,
703            block_id,
704            expected_bank_hash: _,
705            bank_hash_stats: _,
706            epoch_rewards_calculation_cache: _,
707            block_component_processor: _,
708            // Ignore new fields explicitly if they do not impact PartialEq.
709            // Adding ".." will remove compile-time checks that if a new field
710            // is added to the struct, this PartialEq is accordingly updated.
711        } = self;
712        *store_transaction_signatures_in_status_cache
713            == other.store_transaction_signatures_in_status_cache
714            && *blockhash_queue.read().unwrap() == *other.blockhash_queue.read().unwrap()
715            && *max_processing_age == other.max_processing_age
716            && *partitioned_rewards_stake_account_stores_per_block
717                == other.partitioned_rewards_stake_account_stores_per_block
718            && *hash.read().unwrap() == *other.hash.read().unwrap()
719            && parent_hash == &other.parent_hash
720            && parent_slot == &other.parent_slot
721            && *hard_forks.read().unwrap() == *other.hard_forks.read().unwrap()
722            && transaction_count.load(Relaxed) == other.transaction_count.load(Relaxed)
723            && tick_height.load(Relaxed) == other.tick_height.load(Relaxed)
724            && signature_count.load(Relaxed) == other.signature_count.load(Relaxed)
725            && capitalization.load(Relaxed) == other.capitalization.load(Relaxed)
726            && max_tick_height == &other.max_tick_height
727            && *hashes_per_tick.read().unwrap() == *other.hashes_per_tick.read().unwrap()
728            && ticks_per_slot == &other.ticks_per_slot
729            && ns_per_slot == &other.ns_per_slot
730            && genesis_creation_time == &other.genesis_creation_time
731            && slots_per_year == &other.slots_per_year
732            && slot == &other.slot
733            && epoch == &other.epoch
734            && block_height == &other.block_height
735            && leader == &other.leader
736            && fee_rate_governor == &other.fee_rate_governor
737            && rent_collector == &other.rent_collector
738            && epoch_schedule == &other.epoch_schedule
739            && *inflation.read().unwrap() == *other.inflation.read().unwrap()
740            && *stakes_cache.stakes() == *other.stakes_cache.stakes()
741            && epoch_stakes == &other.epoch_stakes
742            && is_delta.load(Relaxed) == other.is_delta.load(Relaxed)
743            // No deadlock is possible, when Arc::ptr_eq() returns false, because of being
744            // different Mutexes.
745            && (Arc::ptr_eq(hash_overrides, &other.hash_overrides) ||
746                *hash_overrides.lock().unwrap() == *other.hash_overrides.lock().unwrap())
747            && *accounts_lt_hash.lock().unwrap() == *other.accounts_lt_hash.lock().unwrap()
748            && *block_id.read().unwrap() == *other.block_id.read().unwrap()
749            && is_alpenglow.load(Relaxed) == other.is_alpenglow()
750    }
751}
752
753#[cfg(feature = "dev-context-only-utils")]
754impl BankFieldsToSerialize {
755    /// Create a new BankFieldsToSerialize where basically every field is defaulted.
756    /// Only use for tests; many of the fields are invalid!
757    pub fn default_for_tests() -> Self {
758        Self {
759            blockhash_queue: BlockhashQueue::default(),
760            hash: Hash::default(),
761            parent_hash: Hash::default(),
762            parent_slot: Slot::default(),
763            hard_forks: HardForks::default(),
764            transaction_count: u64::default(),
765            tick_height: u64::default(),
766            signature_count: u64::default(),
767            capitalization: u64::default(),
768            max_tick_height: u64::default(),
769            hashes_per_tick: Option::default(),
770            ticks_per_slot: u64::default(),
771            ns_per_slot: u128::default(),
772            genesis_creation_time: UnixTimestamp::default(),
773            slots_per_year: f64::default(),
774            slot: Slot::default(),
775            block_height: u64::default(),
776            leader_id: Pubkey::default(),
777            fee_rate_governor: FeeRateGovernor::default(),
778            epoch_schedule: EpochSchedule::default(),
779            inflation: Inflation::default(),
780            stakes: Stakes::<StakeAccount<Delegation>>::default(),
781            is_delta: bool::default(),
782            accounts_data_len: u64::default(),
783            versioned_epoch_stakes: HashMap::default(),
784            accounts_lt_hash: AccountsLtHash(LtHash([0x7E57; LtHash::NUM_ELEMENTS])),
785            block_id: Hash::default(),
786        }
787    }
788}
789
790#[derive(Debug)]
791pub enum RewardCalculationEvent<'a, 'b> {
792    Staking(&'a Pubkey, &'b InflationPointCalculationEvent),
793}
794/// type alias is not supported for trait in rust yet. As a workaround, we define the
795/// `RewardCalcTracer` trait explicitly and implement it on any type that implement
796/// `Fn(&RewardCalculationEvent) + Send + Sync`.
797pub trait RewardCalcTracer: Fn(&RewardCalculationEvent) + Send + Sync {}
798
799impl<T: Fn(&RewardCalculationEvent) + Send + Sync> RewardCalcTracer for T {}
800
801fn null_tracer() -> Option<impl RewardCalcTracer> {
802    None::<fn(&RewardCalculationEvent)>
803}
804
805pub trait DropCallback: fmt::Debug {
806    fn callback(&self, b: &Bank);
807    fn clone_box(&self) -> Box<dyn DropCallback + Send + Sync>;
808}
809
810#[derive(Debug, Default)]
811pub struct OptionalDropCallback(Option<Box<dyn DropCallback + Send + Sync>>);
812
813#[derive(Default, Debug, Clone, PartialEq)]
814#[cfg(feature = "dev-context-only-utils")]
815pub struct HashOverrides {
816    hashes: HashMap<Slot, HashOverride>,
817}
818
819#[cfg(feature = "dev-context-only-utils")]
820impl HashOverrides {
821    fn get_hash_override(&self, slot: Slot) -> Option<&HashOverride> {
822        self.hashes.get(&slot)
823    }
824
825    fn get_blockhash_override(&self, slot: Slot) -> Option<&Hash> {
826        self.get_hash_override(slot)
827            .map(|hash_override| &hash_override.blockhash)
828    }
829
830    fn get_bank_hash_override(&self, slot: Slot) -> Option<&Hash> {
831        self.get_hash_override(slot)
832            .map(|hash_override| &hash_override.bank_hash)
833    }
834
835    pub fn add_override(&mut self, slot: Slot, blockhash: Hash, bank_hash: Hash) {
836        let is_new = self
837            .hashes
838            .insert(
839                slot,
840                HashOverride {
841                    blockhash,
842                    bank_hash,
843                },
844            )
845            .is_none();
846        assert!(is_new);
847    }
848}
849
850#[derive(Debug, Clone, PartialEq)]
851#[cfg(feature = "dev-context-only-utils")]
852struct HashOverride {
853    blockhash: Hash,
854    bank_hash: Hash,
855}
856
857/// Manager for the state of all accounts and programs after processing its entries.
858pub struct Bank {
859    /// References to accounts, parent and signature status
860    pub rc: BankRc,
861
862    /// A cache of signature statuses
863    pub status_cache: Arc<RwLock<BankStatusCache>>,
864
865    /// Derived from RuntimeConfig::skip_transaction_signatures_in_status_cache.
866    store_transaction_signatures_in_status_cache: bool,
867
868    /// FIFO queue of `recent_blockhash` items
869    blockhash_queue: RwLock<BlockhashQueue>,
870
871    /// Maximum age in slots a blockhash can be for a tx to be processed.
872    max_processing_age: usize,
873
874    /// Number of stake accounts to store in each block during partitioned rewards.
875    partitioned_rewards_stake_account_stores_per_block: u64,
876
877    /// The set of parents including this bank
878    pub ancestors: Ancestors,
879
880    /// Hash of this Bank's state. Only meaningful after freezing.
881    hash: RwLock<Hash>,
882
883    /// Hash of this Bank's parent's state
884    parent_hash: Hash,
885
886    /// parent's slot
887    parent_slot: Slot,
888
889    /// slots to hard fork at
890    hard_forks: Arc<RwLock<HardForks>>,
891
892    /// The number of committed transactions since genesis.
893    transaction_count: AtomicU64,
894
895    /// The number of non-vote transactions committed since the most
896    /// recent boot from snapshot or genesis. This value is only stored in
897    /// blockstore for the RPC method "getPerformanceSamples". It is not
898    /// retained within snapshots, but is preserved in `Bank::new_from_parent`.
899    non_vote_transaction_count_since_restart: AtomicU64,
900
901    /// The number of transaction errors in this slot
902    transaction_error_count: AtomicU64,
903
904    /// The number of transaction entries in this slot
905    transaction_entries_count: AtomicU64,
906
907    /// The max number of transaction in an entry in this slot
908    transactions_per_entry_max: AtomicU64,
909
910    /// The number of entry bytes reserved for recording in this slot.
911    entry_bytes_consumed: EntryBytesBudget,
912
913    /// Bank tick height
914    tick_height: AtomicU64,
915
916    /// The number of signatures from valid transactions in this slot
917    signature_count: AtomicU64,
918
919    /// Total capitalization, used to calculate inflation
920    capitalization: AtomicU64,
921
922    // Bank max_tick_height
923    max_tick_height: u64,
924
925    /// The number of hashes in each tick. None value means hashing is disabled.
926    hashes_per_tick: RwLock<Option<u64>>,
927
928    /// The number of ticks in each slot.
929    ticks_per_slot: u64,
930
931    /// length of a slot in ns
932    pub ns_per_slot: u128,
933
934    /// genesis time, used for computed clock
935    genesis_creation_time: UnixTimestamp,
936
937    /// The number of slots per year, used for inflation
938    slots_per_year: f64,
939
940    /// Slot-scoped parameter history used for slot-relative parameter lookups.
941    slot_params: SlotParamsArchive,
942
943    /// Bank slot (i.e. block)
944    slot: Slot,
945
946    bank_id: BankId,
947
948    /// Bank epoch
949    epoch: Epoch,
950
951    /// Bank block_height
952    block_height: u64,
953
954    /// The leader who produced this block
955    leader: SlotLeader,
956
957    /// Track cluster signature throughput and adjust fee rate
958    pub(crate) fee_rate_governor: FeeRateGovernor,
959
960    /// latest rent collector, knows the epoch
961    rent_collector: RentCollector,
962
963    /// initialized from genesis
964    pub(crate) epoch_schedule: EpochSchedule,
965
966    /// inflation specs
967    inflation: Arc<RwLock<Inflation>>,
968
969    /// cache of vote_account and stake_account state for this fork
970    stakes_cache: StakesCache,
971
972    /// staked nodes on epoch boundaries, saved off when a bank.slot() is at
973    ///   a leader schedule calculation boundary
974    epoch_stakes: HashMap<Epoch, VersionedEpochStakes>,
975
976    /// A boolean reflecting whether any entries were recorded into the PoH
977    /// stream for the slot == self.slot
978    is_delta: AtomicBool,
979
980    /// Protocol-level rewards that were distributed by this bank
981    pub rewards: RwLock<Vec<(Pubkey, RewardInfo)>>,
982
983    pub cluster_type: Option<ClusterType>,
984
985    transaction_debug_keys: Option<Arc<HashSet<Pubkey>>>,
986
987    // Global configuration for how transaction logs should be collected across all banks
988    pub transaction_log_collector_config: Arc<RwLock<TransactionLogCollectorConfig>>,
989
990    // Logs from transactions that this Bank executed collected according to the criteria in
991    // `transaction_log_collector_config`
992    pub transaction_log_collector: Arc<RwLock<TransactionLogCollector>>,
993
994    pub feature_set: Arc<FeatureSet>,
995
996    /// Set of reserved account keys that cannot be write locked
997    reserved_account_keys: Arc<ReservedAccountKeys>,
998
999    /// callback function only to be called when dropping and should only be called once
1000    pub drop_callback: RwLock<OptionalDropCallback>,
1001
1002    pub freeze_started: AtomicBool,
1003
1004    vote_only_bank: bool,
1005
1006    cost_tracker: RwLock<CostTracker>,
1007
1008    /// The initial accounts data size at the start of this Bank, before processing any transactions/etc
1009    accounts_data_size_initial: u64,
1010    /// The change to accounts data size in this Bank, due on-chain events (i.e. transactions)
1011    accounts_data_size_delta_on_chain: AtomicI64,
1012    /// The change to accounts data size in this Bank, due to off-chain events (i.e. rent collection)
1013    accounts_data_size_delta_off_chain: AtomicI64,
1014
1015    epoch_reward_status: EpochRewardStatus,
1016
1017    transaction_processor: TransactionBatchProcessor<BankForks>,
1018
1019    check_program_deployment_slot: bool,
1020
1021    /// Collected fee details
1022    collector_fee_details: RwLock<CollectorFeeDetails>,
1023
1024    /// The compute budget to use for transaction execution.
1025    compute_budget: Option<ComputeBudget>,
1026
1027    /// The max number of accounts that a transaction may lock.
1028    transaction_account_lock_limit: Option<usize>,
1029
1030    /// Fee structure to use for assessing transaction fees.
1031    fee_structure: FeeStructure,
1032
1033    /// blockhash and bank_hash overrides keyed by slot for simulated block production.
1034    /// This _field_ was needed to be DCOU-ed to avoid 2 locks per bank freezing...
1035    #[cfg(feature = "dev-context-only-utils")]
1036    hash_overrides: Arc<Mutex<HashOverrides>>,
1037
1038    /// The lattice hash of all accounts
1039    ///
1040    /// The value is only meaningful after freezing.
1041    accounts_lt_hash: Mutex<AccountsLtHash>,
1042
1043    /// Track progress of the asynchronous accounts lt hashing for this Bank.
1044    accounts_lt_hash_async_progress: AccountsLtHashAsyncProgress,
1045
1046    /// The unique identifier for the corresponding block for this bank.
1047    /// None for banks that have not yet completed replay or for leader banks as we cannot populate block_id
1048    /// until bankless leader. Can be computed directly from shreds without needing to execute transactions.
1049    block_id: RwLock<Option<Hash>>,
1050
1051    /// Expected bank hash provided by block footer (if any). Set when processing footer; verified
1052    /// later when the bank is frozen.
1053    expected_bank_hash: RwLock<Option<Hash>>,
1054
1055    /// Accounts stats for computing the bank hash
1056    bank_hash_stats: AtomicBankHashStats,
1057
1058    /// The cache of epoch rewards calculation results
1059    /// This is used to avoid recalculating the same epoch rewards at epoch boundary.
1060    /// The hashmap is keyed by parent_hash.
1061    epoch_rewards_calculation_cache: Arc<Mutex<HashMap<Hash, Arc<PartitionedRewardsCalculation>>>>,
1062
1063    /// Block component processor for validating block headers/footers and clock bounds. We
1064    /// currently write to this during replay, as we process block components one at a time, and
1065    /// read from this once replay is complete.
1066    pub block_component_processor: RwLock<BlockComponentProcessor>,
1067
1068    /// Cached Alpenglow migration state, derived from the genesis certificate account.
1069    is_alpenglow: AtomicBool,
1070}
1071
1072#[derive(Debug, Default)]
1073pub struct NewBankOptions {
1074    pub vote_only_bank: bool,
1075}
1076
1077#[cfg(feature = "dev-context-only-utils")]
1078#[derive(Debug)]
1079pub struct BankTestConfig {
1080    pub accounts_db_config: AccountsDbConfig,
1081}
1082
1083#[cfg(feature = "dev-context-only-utils")]
1084impl Default for BankTestConfig {
1085    fn default() -> Self {
1086        Self {
1087            accounts_db_config: ACCOUNTS_DB_CONFIG_FOR_TESTING,
1088        }
1089    }
1090}
1091
1092#[derive(Debug, Default, PartialEq)]
1093pub struct ProcessedTransactionCounts {
1094    pub processed_transactions_count: u64,
1095    pub processed_non_vote_transactions_count: u64,
1096    pub processed_with_successful_result_count: u64,
1097    pub signature_count: u64,
1098}
1099
1100/// Account stats for computing the bank hash
1101/// This struct is serialized and stored in the snapshot.
1102#[repr(C)]
1103#[cfg_attr(feature = "frozen-abi", derive(AbiExample, StableAbi, StableAbiSample))]
1104#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, SchemaRead, SchemaWrite)]
1105pub struct BankHashStats {
1106    pub num_updated_accounts: u64,
1107    pub num_removed_accounts: u64,
1108    pub num_lamports_stored: u64,
1109    pub total_data_len: u64,
1110    pub num_executable_accounts: u64,
1111}
1112
1113impl BankHashStats {
1114    pub fn update<T: ReadableAccount>(&mut self, account: &T) {
1115        if account.lamports() == 0 {
1116            self.num_removed_accounts += 1;
1117        } else {
1118            self.num_updated_accounts += 1;
1119        }
1120        self.total_data_len = self
1121            .total_data_len
1122            .wrapping_add(account.data().len() as u64);
1123        if account.executable() {
1124            self.num_executable_accounts += 1;
1125        }
1126        self.num_lamports_stored = self.num_lamports_stored.wrapping_add(account.lamports());
1127    }
1128    pub fn accumulate(&mut self, other: &BankHashStats) {
1129        self.num_updated_accounts += other.num_updated_accounts;
1130        self.num_removed_accounts += other.num_removed_accounts;
1131        self.total_data_len = self.total_data_len.wrapping_add(other.total_data_len);
1132        self.num_lamports_stored = self
1133            .num_lamports_stored
1134            .wrapping_add(other.num_lamports_stored);
1135        self.num_executable_accounts += other.num_executable_accounts;
1136    }
1137}
1138
1139#[derive(Debug, Default)]
1140pub struct AtomicBankHashStats {
1141    pub num_updated_accounts: AtomicU64,
1142    pub num_removed_accounts: AtomicU64,
1143    pub num_lamports_stored: AtomicU64,
1144    pub total_data_len: AtomicU64,
1145    pub num_executable_accounts: AtomicU64,
1146}
1147
1148impl AtomicBankHashStats {
1149    pub fn new(stat: &BankHashStats) -> Self {
1150        AtomicBankHashStats {
1151            num_updated_accounts: AtomicU64::new(stat.num_updated_accounts),
1152            num_removed_accounts: AtomicU64::new(stat.num_removed_accounts),
1153            num_lamports_stored: AtomicU64::new(stat.num_lamports_stored),
1154            total_data_len: AtomicU64::new(stat.total_data_len),
1155            num_executable_accounts: AtomicU64::new(stat.num_executable_accounts),
1156        }
1157    }
1158
1159    pub fn accumulate(&self, other: &BankHashStats) {
1160        self.num_updated_accounts
1161            .fetch_add(other.num_updated_accounts, Relaxed);
1162        self.num_removed_accounts
1163            .fetch_add(other.num_removed_accounts, Relaxed);
1164        self.total_data_len.fetch_add(other.total_data_len, Relaxed);
1165        self.num_lamports_stored
1166            .fetch_add(other.num_lamports_stored, Relaxed);
1167        self.num_executable_accounts
1168            .fetch_add(other.num_executable_accounts, Relaxed);
1169    }
1170
1171    pub fn load(&self) -> BankHashStats {
1172        BankHashStats {
1173            num_updated_accounts: self.num_updated_accounts.load(Relaxed),
1174            num_removed_accounts: self.num_removed_accounts.load(Relaxed),
1175            num_lamports_stored: self.num_lamports_stored.load(Relaxed),
1176            total_data_len: self.total_data_len.load(Relaxed),
1177            num_executable_accounts: self.num_executable_accounts.load(Relaxed),
1178        }
1179    }
1180}
1181
1182struct NewEpochBundle {
1183    stake_history: CowStakeHistory,
1184    /// Vote accounts computed from the stakes cache for the current
1185    /// (distribution) epoch *before* applying any VAT filtering.
1186    unfiltered_distribution_vote_accounts: VoteAccounts,
1187    /// Current effective stake delegated to each vote account pubkey.
1188    delegated_stakes: DelegatedStakes,
1189    /// Vote accounts computed from the stakes cache for the current
1190    /// (distribution) epoch *after* applying VAT filtering.
1191    filtered_distribution_vote_accounts: VoteAccounts,
1192    rewards_calculation: Arc<PartitionedRewardsCalculation>,
1193    calculate_activated_stake_time_us: u64,
1194    update_rewards_with_thread_pool_time_us: u64,
1195}
1196
1197impl Bank {
1198    fn default_with_accounts(accounts: Accounts) -> Self {
1199        let partitioned_rewards_stake_account_stores_per_block = accounts
1200            .accounts_db
1201            .partitioned_epoch_rewards_config
1202            .stake_account_stores_per_block;
1203        let mut bank = Self {
1204            rc: BankRc::new(accounts),
1205            status_cache: Arc::<RwLock<BankStatusCache>>::default(),
1206            store_transaction_signatures_in_status_cache: !RuntimeConfig::default()
1207                .skip_transaction_signatures_in_status_cache,
1208            blockhash_queue: RwLock::<BlockhashQueue>::default(),
1209            max_processing_age: MAX_PROCESSING_AGE,
1210            partitioned_rewards_stake_account_stores_per_block,
1211            ancestors: Ancestors::default(),
1212            hash: RwLock::<Hash>::default(),
1213            parent_hash: Hash::default(),
1214            parent_slot: Slot::default(),
1215            hard_forks: Arc::<RwLock<HardForks>>::default(),
1216            transaction_count: AtomicU64::default(),
1217            non_vote_transaction_count_since_restart: AtomicU64::default(),
1218            transaction_error_count: AtomicU64::default(),
1219            transaction_entries_count: AtomicU64::default(),
1220            transactions_per_entry_max: AtomicU64::default(),
1221            entry_bytes_consumed: EntryBytesBudget::new(DEFAULT_MAX_ENTRY_BYTES_PER_SLOT),
1222            tick_height: AtomicU64::default(),
1223            signature_count: AtomicU64::default(),
1224            capitalization: AtomicU64::default(),
1225            max_tick_height: u64::default(),
1226            hashes_per_tick: RwLock::default(),
1227            ticks_per_slot: u64::default(),
1228            ns_per_slot: u128::default(),
1229            genesis_creation_time: UnixTimestamp::default(),
1230            slots_per_year: f64::default(),
1231            slot_params: SlotParamsArchive::default(),
1232            slot: Slot::default(),
1233            bank_id: BankId::default(),
1234            epoch: Epoch::default(),
1235            block_height: u64::default(),
1236            leader: SlotLeader::default(),
1237            fee_rate_governor: FeeRateGovernor::default(),
1238            rent_collector: RentCollector::default(),
1239            epoch_schedule: EpochSchedule::default(),
1240            inflation: Arc::<RwLock<Inflation>>::default(),
1241            stakes_cache: StakesCache::default(),
1242            epoch_stakes: HashMap::<Epoch, VersionedEpochStakes>::default(),
1243            is_delta: AtomicBool::default(),
1244            rewards: RwLock::<Vec<(Pubkey, RewardInfo)>>::default(),
1245            cluster_type: Option::<ClusterType>::default(),
1246            transaction_debug_keys: Option::<Arc<HashSet<Pubkey>>>::default(),
1247            transaction_log_collector_config: Arc::<RwLock<TransactionLogCollectorConfig>>::default(
1248            ),
1249            transaction_log_collector: Arc::<RwLock<TransactionLogCollector>>::default(),
1250            feature_set: Arc::<FeatureSet>::default(),
1251            reserved_account_keys: Arc::<ReservedAccountKeys>::default(),
1252            drop_callback: RwLock::new(OptionalDropCallback(None)),
1253            freeze_started: AtomicBool::default(),
1254            vote_only_bank: false,
1255            cost_tracker: RwLock::<CostTracker>::default(),
1256            accounts_data_size_initial: 0,
1257            accounts_data_size_delta_on_chain: AtomicI64::new(0),
1258            accounts_data_size_delta_off_chain: AtomicI64::new(0),
1259            epoch_reward_status: EpochRewardStatus::default(),
1260            transaction_processor: TransactionBatchProcessor::default(),
1261            check_program_deployment_slot: false,
1262            collector_fee_details: RwLock::new(CollectorFeeDetails::default()),
1263            compute_budget: None,
1264            transaction_account_lock_limit: None,
1265            fee_structure: FeeStructure::default(),
1266            #[cfg(feature = "dev-context-only-utils")]
1267            hash_overrides: Arc::new(Mutex::new(HashOverrides::default())),
1268            accounts_lt_hash: Mutex::new(AccountsLtHash(LtHash::identity())),
1269            accounts_lt_hash_async_progress: AccountsLtHashAsyncProgress::new(),
1270            block_id: RwLock::new(None),
1271            expected_bank_hash: RwLock::new(None),
1272            bank_hash_stats: AtomicBankHashStats::default(),
1273            epoch_rewards_calculation_cache: Arc::new(Mutex::new(HashMap::default())),
1274            block_component_processor: RwLock::new(BlockComponentProcessor::default()),
1275            is_alpenglow: AtomicBool::new(false),
1276        };
1277
1278        bank.transaction_processor =
1279            TransactionBatchProcessor::new_uninitialized(bank.slot, bank.epoch);
1280
1281        bank.accounts_data_size_initial = bank.calculate_accounts_data_size().unwrap();
1282
1283        bank
1284    }
1285
1286    #[expect(clippy::too_many_arguments)]
1287    pub fn new_from_genesis(
1288        genesis_config: &GenesisConfig,
1289        runtime_config: Arc<RuntimeConfig>,
1290        paths: Vec<PathBuf>,
1291        debug_keys: Option<Arc<HashSet<Pubkey>>>,
1292        accounts_db_config: AccountsDbConfig,
1293        accounts_update_notifier: Option<AccountsUpdateNotifier>,
1294        #[cfg_attr(not(feature = "dev-context-only-utils"), expect(unused))]
1295        leader_for_tests: Option<SlotLeader>,
1296        exit: Arc<AtomicBool>,
1297        #[cfg_attr(not(feature = "dev-context-only-utils"), expect(unused))] genesis_hash: Option<
1298            Hash,
1299        >,
1300        #[cfg_attr(not(feature = "dev-context-only-utils"), expect(unused))] feature_set: Option<
1301            FeatureSet,
1302        >,
1303    ) -> Self {
1304        // Initialize the rewards thread pool while creating the first bank so
1305        // the first epoch boundary crossing does not pay the cost.
1306        let _rewards_calculation_thread_pool = rewards_calculation_thread_pool();
1307        let accounts_db =
1308            AccountsDb::new_with_config(paths, accounts_db_config, accounts_update_notifier, exit);
1309        let accounts = Accounts::new(Arc::new(accounts_db));
1310        let mut bank = Self::default_with_accounts(accounts);
1311        bank.ancestors = Ancestors::from(vec![bank.slot()]);
1312        bank.compute_budget = runtime_config.compute_budget;
1313        bank.store_transaction_signatures_in_status_cache =
1314            !runtime_config.skip_transaction_signatures_in_status_cache;
1315        if let Some(compute_budget) = &bank.compute_budget {
1316            bank.transaction_processor
1317                .set_execution_cost(compute_budget.to_cost());
1318        }
1319        bank.transaction_account_lock_limit = runtime_config.transaction_account_lock_limit;
1320        bank.transaction_debug_keys = debug_keys;
1321        bank.cluster_type = Some(genesis_config.cluster_type);
1322
1323        #[cfg(feature = "dev-context-only-utils")]
1324        {
1325            bank.feature_set = Arc::new(feature_set.unwrap_or_default());
1326        }
1327
1328        #[cfg(not(feature = "dev-context-only-utils"))]
1329        bank.process_genesis_config(genesis_config);
1330        #[cfg(feature = "dev-context-only-utils")]
1331        bank.process_genesis_config(genesis_config, leader_for_tests, genesis_hash);
1332
1333        bank.compute_and_apply_genesis_features();
1334
1335        // genesis needs stakes for all epochs up to the epoch implied by
1336        //  slot = 0 and genesis configuration
1337        {
1338            let stakes = bank.get_top_epoch_stakes();
1339            let stakes = SerdeStakesToStakeFormat::from(stakes);
1340            for epoch in 0..=bank.get_leader_schedule_epoch(bank.slot) {
1341                bank.epoch_stakes
1342                    .insert(epoch, VersionedEpochStakes::new(stakes.clone(), epoch));
1343            }
1344            bank.update_stake_history(None);
1345        }
1346        bank.update_clock(None);
1347        bank.update_rent();
1348        bank.update_epoch_schedule();
1349        bank.update_recent_blockhashes();
1350        bank.update_last_restart_slot();
1351        bank.transaction_processor
1352            .fill_missing_sysvar_cache_entries(&bank);
1353        if bank.get_alpenglow_genesis_certificate().is_some() {
1354            bank.set_is_alpenglow();
1355        }
1356        bank
1357    }
1358
1359    /// Create a new bank that points to an immutable checkpoint of another bank.
1360    pub fn new_from_parent(parent: Arc<Bank>, leader: SlotLeader, slot: Slot) -> Self {
1361        Self::_new_from_parent(
1362            parent,
1363            leader,
1364            slot,
1365            null_tracer(),
1366            NewBankOptions::default(),
1367        )
1368    }
1369
1370    pub fn new_from_parent_with_options(
1371        parent: Arc<Bank>,
1372        leader: SlotLeader,
1373        slot: Slot,
1374        new_bank_options: NewBankOptions,
1375    ) -> Self {
1376        Self::_new_from_parent(parent, leader, slot, null_tracer(), new_bank_options)
1377    }
1378
1379    pub fn new_from_parent_with_tracer(
1380        parent: Arc<Bank>,
1381        leader: SlotLeader,
1382        slot: Slot,
1383        reward_calc_tracer: impl RewardCalcTracer,
1384    ) -> Self {
1385        Self::_new_from_parent(
1386            parent,
1387            leader,
1388            slot,
1389            Some(reward_calc_tracer),
1390            NewBankOptions::default(),
1391        )
1392    }
1393
1394    fn get_rent_collector_from(rent_collector: &RentCollector, epoch: Epoch) -> RentCollector {
1395        rent_collector.clone_with_epoch(epoch)
1396    }
1397
1398    fn _new_from_parent(
1399        parent: Arc<Bank>,
1400        leader: SlotLeader,
1401        slot: Slot,
1402        reward_calc_tracer: Option<impl RewardCalcTracer>,
1403        new_bank_options: NewBankOptions,
1404    ) -> Self {
1405        let mut time = Measure::start("bank::new_from_parent");
1406        let NewBankOptions { vote_only_bank } = new_bank_options;
1407
1408        parent.freeze();
1409        assert_ne!(slot, parent.slot());
1410
1411        let epoch_schedule = parent.epoch_schedule().clone();
1412        let epoch = epoch_schedule.get_epoch(slot);
1413
1414        let (rc, bank_rc_creation_time_us) = measure_us!({
1415            let accounts_db = Arc::clone(&parent.rc.accounts.accounts_db);
1416            BankRc {
1417                accounts: Arc::new(Accounts::new(accounts_db)),
1418                parent: RwLock::new(Some(Arc::clone(&parent))),
1419                bank_id_generator: Arc::clone(&parent.rc.bank_id_generator),
1420            }
1421        });
1422
1423        let (status_cache, status_cache_time_us) = measure_us!(Arc::clone(&parent.status_cache));
1424
1425        let (fee_rate_governor, fee_components_time_us) = measure_us!(
1426            FeeRateGovernor::new_derived(&parent.fee_rate_governor, parent.signature_count())
1427        );
1428
1429        let bank_id = rc.bank_id_generator.fetch_add(1, Relaxed) + 1;
1430        let (blockhash_queue, blockhash_queue_time_us) =
1431            measure_us!(RwLock::new(parent.blockhash_queue.read().unwrap().clone()));
1432
1433        let (stakes_cache, stakes_cache_time_us) =
1434            measure_us!(StakesCache::new(parent.stakes_cache.stakes().clone()));
1435
1436        let (epoch_stakes, epoch_stakes_time_us) = measure_us!(parent.epoch_stakes.clone());
1437
1438        let (transaction_processor, builtin_program_ids_time_us) = measure_us!(
1439            TransactionBatchProcessor::new_from(&parent.transaction_processor, slot, epoch)
1440        );
1441
1442        let (transaction_debug_keys, transaction_debug_keys_time_us) =
1443            measure_us!(parent.transaction_debug_keys.clone());
1444
1445        let (transaction_log_collector_config, transaction_log_collector_config_time_us) =
1446            measure_us!(parent.transaction_log_collector_config.clone());
1447
1448        let (feature_set, feature_set_time_us) = measure_us!(parent.feature_set.clone());
1449
1450        let accounts_data_size_initial = parent.load_accounts_data_size();
1451        let mut new = Self {
1452            rc,
1453            status_cache,
1454            store_transaction_signatures_in_status_cache: parent
1455                .store_transaction_signatures_in_status_cache,
1456            slot,
1457            bank_id,
1458            epoch,
1459            blockhash_queue,
1460            max_processing_age: parent.max_processing_age,
1461            partitioned_rewards_stake_account_stores_per_block: parent
1462                .partitioned_rewards_stake_account_stores_per_block,
1463            // TODO: clean this up, so much special-case copying...
1464            hashes_per_tick: RwLock::new(parent.hashes_per_tick()),
1465            ticks_per_slot: parent.ticks_per_slot,
1466            ns_per_slot: parent.ns_per_slot,
1467            genesis_creation_time: parent.genesis_creation_time,
1468            slots_per_year: parent.slots_per_year,
1469            slot_params: parent.slot_params.clone(),
1470            epoch_schedule,
1471            rent_collector: Self::get_rent_collector_from(&parent.rent_collector, epoch),
1472            max_tick_height: slot
1473                .checked_add(1)
1474                .expect("max tick height addition overflowed")
1475                .checked_mul(parent.ticks_per_slot)
1476                .expect("max tick height multiplication overflowed"),
1477            block_height: parent
1478                .block_height
1479                .checked_add(1)
1480                .expect("block height addition overflowed"),
1481            fee_rate_governor,
1482            capitalization: AtomicU64::new(parent.capitalization()),
1483            vote_only_bank,
1484            inflation: parent.inflation.clone(),
1485            transaction_count: AtomicU64::new(parent.transaction_count()),
1486            non_vote_transaction_count_since_restart: AtomicU64::new(
1487                parent.non_vote_transaction_count_since_restart(),
1488            ),
1489            transaction_error_count: AtomicU64::new(0),
1490            transaction_entries_count: AtomicU64::new(0),
1491            transactions_per_entry_max: AtomicU64::new(0),
1492            entry_bytes_consumed: EntryBytesBudget::new(parent.entry_bytes_budget().slot_limit()),
1493            // we will .clone_with_epoch() this soon after stake data update; so just .clone() for now
1494            stakes_cache,
1495            epoch_stakes,
1496            parent_hash: parent.hash(),
1497            parent_slot: parent.slot(),
1498            leader,
1499            ancestors: Ancestors::default(),
1500            hash: RwLock::new(Hash::default()),
1501            is_delta: AtomicBool::new(false),
1502            tick_height: AtomicU64::new(parent.tick_height.load(Relaxed)),
1503            signature_count: AtomicU64::new(0),
1504            hard_forks: parent.hard_forks.clone(),
1505            rewards: RwLock::new(vec![]),
1506            cluster_type: parent.cluster_type,
1507            transaction_debug_keys,
1508            transaction_log_collector_config,
1509            transaction_log_collector: Arc::new(RwLock::new(TransactionLogCollector::default())),
1510            feature_set: Arc::clone(&feature_set),
1511            reserved_account_keys: parent.reserved_account_keys.clone(),
1512            drop_callback: RwLock::new(OptionalDropCallback(
1513                parent
1514                    .drop_callback
1515                    .read()
1516                    .unwrap()
1517                    .0
1518                    .as_ref()
1519                    .map(|drop_callback| drop_callback.clone_box()),
1520            )),
1521            freeze_started: AtomicBool::new(false),
1522            cost_tracker: RwLock::new(parent.read_cost_tracker().unwrap().new_from_parent_limits()),
1523            accounts_data_size_initial,
1524            accounts_data_size_delta_on_chain: AtomicI64::new(0),
1525            accounts_data_size_delta_off_chain: AtomicI64::new(0),
1526            epoch_reward_status: parent.epoch_reward_status.clone(),
1527            transaction_processor,
1528            check_program_deployment_slot: false,
1529            collector_fee_details: RwLock::new(CollectorFeeDetails::default()),
1530            compute_budget: parent.compute_budget,
1531            transaction_account_lock_limit: parent.transaction_account_lock_limit,
1532            fee_structure: parent.fee_structure.clone(),
1533            #[cfg(feature = "dev-context-only-utils")]
1534            hash_overrides: parent.hash_overrides.clone(),
1535            accounts_lt_hash: Mutex::new(parent.accounts_lt_hash.lock().unwrap().clone()),
1536            accounts_lt_hash_async_progress: AccountsLtHashAsyncProgress::new(),
1537            block_id: RwLock::new(None),
1538            expected_bank_hash: RwLock::new(None),
1539            bank_hash_stats: AtomicBankHashStats::default(),
1540            epoch_rewards_calculation_cache: parent.epoch_rewards_calculation_cache.clone(),
1541            block_component_processor: RwLock::new(BlockComponentProcessor::default()),
1542            is_alpenglow: AtomicBool::new(parent.is_alpenglow()),
1543        };
1544
1545        let (_, ancestors_time_us) = measure_us!({
1546            let mut ancestors = Vec::with_capacity(parent.ancestors.len() + 1);
1547            ancestors.push(new.slot());
1548            ancestors.extend(new.parents_iter().map(|parent| parent.slot()));
1549            new.ancestors = Ancestors::from(ancestors);
1550        });
1551
1552        let prepare_timings = new.prepare_for_block_execution(
1553            parent.epoch(),
1554            parent.slot(),
1555            parent.capitalization(),
1556            parent.block_height(),
1557            reward_calc_tracer,
1558        );
1559
1560        time.stop();
1561        report_new_bank_metrics(
1562            slot,
1563            parent.slot(),
1564            new.block_height,
1565            NewBankTimings {
1566                bank_rc_creation_time_us,
1567                total_elapsed_time_us: time.as_us(),
1568                status_cache_time_us,
1569                fee_components_time_us,
1570                blockhash_queue_time_us,
1571                stakes_cache_time_us,
1572                epoch_stakes_time_us,
1573                builtin_program_ids_time_us,
1574                executor_cache_time_us: 0,
1575                transaction_debug_keys_time_us,
1576                transaction_log_collector_config_time_us,
1577                feature_set_time_us,
1578                ancestors_time_us,
1579                update_epoch_time_us: prepare_timings.update_epoch_time_us,
1580                distribute_rewards_time_us: prepare_timings.distribute_rewards_time_us,
1581                cache_preparation_time_us: prepare_timings.cache_preparation_time_us,
1582                update_sysvars_time_us: prepare_timings.update_sysvars_time_us,
1583                fill_sysvar_cache_time_us: prepare_timings.fill_sysvar_cache_time_us,
1584            },
1585        );
1586
1587        report_loaded_programs_stats(
1588            &parent
1589                .transaction_processor
1590                .global_program_cache
1591                .read()
1592                .unwrap(),
1593            parent.slot(),
1594        );
1595
1596        new.transaction_processor
1597            .global_program_cache
1598            .write()
1599            .unwrap()
1600            .stats
1601            .reset();
1602
1603        new
1604    }
1605
1606    pub fn set_fork_graph_in_program_cache(&self, fork_graph: Weak<RwLock<BankForks>>) {
1607        self.transaction_processor
1608            .global_program_cache
1609            .write()
1610            .unwrap()
1611            .set_fork_graph(fork_graph);
1612    }
1613
1614    fn prepare_program_cache_for_upcoming_feature_set(&self) {
1615        let (_epoch, slot_index) = self.epoch_schedule.get_epoch_and_slot_index(self.slot);
1616        let slots_in_epoch = self.epoch_schedule.get_slots_in_epoch(self.epoch);
1617        let (upcoming_feature_set, _newly_activated) = self.compute_active_feature_set(true);
1618
1619        // Recompile loaded programs one at a time before the next epoch hits
1620        let slots_in_recompilation_phase =
1621            (solana_program_runtime::loaded_programs::MAX_LOADED_ENTRY_COUNT as u64)
1622                .min(slots_in_epoch)
1623                .checked_div(2)
1624                .unwrap();
1625
1626        let mut epoch_boundary_preparation = self
1627            .transaction_processor
1628            .epoch_boundary_preparation
1629            .write()
1630            .unwrap();
1631
1632        if let Some(upcoming_environment) = epoch_boundary_preparation.upcoming_environment.as_ref()
1633        {
1634            let upcoming_environment = upcoming_environment.clone();
1635            if let Some((key, program_to_recompile)) =
1636                epoch_boundary_preparation.programs_to_recompile.pop()
1637            {
1638                drop(epoch_boundary_preparation);
1639                self.transaction_processor
1640                    .prepare_one_program_for_upcoming_feature_set(
1641                        self,
1642                        self.check_program_deployment_slot(),
1643                        &upcoming_environment,
1644                        &key,
1645                        &program_to_recompile.stats,
1646                    );
1647            }
1648        } else if slot_index.saturating_add(slots_in_recompilation_phase) >= slots_in_epoch {
1649            // Anticipate the upcoming program runtime environment for the next epoch,
1650            // so we can try to recompile loaded programs before the feature transition hits.
1651            let new_environment = self.create_program_runtime_environment(&upcoming_feature_set);
1652            let mut upcoming_environment = self
1653                .transaction_processor
1654                .program_runtime_environment
1655                .clone();
1656            // Here we actually want to compare the content of the environments, thus the deref.
1657            let changed_program_runtime_environment = *upcoming_environment != *new_environment;
1658            if changed_program_runtime_environment {
1659                upcoming_environment = new_environment;
1660                let program_cache_guard = self
1661                    .transaction_processor
1662                    .global_program_cache
1663                    .read()
1664                    .unwrap();
1665                epoch_boundary_preparation.programs_to_recompile = program_cache_guard
1666                    .get_flattened_entries()
1667                    .into_iter()
1668                    .map(|(id, _last_modification_slot, entry)| (id, entry))
1669                    .collect();
1670                epoch_boundary_preparation
1671                    .programs_to_recompile
1672                    .sort_by_cached_key(|(_id, program)| program.retention_score());
1673            } else {
1674                epoch_boundary_preparation.programs_to_recompile.clear();
1675            }
1676            epoch_boundary_preparation.upcoming_epoch = self.epoch.saturating_add(1);
1677            epoch_boundary_preparation.upcoming_environment = Some(upcoming_environment);
1678        }
1679    }
1680
1681    pub fn prune_program_cache(&self, bank_forks: &BankForks) {
1682        let upcoming_environment = self
1683            .transaction_processor
1684            .epoch_boundary_preparation
1685            .write()
1686            .unwrap()
1687            .reroot(self.epoch());
1688        self.transaction_processor
1689            .global_program_cache
1690            .write()
1691            .unwrap()
1692            .prune(
1693                self.slot(),
1694                upcoming_environment.map(|_| {
1695                    ProgramRuntimeEnvironment::clone(
1696                        &self.transaction_processor.program_runtime_environment,
1697                    )
1698                }),
1699                bank_forks,
1700            );
1701    }
1702
1703    pub fn prune_program_cache_by_deployment_slot(&self, deployment_slot: Slot) {
1704        self.transaction_processor
1705            .global_program_cache
1706            .write()
1707            .unwrap()
1708            .prune_by_deployment_slot(deployment_slot);
1709    }
1710
1711    /// Epoch in which the new cooldown warmup rate for stake was activated
1712    pub fn new_warmup_cooldown_rate_epoch(&self) -> Option<Epoch> {
1713        self.feature_set
1714            .new_warmup_cooldown_rate_epoch(&self.epoch_schedule)
1715    }
1716
1717    fn use_fixed_point_stake_math(&self) -> bool {
1718        self.feature_set
1719            .snapshot()
1720            .upgrade_bpf_stake_program_to_v5_1
1721    }
1722
1723    /// Get cached vote account state from the past few epochs so that some vote
1724    /// state configuration changes are delayed before being used in reward
1725    /// calculation.
1726    fn get_cached_vote_accounts<'a>(
1727        &'a self,
1728        rewarded_epoch: Epoch,
1729        distribution_epoch_vote_accounts: &'a VoteAccounts,
1730    ) -> CachedVoteAccounts<'a> {
1731        // Snapshot of vote account state from the beginning of the epoch prior to
1732        // the rewarded epoch. This snapshot state is saved a full epoch before
1733        // being used to prevent last minute commission rugs.
1734        let snapshot_epoch_vote_accounts = self
1735            .epoch_stakes(rewarded_epoch)
1736            .map(|epoch_stakes| epoch_stakes.stakes().vote_accounts());
1737
1738        // Vote account state from the beginning of the rewarded epoch.
1739        let rewarded_epoch_vote_accounts = self
1740            .epoch_stakes(self.epoch())
1741            .map(|epoch_stakes| epoch_stakes.stakes().vote_accounts());
1742
1743        CachedVoteAccounts {
1744            snapshot_epoch_vote_accounts,
1745            rewarded_epoch_vote_accounts,
1746            distribution_epoch_vote_accounts,
1747        }
1748    }
1749
1750    /// Returns updated stake history and vote accounts that includes new
1751    /// activated stake from the last epoch.
1752    fn compute_new_epoch_caches_and_rewards(
1753        &self,
1754        thread_pool: &ThreadPool,
1755        rewarded_epoch: Epoch,
1756        reward_calc_tracer: Option<impl RewardCalcTracer>,
1757        rewards_metrics: &mut RewardsMetrics,
1758    ) -> NewEpochBundle {
1759        // Add new entry to stakes.stake_history, set appropriate epoch and
1760        // update vote accounts with warmed up stakes before saving a
1761        // snapshot of stakes in epoch stakes
1762        let stakes = self.stakes_cache.stakes();
1763        let stake_delegations = stakes.stake_delegations_vec();
1764        let (
1765            (
1766                stake_history,
1767                unfiltered_distribution_vote_accounts,
1768                delegated_stakes,
1769                reward_epoch_delegated_stakes,
1770            ),
1771            calculate_activated_stake_time_us,
1772        ) = measure_us!(stakes.calculate_activated_stake(
1773            self.epoch(),
1774            thread_pool,
1775            self.new_warmup_cooldown_rate_epoch(),
1776            &stake_delegations,
1777            self.use_fixed_point_stake_math(),
1778        ));
1779        debug_assert_eq!(reward_epoch_delegated_stakes.epoch, rewarded_epoch);
1780
1781        // Apply stake rewards and commission using the VAT-filtered distribution
1782        // vote-account snapshot.
1783        let filtered_distribution_vote_accounts = unfiltered_distribution_vote_accounts
1784            .clone_and_filter_for_vat(
1785                MAX_ALPENGLOW_VOTE_ACCOUNTS,
1786                self.minimum_vote_account_balance_for_vat(),
1787            );
1788        if AlpenglowEpochType::is_alpenglow_or_migration_epoch(self, rewarded_epoch) {
1789            reward_epoch_delegated_stakes.set(self, &filtered_distribution_vote_accounts);
1790        }
1791        let cached_vote_accounts =
1792            self.get_cached_vote_accounts(rewarded_epoch, &filtered_distribution_vote_accounts);
1793        let (rewards_calculation, update_rewards_with_thread_pool_time_us) =
1794            measure_us!(self.calculate_rewards(
1795                &stake_history,
1796                stake_delegations,
1797                cached_vote_accounts,
1798                rewarded_epoch,
1799                reward_epoch_delegated_stakes,
1800                reward_calc_tracer,
1801                thread_pool,
1802                rewards_metrics,
1803            ));
1804        NewEpochBundle {
1805            stake_history,
1806            unfiltered_distribution_vote_accounts,
1807            delegated_stakes,
1808            filtered_distribution_vote_accounts,
1809            rewards_calculation,
1810            calculate_activated_stake_time_us,
1811            update_rewards_with_thread_pool_time_us,
1812        }
1813    }
1814
1815    /// process for the start of a new epoch
1816    fn process_new_epoch(
1817        &mut self,
1818        parent_epoch: Epoch,
1819        parent_slot: Slot,
1820        parent_capitalization: u64,
1821        parent_height: u64,
1822        reward_calc_tracer: Option<impl RewardCalcTracer>,
1823    ) {
1824        let epoch = self.epoch();
1825        let slot = self.slot();
1826        let thread_pool = rewards_calculation_thread_pool();
1827
1828        let (_, apply_feature_activations_time_us) = measure_us!(
1829            thread_pool.install(|| { self.compute_and_apply_new_feature_activations() })
1830        );
1831
1832        let mut rewards_metrics = RewardsMetrics::default();
1833        let NewEpochBundle {
1834            stake_history,
1835            unfiltered_distribution_vote_accounts,
1836            delegated_stakes,
1837            filtered_distribution_vote_accounts,
1838            rewards_calculation,
1839            calculate_activated_stake_time_us,
1840            update_rewards_with_thread_pool_time_us,
1841        } = self.compute_new_epoch_caches_and_rewards(
1842            thread_pool,
1843            parent_epoch,
1844            reward_calc_tracer,
1845            &mut rewards_metrics,
1846        );
1847
1848        self.stakes_cache.activate_epoch(
1849            epoch,
1850            stake_history,
1851            unfiltered_distribution_vote_accounts,
1852            delegated_stakes,
1853        );
1854
1855        // Save a snapshot of stakes for use in consensus and stake weighted networking
1856        let leader_schedule_epoch = self.epoch_schedule.get_leader_schedule_epoch(slot);
1857        let (_, update_epoch_stakes_time_us) = measure_us!(self.update_epoch_stakes(
1858            leader_schedule_epoch,
1859            Some(filtered_distribution_vote_accounts),
1860        ));
1861
1862        // Distribute rewards commission to vote accounts and cache stake rewards
1863        // for partitioned distribution in the upcoming slots.
1864        let (epoch_rewards, begin_partitioned_rewards_time_us) =
1865            measure_us!(self.begin_partitioned_rewards(
1866                parent_epoch,
1867                parent_slot,
1868                parent_height,
1869                &rewards_calculation,
1870                &mut rewards_metrics,
1871                thread_pool,
1872            ));
1873
1874        // the vote reward account state should be created at the epoch boundary in which we
1875        // activate alpenglow as it will need info from the previous epoch.
1876        if self.feature_set.snapshot().alpenglow {
1877            let epoch_start_capitalization = parent_capitalization;
1878            EpochInflationAccountState::new_epoch_update_account(
1879                self,
1880                epoch_start_capitalization,
1881                epoch_rewards,
1882            );
1883        }
1884
1885        report_new_epoch_metrics(
1886            epoch,
1887            slot,
1888            parent_slot,
1889            NewEpochTimings {
1890                apply_feature_activations_time_us,
1891                calculate_activated_stake_time_us,
1892                update_epoch_stakes_time_us,
1893                update_rewards_with_thread_pool_time_us,
1894                begin_partitioned_rewards_time_us,
1895            },
1896            rewards_metrics,
1897        );
1898
1899        let program_runtime_environment =
1900            self.create_program_runtime_environment(&self.feature_set);
1901        self.transaction_processor
1902            .set_program_runtime_environment(program_runtime_environment);
1903    }
1904
1905    pub fn proper_ancestors_set(&self) -> HashSet<Slot> {
1906        HashSet::from_iter(self.proper_ancestors())
1907    }
1908
1909    /// Returns all ancestors excluding self.slot.
1910    pub(crate) fn proper_ancestors(&self) -> impl Iterator<Item = Slot> + '_ {
1911        self.ancestors
1912            .keys()
1913            .into_iter()
1914            .filter(move |slot| *slot != self.slot)
1915    }
1916
1917    pub fn set_callback(&self, callback: Option<Box<dyn DropCallback + Send + Sync>>) {
1918        *self.drop_callback.write().unwrap() = OptionalDropCallback(callback);
1919    }
1920
1921    pub fn vote_only_bank(&self) -> bool {
1922        self.vote_only_bank
1923    }
1924
1925    /// Like `new_from_parent` but additionally:
1926    /// * Doesn't assume that the parent is anywhere near `slot`, parent could be millions of slots
1927    ///   in the past
1928    /// * Adjusts the new bank's tick height to avoid having to run PoH for millions of slots
1929    /// * Freezes the new bank, assuming that the user will `Bank::new_from_parent` from this bank
1930    pub fn warp_from_parent(parent: Arc<Bank>, leader: SlotLeader, slot: Slot) -> Self {
1931        parent.freeze();
1932        let parent_timestamp = parent.clock().unix_timestamp;
1933        let mut new = Bank::new_from_parent(parent, leader, slot);
1934        new.update_epoch_stakes(new.epoch_schedule().get_epoch(slot), None);
1935        new.tick_height.store(new.max_tick_height(), Relaxed);
1936
1937        let mut clock = new.clock();
1938        clock.epoch_start_timestamp = parent_timestamp;
1939        clock.unix_timestamp = parent_timestamp;
1940        new.update_sysvar_account(&sysvar::clock::id(), |account| {
1941            create_account(
1942                &clock,
1943                new.inherit_specially_retained_account_fields(account),
1944            )
1945        });
1946        new.transaction_processor
1947            .fill_missing_sysvar_cache_entries(&new);
1948        new.freeze();
1949        new
1950    }
1951
1952    fn load_rent_from_account_for_snapshot_load(
1953        accounts: &Accounts,
1954        ancestors: &Ancestors,
1955    ) -> Rent {
1956        // The serialized rent collector is deprecated. Instead, reconstruct from fields plus
1957        // the rent sysvar account state.
1958        let rent_sysvar = accounts
1959            .load_with_fixed_root_do_not_populate_read_cache(ancestors, &sysvar::rent::id())
1960            .expect("snapshot must contain rent sysvar account")
1961            .0;
1962        from_account::<sysvar::rent::Rent>(&rent_sysvar)
1963            .expect("snapshot must contain well-formed rent sysvar account")
1964    }
1965
1966    /// Complete bank initialization for block execution. Performs epoch
1967    /// processing, sysvar updates, program cache preparation, and LT hash
1968    /// cache population -- the post-construction sequence shared by
1969    /// `_new_from_parent` and the block-test path.
1970    fn prepare_for_block_execution(
1971        &mut self,
1972        parent_epoch: Epoch,
1973        parent_slot: Slot,
1974        parent_capitalization: u64,
1975        parent_block_height: u64,
1976        reward_calc_tracer: Option<impl RewardCalcTracer>,
1977    ) -> PrepareBlockExecutionStats {
1978        let slot = self.slot;
1979
1980        // Following code may touch AccountsDb, requiring proper ancestors
1981        let (_, update_epoch_time_us) = measure_us!({
1982            if parent_epoch < self.epoch() {
1983                self.process_new_epoch(
1984                    parent_epoch,
1985                    parent_slot,
1986                    parent_capitalization,
1987                    parent_block_height,
1988                    reward_calc_tracer,
1989                );
1990            } else {
1991                // Save a snapshot of stakes for use in consensus and stake weighted networking
1992                let leader_schedule_epoch = self.epoch_schedule().get_leader_schedule_epoch(slot);
1993                self.update_epoch_stakes(leader_schedule_epoch, None);
1994            }
1995        });
1996
1997        let (_, distribute_rewards_time_us) =
1998            measure_us!(self.distribute_partitioned_epoch_rewards());
1999
2000        let (_, cache_preparation_time_us) =
2001            measure_us!(self.prepare_program_cache_for_upcoming_feature_set());
2002
2003        // Update sysvars before processing transactions
2004        let (_, update_sysvars_time_us) = measure_us!({
2005            self.update_slot_hashes();
2006            self.update_stake_history(Some(parent_epoch));
2007
2008            if self.is_alpenglow() {
2009                // Alpenglow banks have the timestamp populated via the footer
2010                // We only populate the slot here
2011                self.update_clock_slot_for_alpenglow();
2012            } else {
2013                // PoH banks have the timestamp and slot populated at the beginning
2014                // Note: The first alpenglow bank will have the timestamp populated
2015                // here at the beginning as well as at the end via the footer - this is intentional.
2016                self.update_clock(Some(parent_epoch));
2017            }
2018            self.update_last_restart_slot()
2019        });
2020
2021        let (_, fill_sysvar_cache_time_us) = measure_us!(
2022            self.transaction_processor
2023                .fill_missing_sysvar_cache_entries(self)
2024        );
2025
2026        PrepareBlockExecutionStats {
2027            update_epoch_time_us,
2028            distribute_rewards_time_us,
2029            cache_preparation_time_us,
2030            update_sysvars_time_us,
2031            fill_sysvar_cache_time_us,
2032        }
2033    }
2034
2035    /// Create a bank from explicit arguments and deserialized fields from snapshot
2036    pub(crate) fn new_from_snapshot(
2037        bank_rc: BankRc,
2038        genesis_config: &GenesisConfig,
2039        runtime_config: Arc<RuntimeConfig>,
2040        fields: BankFieldsToDeserialize,
2041        leader_for_tests: Option<SlotLeader>,
2042        debug_keys: Option<Arc<HashSet<Pubkey>>>,
2043        accounts_data_size_initial: u64,
2044        epoch_stakes: HashMap<Epoch, VersionedEpochStakes>,
2045    ) -> Self {
2046        let now = Instant::now();
2047        let slot = fields.slot;
2048        let epoch = fields.epoch_schedule.get_epoch(slot);
2049        let ancestors = Ancestors::from(vec![slot]);
2050        // Initialize the rewards thread pool while creating the first bank so
2051        // the first epoch boundary crossing does not pay the cost.
2052        let rewards_calculation_thread_pool = rewards_calculation_thread_pool();
2053        // For backward compatibility, we can only serialize and deserialize
2054        // Stakes<Delegation> in BankFieldsTo{Serialize,Deserialize}. But Bank
2055        // caches Stakes<StakeAccount>. Below Stakes<StakeAccount> is obtained
2056        // from Stakes<Delegation> by reading the full account state from
2057        // accounts-db. Note that it is crucial that these accounts are loaded
2058        // at the right slot and match precisely with serialized Delegations.
2059        //
2060        // Note that we are disabling the read cache while we populate the stakes cache.
2061        // The stakes accounts will not be expected to be loaded again.
2062        // If we populate the read cache with these loads, then we'll just soon have to evict these.
2063        let (stakes, stakes_time) = measure_time!(
2064            Stakes::load_from_deserialized_delegations(fields.stakes, |pubkey| {
2065                let (account, _slot) = bank_rc
2066                    .accounts
2067                    .load_with_fixed_root_do_not_populate_read_cache(&ancestors, pubkey)?;
2068                Some(account)
2069            })
2070            .expect(
2071                "Stakes cache is inconsistent with accounts-db. This can indicate a corrupted \
2072                 snapshot or bugs in cached accounts or accounts-db.",
2073            )
2074        );
2075        info!("Loading Stakes took: {stakes_time}");
2076        assert!(
2077            fields.versioned_epoch_stakes.is_empty(),
2078            "should be already converted and passed in epoch_stakes parameter"
2079        );
2080        assert!(
2081            !epoch_stakes.is_empty(),
2082            "should be populated (from fields.versioned_epoch_stakes)"
2083        );
2084
2085        // Compute and validate the slot leader from epoch stakes.
2086        let compute_leader = || {
2087            if slot == 0 {
2088                // Genesis snapshot has no leader for the genesis block.
2089                // Instead the leader is set to the maximum delegated vote account.
2090                stakes
2091                    .highest_staked_node()
2092                    .expect("genesis snapshot should contain at least one staked vote account")
2093            } else {
2094                Self::slot_leader_from_epoch_stakes(
2095                    fields.slot,
2096                    &fields.epoch_schedule,
2097                    &epoch_stakes,
2098                )
2099            }
2100        };
2101        #[cfg(not(feature = "dev-context-only-utils"))]
2102        let leader = {
2103            _ = leader_for_tests;
2104            compute_leader()
2105        };
2106        #[cfg(feature = "dev-context-only-utils")]
2107        let leader = leader_for_tests.unwrap_or_else(compute_leader);
2108        assert_eq!(
2109            fields.leader_id, leader.id,
2110            "snapshot leader_id does not match computed slot leader"
2111        );
2112
2113        let stakes_accounts_load_duration = now.elapsed();
2114        let rent = Self::load_rent_from_account_for_snapshot_load(&bank_rc.accounts, &ancestors);
2115        let partitioned_rewards_stake_account_stores_per_block = bank_rc
2116            .accounts
2117            .accounts_db
2118            .partitioned_epoch_rewards_config
2119            .stake_account_stores_per_block;
2120        let mut bank = Self {
2121            rc: bank_rc,
2122            status_cache: Arc::<RwLock<BankStatusCache>>::default(),
2123            store_transaction_signatures_in_status_cache: !runtime_config
2124                .skip_transaction_signatures_in_status_cache,
2125            blockhash_queue: RwLock::new(fields.blockhash_queue),
2126            max_processing_age: MAX_PROCESSING_AGE,
2127            partitioned_rewards_stake_account_stores_per_block,
2128            ancestors,
2129            hash: RwLock::new(fields.hash),
2130            parent_hash: fields.parent_hash,
2131            parent_slot: fields.parent_slot,
2132            hard_forks: Arc::new(RwLock::new(fields.hard_forks)),
2133            transaction_count: AtomicU64::new(fields.transaction_count),
2134            non_vote_transaction_count_since_restart: AtomicU64::default(),
2135            transaction_error_count: AtomicU64::default(),
2136            transaction_entries_count: AtomicU64::default(),
2137            transactions_per_entry_max: AtomicU64::default(),
2138            entry_bytes_consumed: EntryBytesBudget::new(DEFAULT_MAX_ENTRY_BYTES_PER_SLOT),
2139            tick_height: AtomicU64::new(fields.tick_height),
2140            signature_count: AtomicU64::new(fields.signature_count),
2141            capitalization: AtomicU64::new(fields.capitalization),
2142            max_tick_height: fields.max_tick_height,
2143            hashes_per_tick: RwLock::new(fields.hashes_per_tick),
2144            ticks_per_slot: fields.ticks_per_slot,
2145            ns_per_slot: fields.ns_per_slot,
2146            genesis_creation_time: fields.genesis_creation_time,
2147            slots_per_year: fields.slots_per_year,
2148            slot_params: SlotParamsArchive::default(),
2149            slot,
2150            bank_id: 0,
2151            epoch,
2152            block_height: fields.block_height,
2153            leader,
2154            fee_rate_governor: fields.fee_rate_governor,
2155            rent_collector: RentCollector::new(
2156                epoch,
2157                fields.epoch_schedule.clone(),
2158                fields.slots_per_year,
2159                rent,
2160            ),
2161            epoch_schedule: fields.epoch_schedule,
2162            inflation: Arc::new(RwLock::new(fields.inflation)),
2163            stakes_cache: StakesCache::new(stakes),
2164            epoch_stakes,
2165            is_delta: AtomicBool::new(fields.is_delta),
2166            rewards: RwLock::new(vec![]),
2167            cluster_type: Some(genesis_config.cluster_type),
2168            transaction_debug_keys: debug_keys,
2169            transaction_log_collector_config: Arc::<RwLock<TransactionLogCollectorConfig>>::default(
2170            ),
2171            transaction_log_collector: Arc::<RwLock<TransactionLogCollector>>::default(),
2172            feature_set: Arc::<FeatureSet>::default(),
2173            reserved_account_keys: Arc::<ReservedAccountKeys>::default(),
2174            drop_callback: RwLock::new(OptionalDropCallback(None)),
2175            freeze_started: AtomicBool::new(fields.hash != Hash::default()),
2176            vote_only_bank: false,
2177            cost_tracker: RwLock::new(CostTracker::default()),
2178            accounts_data_size_initial,
2179            accounts_data_size_delta_on_chain: AtomicI64::new(0),
2180            accounts_data_size_delta_off_chain: AtomicI64::new(0),
2181            epoch_reward_status: EpochRewardStatus::default(),
2182            transaction_processor: TransactionBatchProcessor::default(),
2183            check_program_deployment_slot: false,
2184            // collector_fee_details is not serialized to snapshot
2185            collector_fee_details: RwLock::new(CollectorFeeDetails::default()),
2186            compute_budget: runtime_config.compute_budget,
2187            transaction_account_lock_limit: runtime_config.transaction_account_lock_limit,
2188            fee_structure: FeeStructure::default(),
2189            #[cfg(feature = "dev-context-only-utils")]
2190            hash_overrides: Arc::new(Mutex::new(HashOverrides::default())),
2191            accounts_lt_hash: Mutex::new(fields.accounts_lt_hash),
2192            accounts_lt_hash_async_progress: AccountsLtHashAsyncProgress::new(),
2193            block_id: RwLock::new(fields.block_id),
2194            bank_hash_stats: AtomicBankHashStats::new(&fields.bank_hash_stats),
2195            epoch_rewards_calculation_cache: Arc::new(Mutex::new(HashMap::default())),
2196            expected_bank_hash: RwLock::new(None),
2197            block_component_processor: RwLock::new(BlockComponentProcessor::default()),
2198            is_alpenglow: AtomicBool::new(false),
2199        };
2200
2201        if bank.get_alpenglow_genesis_certificate().is_some() {
2202            bank.set_is_alpenglow();
2203        }
2204
2205        // Sanity assertions between bank snapshot and genesis config
2206        // Consider removing from serializable bank state
2207        // (BankFieldsToSerialize/BankFieldsToDeserialize) and initializing
2208        // from the passed in genesis_config instead (as new()/new_from_genesis() already do)
2209        assert_eq!(
2210            bank.genesis_creation_time, genesis_config.creation_time,
2211            "Bank snapshot genesis creation time does not match genesis.bin creation time. The \
2212             snapshot and genesis.bin might pertain to different clusters"
2213        );
2214        assert_eq!(bank.ticks_per_slot, genesis_config.ticks_per_slot);
2215        assert_eq!(bank.max_tick_height, (bank.slot + 1) * bank.ticks_per_slot);
2216        assert_eq!(bank.epoch_schedule, genesis_config.epoch_schedule);
2217
2218        bank.refresh_slot_params_from_snapshot(genesis_config);
2219        bank.initialize_after_snapshot_restore(|| rewards_calculation_thread_pool);
2220
2221        datapoint_info!(
2222            "bank-new-from-fields",
2223            (
2224                "accounts_data_len-from-snapshot",
2225                fields.accounts_data_len as i64,
2226                i64
2227            ),
2228            (
2229                "accounts_data_len-from-generate_index",
2230                accounts_data_size_initial as i64,
2231                i64
2232            ),
2233            (
2234                "stakes_accounts_load_duration_us",
2235                stakes_accounts_load_duration.as_micros(),
2236                i64
2237            ),
2238        );
2239        bank
2240    }
2241
2242    /// Compute the slot leader from epoch stakes during snapshot restoration.
2243    fn slot_leader_from_epoch_stakes(
2244        slot: Slot,
2245        epoch_schedule: &EpochSchedule,
2246        epoch_stakes: &HashMap<Epoch, VersionedEpochStakes>,
2247    ) -> SlotLeader {
2248        let (epoch, slot_index) = epoch_schedule.get_epoch_and_slot_index(slot);
2249        let epoch_vote_accounts = epoch_stakes
2250            .get(&epoch)
2251            .expect("epoch stakes should contain current epoch")
2252            .stakes()
2253            .vote_accounts();
2254        let leader_schedule =
2255            leader_schedule_from_vote_accounts(epoch, epoch_schedule, epoch_vote_accounts.as_ref())
2256                .expect("leader schedule should be computable from epoch stakes");
2257        leader_schedule.get_slot_leader_at_index(slot_index as usize)
2258    }
2259
2260    /// Return subset of bank fields representing serializable state
2261    pub(crate) fn get_fields_to_serialize(&self) -> BankFieldsToSerialize {
2262        BankFieldsToSerialize {
2263            blockhash_queue: self.blockhash_queue.read().unwrap().clone(),
2264            hash: *self.hash.read().unwrap(),
2265            parent_hash: self.parent_hash,
2266            parent_slot: self.parent_slot,
2267            hard_forks: self.hard_forks.read().unwrap().clone(),
2268            transaction_count: self.transaction_count.load(Relaxed),
2269            tick_height: self.tick_height.load(Relaxed),
2270            signature_count: self.signature_count.load(Relaxed),
2271            capitalization: self.capitalization.load(Relaxed),
2272            max_tick_height: self.max_tick_height,
2273            hashes_per_tick: *self.hashes_per_tick.read().unwrap(),
2274            ticks_per_slot: self.ticks_per_slot,
2275            ns_per_slot: self.ns_per_slot,
2276            genesis_creation_time: self.genesis_creation_time,
2277            slots_per_year: self.slots_per_year,
2278            slot: self.slot,
2279            block_height: self.block_height,
2280            leader_id: self.leader.id,
2281            fee_rate_governor: self.fee_rate_governor.clone(),
2282            epoch_schedule: self.epoch_schedule.clone(),
2283            inflation: *self.inflation.read().unwrap(),
2284            stakes: self.stakes_cache.stakes().clone(),
2285            is_delta: self.is_delta.load(Relaxed),
2286            accounts_data_len: self.load_accounts_data_size(),
2287            versioned_epoch_stakes: self.epoch_stakes.clone(),
2288            accounts_lt_hash: self.accounts_lt_hash.lock().unwrap().clone(),
2289            block_id: self.block_id().expect("block id must be set"),
2290        }
2291    }
2292
2293    pub fn leader(&self) -> &SlotLeader {
2294        &self.leader
2295    }
2296
2297    pub fn leader_id(&self) -> &Pubkey {
2298        &self.leader.id
2299    }
2300
2301    pub fn genesis_creation_time(&self) -> UnixTimestamp {
2302        self.genesis_creation_time
2303    }
2304
2305    pub fn slot(&self) -> Slot {
2306        self.slot
2307    }
2308
2309    pub fn bank_id(&self) -> BankId {
2310        self.bank_id
2311    }
2312
2313    pub fn epoch(&self) -> Epoch {
2314        self.epoch
2315    }
2316
2317    pub fn first_normal_epoch(&self) -> Epoch {
2318        self.epoch_schedule().first_normal_epoch
2319    }
2320
2321    pub fn freeze_lock(&self) -> RwLockReadGuard<'_, Hash> {
2322        self.hash.read().unwrap()
2323    }
2324
2325    /// Waits for in-flight BankingStage commits to finish without freezing the bank.
2326    ///
2327    /// BankingStage holds the read side of this lock from before a successful
2328    /// PoH record until after the matching account commit. Taking and dropping
2329    /// the write side gives callers a quiescence point before abandoning and
2330    /// purging an unfrozen leader bank.
2331    pub fn wait_for_inflight_commits(&self) {
2332        drop(self.hash.write().unwrap());
2333    }
2334
2335    pub fn hash(&self) -> Hash {
2336        *self.hash.read().unwrap()
2337    }
2338
2339    pub fn is_frozen(&self) -> bool {
2340        *self.hash.read().unwrap() != Hash::default()
2341    }
2342
2343    pub fn freeze_started(&self) -> bool {
2344        self.freeze_started.load(Relaxed)
2345    }
2346
2347    pub fn status_cache_ancestors(&self) -> Vec<u64> {
2348        let (min, mut ancestors) = {
2349            let status_cache = self.status_cache.read().unwrap();
2350            let roots = status_cache.roots();
2351            let mut ancestors = Vec::with_capacity(roots.len() + self.ancestors.len());
2352            let mut min = Slot::MAX;
2353            for root in roots {
2354                ancestors.push(*root);
2355                min = min.min(*root);
2356            }
2357            (if roots.is_empty() { 0 } else { min }, ancestors)
2358        };
2359
2360        ancestors.extend(self.ancestors.iter().filter(|ancestor| *ancestor >= min));
2361        ancestors.sort_unstable();
2362        ancestors.dedup();
2363        ancestors
2364    }
2365
2366    /// computed unix_timestamp at this slot height
2367    pub fn unix_timestamp_from_genesis(&self) -> i64 {
2368        self.genesis_creation_time.saturating_add(
2369            (self.slot as u128)
2370                .saturating_mul(self.ns_per_slot)
2371                .saturating_div(1_000_000_000) as i64,
2372        )
2373    }
2374
2375    /// Returns a reference to the [`VersionedEpochStakes`] corresponding to the given [`Slot`].
2376    pub fn epoch_stakes_from_slot(&self, slot: Slot) -> Option<&VersionedEpochStakes> {
2377        let epoch = self.epoch_schedule().get_epoch(slot);
2378        self.epoch_stakes(epoch)
2379    }
2380
2381    /// Returns a reference to [`BLSPubkeyToRankMap`] for the given `slot`.
2382    pub fn get_rank_map(&self, slot: Slot) -> Option<&Arc<BLSPubkeyToRankMap>> {
2383        self.epoch_stakes_from_slot(slot)
2384            .map(|stake| stake.bls_pubkey_to_rank_map())
2385    }
2386
2387    fn update_sysvar_account<F>(&self, pubkey: &Pubkey, updater: F)
2388    where
2389        F: Fn(&Option<AccountSharedData>) -> AccountSharedData,
2390    {
2391        let old_account = self.get_account_with_fixed_root(pubkey);
2392        let mut new_account = updater(&old_account);
2393
2394        // When new sysvar comes into existence (with RENT_UNADJUSTED_INITIAL_BALANCE lamports),
2395        // this code ensures that the sysvar's balance is adjusted to be rent-exempt.
2396        //
2397        // More generally, this code always re-calculates for possible sysvar data size change,
2398        // although there is no such sysvars currently.
2399        self.adjust_sysvar_balance_for_rent(&mut new_account);
2400        self.store_account_and_update_capitalization(pubkey, &new_account);
2401    }
2402
2403    fn inherit_specially_retained_account_fields(
2404        &self,
2405        old_account: &Option<AccountSharedData>,
2406    ) -> InheritableAccountFields {
2407        const RENT_UNADJUSTED_INITIAL_BALANCE: u64 = 1;
2408
2409        (
2410            old_account
2411                .as_ref()
2412                .map(|a| a.lamports())
2413                .unwrap_or(RENT_UNADJUSTED_INITIAL_BALANCE),
2414            old_account
2415                .as_ref()
2416                .map(|a| a.rent_epoch())
2417                .unwrap_or(INITIAL_RENT_EPOCH),
2418        )
2419    }
2420
2421    pub fn clock(&self) -> sysvar::clock::Clock {
2422        from_account(&self.get_account(&sysvar::clock::id()).unwrap_or_default())
2423            .unwrap_or_default()
2424    }
2425
2426    fn update_clock(&self, parent_epoch: Option<Epoch>) {
2427        let mut unix_timestamp = self.clock().unix_timestamp;
2428        // set epoch_start_timestamp to None to warp timestamp
2429        let epoch_start_timestamp = {
2430            let epoch = if let Some(epoch) = parent_epoch {
2431                epoch
2432            } else {
2433                self.epoch()
2434            };
2435            let first_slot_in_epoch = self.epoch_schedule().get_first_slot_in_epoch(epoch);
2436            Some((first_slot_in_epoch, self.clock().epoch_start_timestamp))
2437        };
2438        let max_allowable_drift = MaxAllowableDrift {
2439            fast: MAX_ALLOWABLE_DRIFT_PERCENTAGE_FAST,
2440            slow: MAX_ALLOWABLE_DRIFT_PERCENTAGE_SLOW_V2,
2441        };
2442
2443        let ancestor_timestamp = self.clock().unix_timestamp;
2444        if let Some(timestamp_estimate) =
2445            self.get_timestamp_estimate(max_allowable_drift, epoch_start_timestamp)
2446        {
2447            unix_timestamp = timestamp_estimate;
2448            if timestamp_estimate < ancestor_timestamp {
2449                unix_timestamp = ancestor_timestamp;
2450            }
2451        }
2452        datapoint_info!(
2453            "bank-timestamp-correction",
2454            ("slot", self.slot(), i64),
2455            ("from_genesis", self.unix_timestamp_from_genesis(), i64),
2456            ("corrected", unix_timestamp, i64),
2457            ("ancestor_timestamp", ancestor_timestamp, i64),
2458        );
2459        let mut epoch_start_timestamp =
2460            // On epoch boundaries, update epoch_start_timestamp
2461            if parent_epoch.is_some() && parent_epoch.unwrap() != self.epoch() {
2462                unix_timestamp
2463            } else {
2464                self.clock().epoch_start_timestamp
2465            };
2466        if self.slot == 0 {
2467            unix_timestamp = self.unix_timestamp_from_genesis();
2468            epoch_start_timestamp = self.unix_timestamp_from_genesis();
2469        }
2470        let clock = sysvar::clock::Clock {
2471            slot: self.slot,
2472            epoch_start_timestamp,
2473            epoch: self.epoch_schedule().get_epoch(self.slot),
2474            leader_schedule_epoch: self.epoch_schedule().get_leader_schedule_epoch(self.slot),
2475            unix_timestamp,
2476        };
2477        self.update_sysvar_account(&sysvar::clock::id(), |account| {
2478            create_account(
2479                &clock,
2480                self.inherit_specially_retained_account_fields(account),
2481            )
2482        });
2483    }
2484
2485    /// In Alpenglow the clock sysvar's timestamp is populated from the block footer.
2486    /// The timestamp value on the block footer is used as an estimate for when the block *ended*.
2487    /// This is applied at the end of execution on the bank for use in the child.
2488    ///
2489    /// However we still need to update the slot and epoch fields for the clock sysvar at the *start*
2490    /// of the bank, as transactions executing in this bank need to be able to read these values.
2491    /// This function updates the slot and epoch fields while preserving the timestamp fields from the parent
2492    /// bank's footer.
2493    fn update_clock_slot_for_alpenglow(&self) {
2494        let clock = self.clock();
2495        let clock = sysvar::clock::Clock {
2496            slot: self.slot,
2497            epoch: self.epoch_schedule().get_epoch(self.slot),
2498            leader_schedule_epoch: self.epoch_schedule().get_leader_schedule_epoch(self.slot),
2499            epoch_start_timestamp: clock.epoch_start_timestamp,
2500            unix_timestamp: clock.unix_timestamp,
2501        };
2502        self.update_sysvar_account(&sysvar::clock::id(), |account| {
2503            create_account(
2504                &clock,
2505                self.inherit_specially_retained_account_fields(account),
2506            )
2507        });
2508    }
2509
2510    pub fn update_last_restart_slot(&self) {
2511        // First, see what the currently stored last restart slot is.
2512        let current_last_restart_slot = self
2513            .get_account(&sysvar::last_restart_slot::id())
2514            .and_then(|account| {
2515                let lrs: Option<LastRestartSlot> = from_account(&account);
2516                lrs
2517            })
2518            .map(|account| account.last_restart_slot);
2519
2520        let last_restart_slot = {
2521            let slot = self.slot;
2522            let hard_forks_r = self.hard_forks.read().unwrap();
2523
2524            // Only consider hard forks <= this bank's slot to avoid prematurely applying
2525            // a hard fork that is set to occur in the future.
2526            hard_forks_r
2527                .iter()
2528                .rev()
2529                .find(|(hard_fork, _)| *hard_fork <= slot)
2530                .map(|(slot, _)| *slot)
2531                .unwrap_or(0)
2532        };
2533
2534        // Only need to write if the last restart has changed
2535        if current_last_restart_slot != Some(last_restart_slot) {
2536            self.update_sysvar_account(&sysvar::last_restart_slot::id(), |account| {
2537                create_account(
2538                    &LastRestartSlot { last_restart_slot },
2539                    self.inherit_specially_retained_account_fields(account),
2540                )
2541            });
2542        }
2543    }
2544
2545    pub fn set_sysvar_for_tests<T>(&self, sysvar: &T)
2546    where
2547        T: Serialize + SysvarId,
2548    {
2549        self.update_sysvar_account(&T::id(), |account| {
2550            create_account_with_bincode(
2551                sysvar,
2552                self.inherit_specially_retained_account_fields(account),
2553            )
2554        });
2555        // Simply force fill sysvar cache rather than checking which sysvar was
2556        // actually updated since tests don't need to be optimized for performance.
2557        self.transaction_processor
2558            .reset_and_fill_sysvar_cache_entries(self);
2559    }
2560
2561    fn update_slot_history(&self) {
2562        self.update_sysvar_account(&sysvar::slot_history::id(), |account| {
2563            let mut slot_history = account
2564                .as_ref()
2565                .map(|account| wincode::deserialize::<SlotHistory>(account.data()).unwrap())
2566                .unwrap_or_default();
2567            slot_history.add(self.slot());
2568            create_account(
2569                &slot_history,
2570                self.inherit_specially_retained_account_fields(account),
2571            )
2572        });
2573    }
2574
2575    fn update_slot_hashes(&self) {
2576        self.update_sysvar_account(&sysvar::slot_hashes::id(), |account| {
2577            let mut slot_hashes = account
2578                .as_ref()
2579                .map(|account| wincode::deserialize::<SlotHashes>(account.data()).unwrap())
2580                .unwrap_or_default();
2581            slot_hashes.add(self.parent_slot, self.parent_hash);
2582            create_account(
2583                &slot_hashes,
2584                self.inherit_specially_retained_account_fields(account),
2585            )
2586        });
2587    }
2588
2589    pub fn get_slot_history(&self) -> Option<SlotHistory> {
2590        wincode::deserialize::<SlotHistory>(self.get_account(&sysvar::slot_history::id())?.data())
2591            .ok()
2592    }
2593
2594    fn update_epoch_stakes(
2595        &mut self,
2596        leader_schedule_epoch: Epoch,
2597        prefiltered_distribution_vote_accounts: Option<VoteAccounts>,
2598    ) {
2599        // update epoch_stakes cache
2600        //  if my parent didn't populate for this staker's epoch, we've
2601        //  crossed a boundary
2602        if !self.epoch_stakes.contains_key(&leader_schedule_epoch) {
2603            self.epoch_stakes.retain(|&epoch, _| {
2604                // Note the greater-than-or-equal (and the `- 1`) is needed here
2605                // to ensure we retain the oldest epoch, if that epoch is 0.
2606                epoch >= leader_schedule_epoch.saturating_sub(MAX_LEADER_SCHEDULE_STAKES - 1)
2607            });
2608            // At the epoch boundary, `compute_new_epoch_caches_and_rewards`
2609            // has already produced the VAT-filtered vote-account snapshot;
2610            // reuse it here instead of re-cloning and re-filtering the
2611            // `stakes_cache`. Other callers (same-epoch refresh, warps)
2612            // fall back to `get_top_epoch_stakes`.
2613            let stakes = match prefiltered_distribution_vote_accounts {
2614                Some(prefiltered) => Stakes::new(prefiltered, self.epoch()),
2615                None => self.get_top_epoch_stakes(),
2616            };
2617            let stakes = SerdeStakesToStakeFormat::from(stakes);
2618            let new_epoch_stakes = VersionedEpochStakes::new(stakes, leader_schedule_epoch);
2619            info!(
2620                "new epoch stakes, epoch: {}, total_stake: {}",
2621                leader_schedule_epoch,
2622                new_epoch_stakes.total_stake(),
2623            );
2624
2625            self.maybe_burn_vat_from_staked_accounts(&new_epoch_stakes);
2626
2627            // It is expensive to log the details of epoch stakes. Only log them at "trace"
2628            // level for debugging purpose.
2629            if log::log_enabled!(log::Level::Trace) {
2630                let vote_stakes: HashMap<_, _> = self
2631                    .stakes_cache
2632                    .stakes()
2633                    .vote_accounts()
2634                    .delegated_stakes()
2635                    .map(|(pubkey, stake)| (*pubkey, stake))
2636                    .collect();
2637                trace!("new epoch stakes, stakes: {vote_stakes:#?}");
2638            }
2639            self.epoch_stakes
2640                .insert(leader_schedule_epoch, new_epoch_stakes);
2641        }
2642    }
2643
2644    /// Burn the Validator Admission ticket from each vote account if Alpenglow is enabled
2645    ///
2646    /// Note: This must ONLY be called after the vote accounts have been filtered (`clone_and_filter_for_vat`)
2647    /// to the top `MAX_ALPENGLOW_VOTE_ACCOUNTS` that contain enough balance for admission.
2648    fn maybe_burn_vat_from_staked_accounts(&mut self, epoch_stakes: &VersionedEpochStakes) {
2649        let feature_snapshot = self.feature_set.snapshot();
2650        if !feature_snapshot.alpenglow {
2651            return;
2652        }
2653
2654        let vat_to_burn_per_epoch = self.vat_to_burn_per_epoch();
2655        let vote_accounts = epoch_stakes.stakes().vote_accounts();
2656        debug_assert!(vote_accounts.len() <= 2000);
2657        // +1 for the incinerator account
2658        let mut accounts_to_store: Vec<(Pubkey, AccountSharedData)> =
2659            Vec::with_capacity(vote_accounts.len() + 1);
2660        let mut total_vat = 0u64;
2661
2662        // Vote accounts have already been filtered by clone_and_filter_for_vat to only include
2663        // accounts with non-zero stake and sufficient balance.
2664        for (vote_pubkey, _stake) in vote_accounts.delegated_stakes() {
2665            let mut account = self.get_account(vote_pubkey).unwrap();
2666            total_vat += vat_to_burn_per_epoch;
2667            account.set_lamports(
2668                account
2669                    .lamports()
2670                    .checked_sub(vat_to_burn_per_epoch)
2671                    .expect(
2672                        "Vote accounts should have already been filtered to contain enough \
2673                         balance for the VAT",
2674                    ),
2675            );
2676            accounts_to_store.push((*vote_pubkey, account));
2677        }
2678
2679        // Per SIMD-0357, transfer collected VAT to the incinerator account.
2680        let mut incinerator_account = self.get_account(&incinerator::id()).unwrap_or_default();
2681        incinerator_account.set_lamports(
2682            incinerator_account
2683                .lamports()
2684                .checked_add(total_vat)
2685                .unwrap(),
2686        );
2687        accounts_to_store.push((incinerator::id(), incinerator_account));
2688
2689        self.store_accounts((self.slot, accounts_to_store.as_slice()), None);
2690        info!(
2691            "Transferred total VAT of {total_vat} lamports to incinerator from staked vote \
2692             accounts"
2693        );
2694    }
2695
2696    #[cfg(feature = "dev-context-only-utils")]
2697    pub fn set_epoch_stakes_for_test(&mut self, epoch: Epoch, stakes: VersionedEpochStakes) {
2698        self.epoch_stakes.insert(epoch, stakes);
2699    }
2700
2701    fn update_rent(&self) {
2702        self.update_sysvar_account(&sysvar::rent::id(), |account| {
2703            create_account(
2704                &self.rent_collector.rent,
2705                self.inherit_specially_retained_account_fields(account),
2706            )
2707        });
2708    }
2709
2710    fn update_epoch_schedule(&self) {
2711        self.update_sysvar_account(&sysvar::epoch_schedule::id(), |account| {
2712            create_account(
2713                self.epoch_schedule(),
2714                self.inherit_specially_retained_account_fields(account),
2715            )
2716        });
2717    }
2718
2719    fn update_stake_history(&self, epoch: Option<Epoch>) {
2720        if epoch == Some(self.epoch()) {
2721            return;
2722        }
2723        // if I'm the first Bank in an epoch, ensure stake_history is updated
2724        self.update_sysvar_account(&stake_history::id(), |account| {
2725            create_account::<StakeHistory>(
2726                self.stakes_cache.stakes().history(),
2727                self.inherit_specially_retained_account_fields(account),
2728            )
2729        });
2730    }
2731
2732    /// Rebuilds slot-param state from the current feature set.
2733    fn refresh_slot_params(&mut self) {
2734        self.refresh_slot_params_with_baseline(self.slot_params.baseline_params());
2735    }
2736
2737    fn refresh_slot_params_from_snapshot(&mut self, genesis_config: &GenesisConfig) {
2738        let (feature_set, _) = self.compute_active_feature_set(false);
2739        self.refresh_slot_params_with_baseline(
2740            self.snapshot_restore_slot_params_baseline(genesis_config, &feature_set),
2741        );
2742    }
2743
2744    /// Rebuilds cached slot params while preserving the supplied slot-0 baseline.
2745    ///
2746    /// The cache is not serialized into snapshots; it is reconstructed from
2747    /// existing Bank fields during genesis and snapshot restore.
2748    fn refresh_slot_params_with_baseline(&mut self, baseline_params: SlotParams) {
2749        self.slot_params =
2750            SlotParamsArchive::new(&self.feature_set, &self.epoch_schedule, baseline_params);
2751    }
2752
2753    /// Builds slot-0 params from the genesis config.
2754    fn genesis_config_slot_params(
2755        genesis_config: &GenesisConfig,
2756        partitioned_rewards_stake_account_stores_per_block: u64,
2757    ) -> SlotParams {
2758        SlotParams::genesis_baseline(
2759            genesis_config.ns_per_slot(),
2760            genesis_config.slots_per_year(),
2761            genesis_config.hashes_per_tick(),
2762            partitioned_rewards_stake_account_stores_per_block,
2763        )
2764    }
2765
2766    /// Builds the slot-param baseline from the restored bank fields.
2767    ///
2768    /// Snapshot fields represent the cluster's current reality. This can
2769    /// differ from genesis for values, such as `hashes_per_tick`, that were
2770    /// changed by older feature gates before slot-time reductions existed.
2771    fn restored_bank_slot_params(&self) -> SlotParams {
2772        SlotParams::genesis_baseline(
2773            self.ns_per_slot,
2774            self.slots_per_year,
2775            self.hashes_per_tick(),
2776            self.partitioned_rewards_stake_account_stores_per_block,
2777        )
2778    }
2779
2780    /// Returns true if any slot-time reduction has taken effect by this bank.
2781    ///
2782    /// Feature activation happens in one epoch, but slot params become effective
2783    /// at the start of the following epoch.
2784    fn any_slot_time_reduction_effective(
2785        &self,
2786        feature_set: &FeatureSet,
2787        ns_per_slot: u128,
2788    ) -> bool {
2789        SlotParamsArchive::any_slot_time_reduction_effective(
2790            &self.epoch_schedule,
2791            self.slot,
2792            feature_set,
2793            ns_per_slot,
2794        )
2795    }
2796
2797    /// Selects the slot-param baseline to use when reconstructing from snapshot.
2798    ///
2799    /// Before any slot-time reduction is effective, the baseline should match
2800    /// restored bank fields because historical non-slot-time feature gates may
2801    /// have already changed some values away from genesis. Once a slot-time
2802    /// reduction is effective, keep the genesis baseline so historical lookups
2803    /// for pre-reduction slots remain correct.
2804    fn snapshot_restore_slot_params_baseline(
2805        &self,
2806        genesis_config: &GenesisConfig,
2807        feature_set: &FeatureSet,
2808    ) -> SlotParams {
2809        if self.any_slot_time_reduction_effective(feature_set, genesis_config.ns_per_slot()) {
2810            Self::genesis_config_slot_params(
2811                genesis_config,
2812                self.partitioned_rewards_stake_account_stores_per_block,
2813            )
2814        } else {
2815            // Default to whatever is in the bank if we've never enabled any
2816            // slot time reductions. This prevents resetting any slot params
2817            // that may have been changed previously back to genesis.
2818            self.restored_bank_slot_params()
2819        }
2820    }
2821
2822    /// Returns the slot params effective at `slot`.
2823    fn slot_params_at_slot(&self, slot: Slot) -> SlotParams {
2824        self.slot_params.params_at_slot(slot)
2825    }
2826
2827    /// Returns the slot params that should be effective for this bank's slot.
2828    fn current_slot_params(&self) -> SlotParams {
2829        self.slot_params_at_slot(self.slot)
2830    }
2831
2832    /// Returns the Validator Admission Ticket burn for this bank's slot params.
2833    pub(crate) fn vat_to_burn_per_epoch(&self) -> u64 {
2834        self.current_slot_params().vat_to_burn_per_epoch()
2835    }
2836
2837    pub fn get_vat_health_for_next_epoch(
2838        &self,
2839        vote_account_pubkey: &Pubkey,
2840    ) -> std::result::Result<(), VATHealthError> {
2841        let vote_accounts = self.vote_accounts();
2842
2843        let Some((_, vote_account)) = vote_accounts.get(vote_account_pubkey) else {
2844            return Err(VATHealthError::VoteAccountNotFound);
2845        };
2846
2847        if vote_account
2848            .vote_state_view()
2849            .bls_pubkey_compressed()
2850            .is_none()
2851        {
2852            return Err(VATHealthError::NoBLSPubkey);
2853        }
2854
2855        let my_balance = vote_account.lamports();
2856        let minimum_vote_account_balance_for_vat = self.minimum_vote_account_balance_for_vat();
2857        if vote_account.lamports() < minimum_vote_account_balance_for_vat {
2858            return Err(VATHealthError::InsufficientFundsInVoteAccount(
2859                my_balance,
2860                minimum_vote_account_balance_for_vat,
2861            ));
2862        }
2863
2864        Ok(())
2865    }
2866
2867    /// Returns the effective slot duration for `slot`.
2868    pub fn ns_per_slot_at_slot(&self, slot: Slot) -> u128 {
2869        self.slot_params_at_slot(slot).ns_per_slot()
2870    }
2871
2872    /// Returns slots/year for the slot params active at `epoch` start.
2873    fn slots_per_year_for_epoch(&self, epoch: Epoch) -> f64 {
2874        let first_slot = self.epoch_schedule().get_first_slot_in_epoch(epoch);
2875        self.slot_params_at_slot(first_slot).slots_per_year()
2876    }
2877
2878    /// Returns the wall-clock duration in years for `[start_slot, end_slot)`.
2879    fn slot_range_duration_in_years(&self, start_slot: Slot, end_slot: Slot) -> f64 {
2880        if start_slot >= end_slot {
2881            return 0.0;
2882        }
2883
2884        let mut cursor = start_slot;
2885        let mut params = self.slot_params.baseline_params();
2886        let mut duration = 0.0;
2887
2888        for (effective_slot, effective_params) in self.slot_params.param_transitions() {
2889            if effective_slot <= start_slot {
2890                params = effective_params;
2891                continue;
2892            }
2893            if effective_slot >= end_slot {
2894                break;
2895            }
2896
2897            duration += (effective_slot - cursor) as f64 / params.slots_per_year();
2898            cursor = effective_slot;
2899            params = effective_params;
2900        }
2901
2902        duration + (end_slot - cursor) as f64 / params.slots_per_year()
2903    }
2904
2905    /// Returns the exact wall-clock duration in nanoseconds for `start_slot..=end_slot`.
2906    pub fn slot_range_duration_nanos(&self, start_slot: Slot, end_slot: Slot) -> u128 {
2907        self.slot_params
2908            .slot_range_duration_nanos(start_slot, end_slot)
2909    }
2910
2911    pub fn epoch_duration_in_years(&self, epoch: Epoch) -> f64 {
2912        // period: time that has passed as a fraction of a year, basically the length of
2913        //  an epoch as a fraction of a year
2914        //  calculated as: slots_elapsed / (slots / year)
2915        self.epoch_schedule().get_slots_in_epoch(epoch) as f64
2916            / self.slots_per_year_for_epoch(epoch)
2917    }
2918
2919    pub fn max_processing_age(&self) -> usize {
2920        self.max_processing_age
2921    }
2922
2923    // Calculates the starting-slot for inflation from the activation slot.
2924    // This method assumes that `pico_inflation` will be enabled before `full_inflation`, giving
2925    // precedence to the latter. However, since `pico_inflation` is fixed-rate Inflation, should
2926    // `pico_inflation` be enabled 2nd, the incorrect start slot provided here should have no
2927    // effect on the inflation calculation.
2928    fn get_inflation_start_slot(&self) -> Slot {
2929        let mut slots = self
2930            .feature_set
2931            .full_inflation_features_enabled()
2932            .iter()
2933            .filter_map(|id| self.feature_set.activated_slot(id))
2934            .collect::<Vec<_>>();
2935        slots.sort_unstable();
2936        slots.first().cloned().unwrap_or_else(|| {
2937            self.feature_set
2938                .activated_slot(&feature_set::pico_inflation::id())
2939                .unwrap_or(0)
2940        })
2941    }
2942
2943    /// Returns slots since inflation started, aligned to the first slot used for rewards accrual.
2944    fn get_inflation_num_slots(&self) -> u64 {
2945        let inflation_start_slot = self.inflation_start_slot_aligned_to_rewards();
2946        self.epoch_schedule().get_first_slot_in_epoch(self.epoch()) - inflation_start_slot
2947    }
2948
2949    /// Returns the inflation rewards start slot aligned to an epoch boundary.
2950    fn inflation_start_slot_aligned_to_rewards(&self) -> Slot {
2951        let inflation_activation_slot = self.get_inflation_start_slot();
2952        self.epoch_schedule().get_first_slot_in_epoch(
2953            self.epoch_schedule()
2954                .get_epoch(inflation_activation_slot)
2955                .saturating_sub(1),
2956        )
2957    }
2958
2959    /// Returns elapsed inflation time in years for slots since inflation started.
2960    pub fn slot_in_year_for_inflation(&self) -> f64 {
2961        let num_slots = self.get_inflation_num_slots();
2962        let inflation_start_slot = self.inflation_start_slot_aligned_to_rewards();
2963        self.slot_range_duration_in_years(inflation_start_slot, inflation_start_slot + num_slots)
2964    }
2965
2966    /// For a given `capitalization` (total_supply in lamports) and `epoch`, returns the
2967    /// `epoch inflation rewards` in lamports.
2968    pub(crate) fn calculate_epoch_inflation_rewards(
2969        &self,
2970        capitalization: u64,
2971        epoch: Epoch,
2972    ) -> u64 {
2973        let slot_in_year = self.slot_in_year_for_inflation();
2974        let validator_rate = self.inflation.read().unwrap().validator(slot_in_year);
2975        let epoch_duration_in_years = self.epoch_duration_in_years(epoch);
2976        (validator_rate * capitalization as f64 * epoch_duration_in_years) as u64
2977    }
2978
2979    fn update_recent_blockhashes_locked(&self, locked_blockhash_queue: &BlockhashQueue) {
2980        #[expect(deprecated)]
2981        self.update_sysvar_account(&sysvar::recent_blockhashes::id(), |account| {
2982            let recent_blockhash_iter = locked_blockhash_queue.get_recent_blockhashes();
2983            recent_blockhashes_account::create_account_with_data_and_fields(
2984                recent_blockhash_iter,
2985                self.inherit_specially_retained_account_fields(account),
2986            )
2987        });
2988    }
2989
2990    pub fn update_recent_blockhashes(&self) {
2991        let blockhash_queue = self.blockhash_queue.read().unwrap();
2992        self.update_recent_blockhashes_locked(&blockhash_queue);
2993    }
2994
2995    fn get_timestamp_estimate(
2996        &self,
2997        max_allowable_drift: MaxAllowableDrift,
2998        epoch_start_timestamp: Option<(Slot, UnixTimestamp)>,
2999    ) -> Option<UnixTimestamp> {
3000        let mut get_timestamp_estimate_time = Measure::start("get_timestamp_estimate");
3001        let slots_per_epoch = self.epoch_schedule().slots_per_epoch;
3002        let vote_accounts = self.vote_accounts();
3003        let recent_timestamps = vote_accounts.iter().filter_map(|(pubkey, (_, account))| {
3004            let vote_state = account.vote_state_view();
3005            let last_timestamp = vote_state.last_timestamp();
3006            let slot_delta = self.slot().checked_sub(last_timestamp.slot)?;
3007            (slot_delta <= slots_per_epoch)
3008                .then_some((*pubkey, (last_timestamp.slot, last_timestamp.timestamp)))
3009        });
3010        let elapsed_slot_duration = |from_slot: Slot, to_slot: Slot| {
3011            if from_slot >= to_slot {
3012                Duration::ZERO
3013            } else {
3014                Duration::from_nanos_u128(
3015                    self.slot_range_duration_nanos(from_slot.saturating_add(1), to_slot),
3016                )
3017            }
3018        };
3019        let epoch = self.epoch_schedule().get_epoch(self.slot());
3020        let stakes = self.epoch_vote_accounts(epoch)?;
3021        let stake_weighted_timestamp = calculate_stake_weighted_timestamp(
3022            recent_timestamps,
3023            stakes,
3024            self.slot(),
3025            elapsed_slot_duration,
3026            epoch_start_timestamp,
3027            max_allowable_drift,
3028        );
3029        get_timestamp_estimate_time.stop();
3030        datapoint_info!(
3031            "bank-timestamp",
3032            (
3033                "get_timestamp_estimate_us",
3034                get_timestamp_estimate_time.as_us(),
3035                i64
3036            ),
3037        );
3038        stake_weighted_timestamp
3039    }
3040
3041    /// Recalculates the bank hash
3042    ///
3043    /// This is used by ledger-tool when creating a snapshot, which
3044    /// recalculates the bank hash.
3045    ///
3046    /// Note that the account state is *not* allowed to change by rehashing.
3047    /// If modifying accounts in ledger-tool is needed, create a new bank.
3048    pub fn rehash(&self) {
3049        let mut hash = self.hash.write().unwrap();
3050        let new = self.hash_internal_state();
3051        if new != *hash {
3052            warn!("Updating bank hash to {new}");
3053            *hash = new;
3054        }
3055    }
3056
3057    pub fn freeze(&self) {
3058        // This lock prevents any new commits from BankingStage
3059        // `Consumer::execute_and_commit_transactions_locked()` from
3060        // coming in after the last tick is observed. This is because in
3061        // BankingStage, any transaction successfully recorded in
3062        // `record_transactions()` is recorded after this `hash` lock
3063        // is grabbed. At the time of the successful record,
3064        // this means the PoH has not yet reached the last tick,
3065        // so this means freeze() hasn't been called yet. And because
3066        // BankingStage doesn't release this hash lock until both
3067        // record and commit are finished, those transactions will be
3068        // committed before this write lock can be obtained here.
3069        let mut hash = self.hash.write().unwrap();
3070        if *hash == Hash::default() {
3071            // finish up any deferred changes to account state
3072            self.distribute_transaction_fee_details();
3073            self.update_slot_history();
3074            self.run_incinerator();
3075
3076            // freeze is a one-way trip, idempotent
3077            self.freeze_started.store(true, Relaxed);
3078            // updating the accounts lt hash must happen *outside* of hash_internal_state() so
3079            // that rehash() can be called and *not* modify self.accounts_lt_hash.
3080            self.finish_accounts_lt_hash_updates();
3081            *hash = self.hash_internal_state();
3082            self.rc.accounts.accounts_db.mark_slot_frozen(self.slot());
3083        }
3084    }
3085
3086    /// Freeze the bank and verify its computed bank hash against the expected bank hash,
3087    /// If hashes do not match, return Err with (expected_hash, computed_hash)
3088    pub fn freeze_and_verify_bank_hash(&self) -> std::result::Result<(), (Hash, Hash)> {
3089        self.freeze();
3090        let computed_hash = self.hash();
3091
3092        if let Some(expected_hash) = self.expected_bank_hash()
3093            && expected_hash != computed_hash
3094        {
3095            return Err((expected_hash, computed_hash));
3096        }
3097        Ok(())
3098    }
3099
3100    /// Set the expected bank hash (from an external footer).  This is stored for later verification
3101    /// when the bank is frozen.
3102    pub fn set_expected_bank_hash(&self, hash: Hash) {
3103        *self.expected_bank_hash.write().unwrap() = Some(hash);
3104    }
3105
3106    /// Returns the expected bank hash if any.
3107    pub fn expected_bank_hash(&self) -> Option<Hash> {
3108        *self.expected_bank_hash.read().unwrap()
3109    }
3110
3111    // dangerous; don't use this; this is only needed for ledger-tool's special command
3112    #[cfg(feature = "dev-context-only-utils")]
3113    pub fn unfreeze_for_ledger_tool(&self) {
3114        self.freeze_started.store(false, Relaxed);
3115    }
3116
3117    pub fn epoch_schedule(&self) -> &EpochSchedule {
3118        &self.epoch_schedule
3119    }
3120
3121    /// squash the parent's state up into this Bank,
3122    ///   this Bank becomes a root
3123    /// Note that this function is not thread-safe. If it is called concurrently on the same bank
3124    /// by multiple threads, the end result could be inconsistent.
3125    /// Calling code does not currently call this concurrently.
3126    pub fn squash(&self) -> SquashTiming {
3127        self.freeze();
3128
3129        //this bank and all its parents are now on the rooted path
3130        let mut roots = Vec::with_capacity(self.ancestors.len());
3131        roots.push(self.slot());
3132        roots.extend(self.parents_iter().map(|parent| parent.slot()));
3133
3134        let mut total_cache_us = 0;
3135
3136        let mut squash_accounts_time = Measure::start("squash_accounts_time");
3137        for slot in roots.iter().rev() {
3138            // root forks cannot be purged
3139            let add_root_timing = self.rc.accounts.add_root(*slot);
3140            total_cache_us += add_root_timing.cache_us;
3141        }
3142        squash_accounts_time.stop();
3143
3144        *self.rc.parent.write().unwrap() = None;
3145
3146        let mut squash_cache_time = Measure::start("squash_cache_time");
3147        self.status_cache
3148            .write()
3149            .unwrap()
3150            .add_roots(roots.iter().copied());
3151        squash_cache_time.stop();
3152
3153        SquashTiming {
3154            squash_accounts_ms: squash_accounts_time.as_ms(),
3155            squash_accounts_cache_ms: total_cache_us / 1000,
3156            squash_cache_ms: squash_cache_time.as_ms(),
3157        }
3158    }
3159
3160    /// Return the more recent checkpoint of this bank instance.
3161    pub fn parent(&self) -> Option<Arc<Bank>> {
3162        self.rc.parent.read().unwrap().clone()
3163    }
3164
3165    pub fn parent_slot(&self) -> Slot {
3166        self.parent_slot
3167    }
3168
3169    pub fn parent_hash(&self) -> Hash {
3170        self.parent_hash
3171    }
3172
3173    fn process_genesis_config(
3174        &mut self,
3175        genesis_config: &GenesisConfig,
3176        #[cfg(feature = "dev-context-only-utils")] leader_for_tests: Option<SlotLeader>,
3177        #[cfg(feature = "dev-context-only-utils")] genesis_hash: Option<Hash>,
3178    ) {
3179        // Bootstrap validator collects fees until `new_from_parent` is called.
3180        self.fee_rate_governor = genesis_config.fee_rate_governor.clone();
3181
3182        for (pubkey, account) in genesis_config.accounts.iter() {
3183            assert!(
3184                self.get_account(pubkey).is_none(),
3185                "{pubkey} repeated in genesis config"
3186            );
3187            let account_shared_data = create_account_shared_data(account);
3188            self.store_account_without_stakes_cache(pubkey, &account_shared_data);
3189            self.capitalization.fetch_add(account.lamports(), Relaxed);
3190            self.accounts_data_size_initial += account.data().len() as u64;
3191        }
3192
3193        for (pubkey, account) in genesis_config.rewards_pools.iter() {
3194            assert!(
3195                self.get_account(pubkey).is_none(),
3196                "{pubkey} repeated in genesis config"
3197            );
3198            let account_shared_data = create_account_shared_data(account);
3199            self.store_account_without_stakes_cache(pubkey, &account_shared_data);
3200            self.accounts_data_size_initial += account.data().len() as u64;
3201        }
3202
3203        self.stakes_cache = StakesCache::new(Stakes::new_from_accounts_for_genesis(
3204            self.new_warmup_cooldown_rate_epoch(),
3205            genesis_config.accounts.iter(),
3206            self.use_fixed_point_stake_math(),
3207        ));
3208
3209        // After storing genesis accounts, the bank stakes cache will be warmed
3210        // up and can be used to set the leader id to the highest staked
3211        // node.
3212        let leader = self.stakes_cache.stakes().highest_staked_node();
3213        // If a leader is specified for test purposes, use that and if no leader found, use a random one.
3214        #[cfg(feature = "dev-context-only-utils")]
3215        let leader = leader_for_tests
3216            .or(leader)
3217            .or(Some(SlotLeader::new_unique()));
3218        self.leader = leader.expect("genesis processing failed because no staked nodes exist");
3219
3220        #[cfg(not(feature = "dev-context-only-utils"))]
3221        let genesis_hash = genesis_config.hash();
3222        #[cfg(feature = "dev-context-only-utils")]
3223        let genesis_hash = genesis_hash.unwrap_or(genesis_config.hash());
3224
3225        self.blockhash_queue.write().unwrap().genesis_hash(
3226            &genesis_hash,
3227            genesis_config.fee_rate_governor.lamports_per_signature,
3228        );
3229
3230        self.hashes_per_tick = RwLock::new(genesis_config.hashes_per_tick());
3231        self.ticks_per_slot = genesis_config.ticks_per_slot();
3232        self.ns_per_slot = genesis_config.ns_per_slot();
3233        self.genesis_creation_time = genesis_config.creation_time;
3234        self.max_tick_height = (self.slot + 1) * self.ticks_per_slot;
3235        self.slots_per_year = genesis_config.slots_per_year();
3236
3237        self.epoch_schedule = genesis_config.epoch_schedule.clone();
3238        self.refresh_slot_params_with_baseline(Self::genesis_config_slot_params(
3239            genesis_config,
3240            self.partitioned_rewards_stake_account_stores_per_block,
3241        ));
3242
3243        self.inflation = Arc::new(RwLock::new(genesis_config.inflation));
3244
3245        self.rent_collector = RentCollector::new(
3246            self.epoch,
3247            self.epoch_schedule().clone(),
3248            self.slots_per_year,
3249            genesis_config.rent.clone(),
3250        );
3251    }
3252
3253    fn burn_and_purge_account(&self, program_id: &Pubkey, mut account: AccountSharedData) {
3254        let old_data_size = account.data().len();
3255        self.capitalization.fetch_sub(account.lamports(), Relaxed);
3256        // Both resetting account balance to 0 and zeroing the account data
3257        // is needed to really purge from AccountsDb and flush the Stakes cache
3258        account.set_lamports(0);
3259        account.data_as_mut_slice().fill(0);
3260        self.store_account(program_id, &account);
3261        self.calculate_and_update_accounts_data_size_delta_off_chain(old_data_size, 0);
3262    }
3263
3264    /// Add a precompiled program account
3265    pub fn add_precompiled_account(&self, program_id: &Pubkey) {
3266        self.add_precompiled_account_with_owner(program_id, native_loader::id())
3267    }
3268
3269    // Used by tests to simulate clusters with precompiles that aren't owned by the native loader
3270    fn add_precompiled_account_with_owner(&self, program_id: &Pubkey, owner: Pubkey) {
3271        if let Some(account) = self.get_account_with_fixed_root(program_id) {
3272            if account.executable() {
3273                return;
3274            } else {
3275                // malicious account is pre-occupying at program_id
3276                self.burn_and_purge_account(program_id, account);
3277            }
3278        };
3279
3280        assert!(
3281            !self.freeze_started(),
3282            "Can't change frozen bank by adding not-existing new precompiled program \
3283             ({program_id}). Maybe, inconsistent program activation is detected on snapshot \
3284             restore?"
3285        );
3286
3287        // Add a bogus executable account, which will be loaded and ignored.
3288        let (lamports, rent_epoch) = self.inherit_specially_retained_account_fields(&None);
3289
3290        let account = AccountSharedData::from(Account {
3291            lamports,
3292            owner,
3293            data: vec![],
3294            executable: true,
3295            rent_epoch,
3296        });
3297        self.store_account_and_update_capitalization(program_id, &account);
3298    }
3299
3300    #[allow(deprecated)]
3301    pub fn set_rent_burn_percentage(&mut self, burn_percent: u8) {
3302        self.rent_collector.rent.burn_percent = burn_percent;
3303    }
3304
3305    pub fn set_hashes_per_tick(&self, hashes_per_tick: Option<u64>) {
3306        *self.hashes_per_tick.write().unwrap() = hashes_per_tick;
3307    }
3308
3309    /// Return the last block hash registered.
3310    pub fn last_blockhash(&self) -> Hash {
3311        self.blockhash_queue.read().unwrap().last_hash()
3312    }
3313
3314    pub fn last_blockhash_and_lamports_per_signature(&self) -> (Hash, u64) {
3315        let blockhash_queue = self.blockhash_queue.read().unwrap();
3316        let last_hash = blockhash_queue.last_hash();
3317        let last_lamports_per_signature = blockhash_queue
3318            .get_lamports_per_signature(&last_hash)
3319            .unwrap(); // safe so long as the BlockhashQueue is consistent
3320        (last_hash, last_lamports_per_signature)
3321    }
3322
3323    pub fn is_blockhash_valid(&self, hash: &Hash) -> bool {
3324        let blockhash_queue = self.blockhash_queue.read().unwrap();
3325        blockhash_queue.is_hash_valid_for_age(hash, self.max_processing_age())
3326    }
3327
3328    pub fn get_minimum_balance_for_rent_exemption(&self, data_len: usize) -> u64 {
3329        self.rent_collector.rent.minimum_balance(data_len).max(1)
3330    }
3331
3332    pub fn get_lamports_per_signature(&self) -> u64 {
3333        self.fee_rate_governor.lamports_per_signature
3334    }
3335
3336    /// Convert Agave's active feature set into the fee crate's narrowed feature view.
3337    pub fn fee_features(&self) -> FeeFeatures {
3338        FeeFeatures {}
3339    }
3340
3341    pub fn get_lamports_per_signature_for_blockhash(&self, hash: &Hash) -> Option<u64> {
3342        let blockhash_queue = self.blockhash_queue.read().unwrap();
3343        blockhash_queue.get_lamports_per_signature(hash)
3344    }
3345
3346    pub fn get_fee_for_message(&self, message: &SanitizedMessage) -> Option<u64> {
3347        {
3348            let blockhash_queue = self.blockhash_queue.read().unwrap();
3349            blockhash_queue.get_lamports_per_signature(message.recent_blockhash())
3350        }
3351        .or_else(|| {
3352            self.load_message_nonce_data(message, false)
3353                .map(|(_nonce_address, nonce_data)| nonce_data.get_lamports_per_signature())
3354        })?;
3355
3356        let transaction_configuration =
3357            TransactionConfiguration::try_from_sanitized_message(message, &self.feature_set)
3358                .ok()?;
3359        Some(solana_fee::calculate_fee(
3360            message,
3361            self.fee_structure().lamports_per_signature,
3362            transaction_configuration.priority_fee_lamports,
3363            self.fee_features(),
3364        ))
3365    }
3366
3367    pub fn get_blockhash_last_valid_block_height(&self, blockhash: &Hash) -> Option<Slot> {
3368        let blockhash_queue = self.blockhash_queue.read().unwrap();
3369        // This calculation will need to be updated to consider epoch boundaries if BlockhashQueue
3370        // length is made variable by epoch
3371        blockhash_queue
3372            .get_hash_age(blockhash)
3373            .map(|age| self.block_height + self.max_processing_age() as u64 - age)
3374    }
3375
3376    /// Query the alpenglow genesis certificate account.
3377    /// All frozen alpenglow banks will have this account populated and TowerBFT banks will not.
3378    ///
3379    /// The same is true for alpenglow banks yet to be frozen except for the first alpenglow bank:
3380    /// - The first alpenglow bank will contain a special marker that populates this account
3381    /// - If `get_alpenglow_genesis_certificate` is called before the marker is processed by replay
3382    ///   this account will be empty.
3383    /// - If `get_alpenglow_genesis_certificate` is called after the marker is processed, we return the certificate
3384    pub fn get_alpenglow_genesis_certificate(&self) -> Option<GenesisCert> {
3385        let acct = self.get_account(&GENESIS_CERTIFICATE_ACCOUNT)?;
3386        (!acct.data().is_empty()).then(|| {
3387            // The address is known in advance, so the account could already exist if it was prefunded.
3388            // However this account cannot be written to except by us in `set_alpenglow_genesis_certificate`,
3389            // so this deserialize is safe if the account is non-empty
3390            let cert: WireBlockCertMessage = wincode::deserialize(acct.data())
3391                .expect("Programmer error deserializing genesis certificate");
3392            GenesisCert {
3393                block: cert.block,
3394                signature: CertSignature {
3395                    signature: cert.signature.signature,
3396                    bitmap: cert.signature.bitmap,
3397                },
3398            }
3399        })
3400    }
3401
3402    pub fn is_alpenglow(&self) -> bool {
3403        self.is_alpenglow.load(Relaxed)
3404    }
3405
3406    fn set_is_alpenglow(&self) {
3407        self.is_alpenglow.store(true, Relaxed);
3408    }
3409
3410    /// For use in the first Alpenglow block, set the genesis certificate.
3411    pub fn set_alpenglow_genesis_certificate(&self, cert: &GenesisCert) {
3412        let cert = WireBlockCertMessage {
3413            block: cert.block,
3414            signature: WireCertSignature {
3415                signature: cert.signature.signature,
3416                bitmap: cert.signature.bitmap.clone(),
3417            },
3418        };
3419        let data = wincode::serialize(&cert).unwrap();
3420        let lamports = Rent::default().minimum_balance(data.len());
3421        let mut cert_acct = AccountSharedData::new(lamports, data.len(), &system_program::ID);
3422        cert_acct.set_data_from_slice(&data);
3423
3424        self.store_account_and_update_capitalization(&GENESIS_CERTIFICATE_ACCOUNT, &cert_acct);
3425        self.set_is_alpenglow();
3426    }
3427
3428    /// Update the clock sysvar from a block footer's nanosecond timestamp.
3429    /// Also stores the nanosecond value for later retrieval via `get_nanosecond_clock`.
3430    pub fn update_clock_from_footer(&self, unix_timestamp_nanos: i64) {
3431        if !self.feature_set.snapshot().alpenglow {
3432            return;
3433        }
3434
3435        // On epoch boundaries, update epoch_start_timestamp
3436        //
3437        // Note: the genesis block's bank is created via new_from_genesis, which calls update_clock
3438        // unconditionally. In update_clock, we have a check for whether slot == 0, and if that's
3439        // the case, the clock is set to self.unix_timestamp_from_genesis().
3440        //
3441        // As a result, we don't actually need the (0, _) case below, since it's never invoked.
3442        // However, include this for completeness in the match statement.
3443        let unix_timestamp_s = unix_timestamp_nanos / 1_000_000_000;
3444        let epoch_start_timestamp = match (self.slot, self.parent()) {
3445            (0, _) => self.unix_timestamp_from_genesis(),
3446            (_, Some(parent)) if parent.epoch() != self.epoch() => unix_timestamp_s,
3447            _ => self.clock().epoch_start_timestamp,
3448        };
3449
3450        // Update clock sysvar
3451        // NOTE: block footer UNIX timestamps are in nanoseconds, but clock sysvar stores timestamps
3452        // in seconds
3453        let clock = sysvar::clock::Clock {
3454            slot: self.slot,
3455            epoch_start_timestamp,
3456            epoch: self.epoch_schedule().get_epoch(self.slot),
3457            leader_schedule_epoch: self.epoch_schedule().get_leader_schedule_epoch(self.slot),
3458            unix_timestamp: unix_timestamp_s,
3459        };
3460
3461        self.update_sysvar_account(&sysvar::clock::id(), |account| {
3462            create_account(
3463                &clock,
3464                self.inherit_specially_retained_account_fields(account),
3465            )
3466        });
3467
3468        // Update Alpenglow clock
3469        let data = wincode::serialize(&unix_timestamp_nanos).unwrap();
3470        let lamports = Rent::default().minimum_balance(data.len());
3471        let mut alpenclock_acct = AccountSharedData::new(lamports, data.len(), &system_program::ID);
3472        alpenclock_acct.set_data_from_slice(&data);
3473
3474        self.store_account_and_update_capitalization(&NANOSECOND_CLOCK_ACCOUNT, &alpenclock_acct);
3475
3476        self.transaction_processor
3477            .reset_and_fill_sysvar_cache_entries(self);
3478    }
3479
3480    /// Get the nanosecond clock value. Returns `None` if the nanosecond clock has not been
3481    /// populated (i.e., before Alpenglow migration completes).
3482    pub fn get_nanosecond_clock(&self) -> Option<i64> {
3483        let acct = self.get_account(&NANOSECOND_CLOCK_ACCOUNT)?;
3484        (!acct.data().is_empty()).then(|| {
3485            // This address is known in advance, so the account could already exist if it was prefunded.
3486            // The deserialize is only safe when the account is non-empty
3487            wincode::deserialize(acct.data())
3488                .expect("Couldn't deserialize nanosecond resolution clock")
3489        })
3490    }
3491
3492    pub fn confirmed_last_blockhash(&self) -> Hash {
3493        const NUM_BLOCKHASH_CONFIRMATIONS: usize = 3;
3494
3495        let mut last_parent = None;
3496        for (index, parent) in self.parents_iter().enumerate() {
3497            if index == NUM_BLOCKHASH_CONFIRMATIONS {
3498                return parent.last_blockhash();
3499            }
3500            last_parent = Some(parent);
3501        }
3502        last_parent.map_or_else(|| self.last_blockhash(), |parent| parent.last_blockhash())
3503    }
3504
3505    /// Forget all signatures. Useful for benchmarking.
3506    #[cfg(feature = "dev-context-only-utils")]
3507    pub fn clear_signatures(&self) {
3508        self.status_cache.write().unwrap().clear();
3509    }
3510
3511    pub fn clear_slot_signatures(&self, slot: Slot) {
3512        self.status_cache.write().unwrap().clear_slot_entries(slot);
3513    }
3514
3515    fn update_transaction_statuses(
3516        &self,
3517        sanitized_txs: &[impl TransactionWithMeta],
3518        processing_results: &[TransactionProcessingResult],
3519    ) {
3520        let mut status_cache = self.status_cache.write().unwrap();
3521        assert_eq!(sanitized_txs.len(), processing_results.len());
3522        for (tx, processing_result) in sanitized_txs.iter().zip(processing_results) {
3523            if let Ok(processed_tx) = &processing_result {
3524                // Add the message hash to the status cache to ensure that this message
3525                // won't be processed again with a different signature.
3526                status_cache.insert(
3527                    tx.recent_blockhash(),
3528                    tx.message_hash(),
3529                    self.slot(),
3530                    processed_tx.status(),
3531                );
3532                if self.store_transaction_signatures_in_status_cache {
3533                    // Add the transaction signature to the status cache so that transaction
3534                    // status can be queried by transaction signature over RPC.
3535                    status_cache.insert(
3536                        tx.recent_blockhash(),
3537                        tx.signature(),
3538                        self.slot(),
3539                        processed_tx.status(),
3540                    );
3541                }
3542            }
3543        }
3544    }
3545
3546    /// Register a new recent blockhash in the bank's recent blockhash queue. Called when a bank
3547    /// reaches its max tick height. Can be called by tests to get new blockhashes for transaction
3548    /// processing without advancing to a new bank slot.
3549    fn register_recent_blockhash(&self, blockhash: &Hash, scheduler: &InstalledSchedulerRwLock) {
3550        // This is needed because recent_blockhash updates necessitate synchronizations for
3551        // consistent tx check_age handling.
3552        BankWithScheduler::wait_for_paused_scheduler(self, scheduler);
3553
3554        // Only acquire the write lock for the blockhash queue on block boundaries because
3555        // readers can starve this write lock acquisition and ticks would be slowed down too
3556        // much if the write lock is acquired for each tick.
3557        let mut w_blockhash_queue = self.blockhash_queue.write().unwrap();
3558
3559        #[cfg(feature = "dev-context-only-utils")]
3560        let blockhash_override = self
3561            .hash_overrides
3562            .lock()
3563            .unwrap()
3564            .get_blockhash_override(self.slot())
3565            .copied()
3566            .inspect(|blockhash_override| {
3567                if blockhash_override != blockhash {
3568                    info!(
3569                        "bank: slot: {}: overrode blockhash: {} with {}",
3570                        self.slot(),
3571                        blockhash,
3572                        blockhash_override
3573                    );
3574                }
3575            });
3576        #[cfg(feature = "dev-context-only-utils")]
3577        let blockhash = blockhash_override.as_ref().unwrap_or(blockhash);
3578
3579        w_blockhash_queue.register_hash(blockhash, self.fee_rate_governor.lamports_per_signature);
3580        self.update_recent_blockhashes_locked(&w_blockhash_queue);
3581    }
3582
3583    // gating this under #[cfg(feature = "dev-context-only-utils")] isn't easy due to
3584    // solana-program-test's usage...
3585    pub fn register_unique_recent_blockhash_for_test(&self) {
3586        self.register_recent_blockhash(
3587            &Hash::new_unique(),
3588            &BankWithScheduler::no_scheduler_available(),
3589        )
3590    }
3591
3592    #[cfg(feature = "dev-context-only-utils")]
3593    pub fn register_recent_blockhash_for_test(
3594        &self,
3595        blockhash: &Hash,
3596        lamports_per_signature: Option<u64>,
3597    ) {
3598        // Only acquire the write lock for the blockhash queue on block boundaries because
3599        // readers can starve this write lock acquisition and ticks would be slowed down too
3600        // much if the write lock is acquired for each tick.
3601        let mut w_blockhash_queue = self.blockhash_queue.write().unwrap();
3602        if let Some(lamports_per_signature) = lamports_per_signature {
3603            w_blockhash_queue.register_hash(blockhash, lamports_per_signature);
3604        } else {
3605            w_blockhash_queue
3606                .register_hash(blockhash, self.fee_rate_governor.lamports_per_signature);
3607        }
3608    }
3609
3610    /// Tell the bank which Entry IDs exist on the ledger. This function assumes subsequent calls
3611    /// correspond to later entries, and will boot the oldest ones once its internal cache is full.
3612    /// Once boot, the bank will reject transactions using that `hash`.
3613    ///
3614    /// This is NOT thread safe because if tick height is updated by two different threads, the
3615    /// block boundary condition could be missed.
3616    pub fn register_tick(&self, hash: &Hash, scheduler: &InstalledSchedulerRwLock) {
3617        assert!(
3618            !self.freeze_started(),
3619            "register_tick() working on a bank that is already frozen or is undergoing freezing!"
3620        );
3621
3622        if self.is_block_boundary(self.tick_height.load(Relaxed) + 1) {
3623            self.register_recent_blockhash(hash, scheduler);
3624        }
3625
3626        // ReplayStage will start computing the accounts delta hash when it
3627        // detects the tick height has reached the boundary, so the system
3628        // needs to guarantee all account updates for the slot have been
3629        // committed before this tick height is incremented (like the blockhash
3630        // sysvar above)
3631        self.tick_height.fetch_add(1, Relaxed);
3632    }
3633
3634    #[cfg(feature = "dev-context-only-utils")]
3635    pub fn register_tick_for_test(&self, hash: &Hash) {
3636        self.register_tick(hash, &BankWithScheduler::no_scheduler_available())
3637    }
3638
3639    #[cfg(feature = "dev-context-only-utils")]
3640    pub fn register_default_tick_for_test(&self) {
3641        self.register_tick_for_test(&Hash::default())
3642    }
3643
3644    pub fn is_complete(&self) -> bool {
3645        self.tick_height() == self.max_tick_height()
3646    }
3647
3648    pub fn is_block_boundary(&self, tick_height: u64) -> bool {
3649        tick_height == self.max_tick_height
3650    }
3651
3652    /// Get the max number of accounts that a transaction may lock in this block
3653    pub fn get_transaction_account_lock_limit(&self) -> usize {
3654        if let Some(transaction_account_lock_limit) = self.transaction_account_lock_limit {
3655            transaction_account_lock_limit
3656        } else if self.feature_set.snapshot().increase_tx_account_lock_limit {
3657            MAX_TX_ACCOUNT_LOCKS
3658        } else {
3659            64
3660        }
3661    }
3662
3663    /// Prepare a transaction batch from a list of versioned transactions from
3664    /// an entry. Used for tests only.
3665    pub fn prepare_entry_batch(
3666        &self,
3667        txs: Vec<VersionedTransaction>,
3668    ) -> Result<TransactionBatch<'_, '_, RuntimeTransaction<SanitizedTransaction>>> {
3669        let sanitized_txs = txs
3670            .into_iter()
3671            .map(|tx| {
3672                RuntimeTransaction::try_create(
3673                    tx,
3674                    MessageHash::Compute,
3675                    None,
3676                    self,
3677                    self.get_reserved_account_keys(),
3678                )
3679            })
3680            .collect::<Result<Vec<_>>>()?;
3681        Ok(TransactionBatch::new(
3682            self.try_lock_accounts(&sanitized_txs),
3683            self,
3684            OwnedOrBorrowed::Owned(sanitized_txs),
3685        ))
3686    }
3687
3688    /// Attempt to take locks on the accounts in a transaction batch
3689    pub fn try_lock_accounts(&self, txs: &[impl TransactionWithMeta]) -> Vec<Result<()>> {
3690        self.try_lock_accounts_with_results(txs, txs.iter().map(|_| Ok(())))
3691    }
3692
3693    /// Attempt to take locks on the accounts in a transaction batch, and their cost
3694    /// limited packing status and duplicate transaction conflict status
3695    pub fn try_lock_accounts_with_results(
3696        &self,
3697        txs: &[impl TransactionWithMeta],
3698        tx_results: impl Iterator<Item = Result<()>>,
3699    ) -> Vec<Result<()>> {
3700        let tx_account_lock_limit = self.get_transaction_account_lock_limit();
3701
3702        // we must fail transactions that duplicate a prior message hash
3703        let mut batch_message_hashes = AHashSet::with_capacity(txs.len());
3704        let tx_results = tx_results
3705            .enumerate()
3706            .map(|(i, tx_result)| match tx_result {
3707                Ok(()) => {
3708                    // `HashSet::insert()` returns `true` when the value does *not* already exist
3709                    if batch_message_hashes.insert(txs[i].message_hash()) {
3710                        Ok(())
3711                    } else {
3712                        Err(TransactionError::AlreadyProcessed)
3713                    }
3714                }
3715                Err(e) => Err(e),
3716            });
3717
3718        self.rc
3719            .accounts
3720            .lock_accounts(txs.iter(), tx_results, tx_account_lock_limit)
3721    }
3722
3723    /// Prepare a locked transaction batch from a list of sanitized transactions.
3724    pub fn prepare_sanitized_batch<'a, 'b, Tx: TransactionWithMeta>(
3725        &'a self,
3726        txs: &'b [Tx],
3727    ) -> TransactionBatch<'a, 'b, Tx> {
3728        self.prepare_sanitized_batch_with_results(txs, txs.iter().map(|_| Ok(())))
3729    }
3730
3731    /// Prepare a locked transaction batch from a list of sanitized transactions, and their cost
3732    /// limited packing status
3733    pub fn prepare_sanitized_batch_with_results<'a, 'b, Tx: TransactionWithMeta>(
3734        &'a self,
3735        transactions: &'b [Tx],
3736        transaction_results: impl Iterator<Item = Result<()>>,
3737    ) -> TransactionBatch<'a, 'b, Tx> {
3738        // this lock_results could be: Ok, AccountInUse, WouldExceedBlockMaxLimit or WouldExceedAccountMaxLimit
3739        TransactionBatch::new(
3740            self.try_lock_accounts_with_results(transactions, transaction_results),
3741            self,
3742            OwnedOrBorrowed::Borrowed(transactions),
3743        )
3744    }
3745
3746    /// Prepare a transaction batch from a single transaction without locking accounts
3747    pub fn prepare_unlocked_batch_from_single_tx<'a, Tx: SVMMessage>(
3748        &'a self,
3749        transaction: &'a Tx,
3750    ) -> TransactionBatch<'a, 'a, Tx> {
3751        let tx_account_lock_limit = self.get_transaction_account_lock_limit();
3752        let lock_result = validate_account_locks(transaction.account_keys(), tx_account_lock_limit);
3753        let mut batch = TransactionBatch::new(
3754            vec![lock_result],
3755            self,
3756            OwnedOrBorrowed::Borrowed(slice::from_ref(transaction)),
3757        );
3758        batch.set_needs_unlock(false);
3759        batch
3760    }
3761
3762    /// Prepare a transaction batch from a single transaction after locking accounts
3763    pub fn prepare_locked_batch_from_single_tx<'a, Tx: TransactionWithMeta>(
3764        &'a self,
3765        transaction: &'a Tx,
3766    ) -> TransactionBatch<'a, 'a, Tx> {
3767        self.prepare_sanitized_batch(slice::from_ref(transaction))
3768    }
3769
3770    pub fn resanitize_transaction_minimally(
3771        &self,
3772        transaction: &impl TransactionWithMeta,
3773        sanitized_epoch: Epoch,
3774        alt_invalidation_slot: Slot,
3775    ) -> Result<()> {
3776        if self.vote_only_bank() && !vote_parser::is_valid_vote_only_transaction(transaction) {
3777            return Err(TransactionError::SanitizeFailure);
3778        }
3779
3780        // If the transaction was sanitized before this bank's epoch,
3781        // additional checks are necessary.
3782        if self.epoch() != sanitized_epoch {
3783            // Reserved key set may have changed, so we must verify that
3784            // no writable keys are reserved.
3785            self.check_reserved_keys(transaction)?;
3786
3787            for instr in transaction.instructions_iter() {
3788                if instr.accounts.len() > solana_transaction_context::MAX_ACCOUNTS_PER_INSTRUCTION {
3789                    return Err(solana_transaction_error::TransactionError::SanitizeFailure);
3790                }
3791            }
3792        }
3793
3794        if self.slot() > alt_invalidation_slot {
3795            // The address table lookup **may** have expired, but the
3796            // expiration is not guaranteed since there may have been
3797            // skipped slot.
3798            // If the addresses still resolve here, then the transaction is still
3799            // valid, and we can continue with processing.
3800            // If they do not, then the ATL has expired and the transaction
3801            // can be dropped.
3802            let (_addresses, _deactivation_slot) =
3803                self.load_addresses_from_ref(transaction.message_address_table_lookups())?;
3804        }
3805
3806        Ok(())
3807    }
3808
3809    /// Run transactions against a frozen bank without committing the results
3810    pub fn simulate_transaction(
3811        &self,
3812        transaction: &impl TransactionWithMeta,
3813        enable_cpi_recording: bool,
3814    ) -> TransactionSimulationResult {
3815        assert!(self.is_frozen(), "simulation bank must be frozen");
3816
3817        self.simulate_transaction_unchecked(transaction, enable_cpi_recording)
3818    }
3819
3820    /// Run transactions against a bank without committing the results; does not check if the bank
3821    /// is frozen, enabling use in single-Bank test frameworks
3822    pub fn simulate_transaction_unchecked(
3823        &self,
3824        transaction: &impl TransactionWithMeta,
3825        enable_cpi_recording: bool,
3826    ) -> TransactionSimulationResult {
3827        let account_keys = transaction.account_keys();
3828        let number_of_accounts = account_keys.len();
3829        let account_overrides = self.get_account_overrides_for_simulation(&account_keys);
3830        let batch = self.prepare_unlocked_batch_from_single_tx(transaction);
3831        let mut timings = ExecuteTimings::default();
3832
3833        let LoadAndExecuteTransactionsOutput {
3834            mut processing_results,
3835            balance_collector,
3836            ..
3837        } = self.load_and_execute_transactions(
3838            &batch,
3839            // After simulation, transactions will need to be forwarded to the leader
3840            // for processing. During forwarding, the transaction could expire if the
3841            // delay is not accounted for.
3842            self.max_processing_age()
3843                .saturating_sub(MAX_TRANSACTION_FORWARDING_DELAY),
3844            &mut timings,
3845            &mut TransactionErrorMetrics::default(),
3846            TransactionProcessingConfig {
3847                account_overrides: Some(&account_overrides),
3848                check_program_deployment_slot: self.check_program_deployment_slot,
3849                log_messages_bytes_limit: None,
3850                limit_to_load_programs: true,
3851                recording_config: ExecutionRecordingConfig {
3852                    enable_cpi_recording,
3853                    enable_log_recording: true,
3854                    enable_return_data_recording: true,
3855                    enable_transaction_balance_recording: true,
3856                },
3857                drop_on_failure: false,
3858                all_or_nothing: false,
3859                strict_nonce_size_check: true,
3860                drop_noop_transactions: true,
3861            },
3862        );
3863
3864        debug!("simulate_transaction: {timings:?}");
3865
3866        let processing_result = processing_results
3867            .pop()
3868            .unwrap_or(Err(TransactionError::InvalidProgramForExecution));
3869        let (
3870            post_simulation_accounts,
3871            result,
3872            fee,
3873            logs,
3874            return_data,
3875            inner_instructions,
3876            units_consumed,
3877            loaded_accounts_data_size,
3878        ) = match processing_result {
3879            Ok(processed_tx) => {
3880                let executed_units = processed_tx.executed_units();
3881                let loaded_accounts_data_size = processed_tx.loaded_accounts_data_size();
3882
3883                match processed_tx {
3884                    ProcessedTransaction::Executed(executed_tx) => {
3885                        let details = executed_tx.execution_details;
3886                        let post_simulation_accounts = executed_tx
3887                            .loaded_transaction
3888                            .accounts
3889                            .into_iter()
3890                            .take(number_of_accounts)
3891                            .collect::<Vec<_>>();
3892                        (
3893                            post_simulation_accounts,
3894                            details.status,
3895                            Some(executed_tx.loaded_transaction.fee_details.total_fee()),
3896                            details.log_messages,
3897                            details.return_data,
3898                            details.inner_instructions,
3899                            executed_units,
3900                            loaded_accounts_data_size,
3901                        )
3902                    }
3903                    ProcessedTransaction::FeesOnly(fees_only_tx) => (
3904                        vec![],
3905                        Err(fees_only_tx.load_error),
3906                        Some(fees_only_tx.fee_details.total_fee()),
3907                        None,
3908                        None,
3909                        None,
3910                        executed_units,
3911                        loaded_accounts_data_size,
3912                    ),
3913                    ProcessedTransaction::NoOp(no_op_tx) => (
3914                        vec![],
3915                        Err(no_op_tx.validation_error),
3916                        None,
3917                        None,
3918                        None,
3919                        None,
3920                        executed_units,
3921                        loaded_accounts_data_size,
3922                    ),
3923                }
3924            }
3925            Err(error) => (vec![], Err(error), None, None, None, None, 0, 0),
3926        };
3927        let logs = logs.unwrap_or_default();
3928
3929        let (pre_balances, post_balances, pre_token_balances, post_token_balances) =
3930            match balance_collector {
3931                Some(balance_collector) => {
3932                    let (mut native_pre, mut native_post, mut token_pre, mut token_post) =
3933                        balance_collector.into_vecs();
3934
3935                    (
3936                        native_pre.pop(),
3937                        native_post.pop(),
3938                        token_pre.pop(),
3939                        token_post.pop(),
3940                    )
3941                }
3942                None => (None, None, None, None),
3943            };
3944
3945        TransactionSimulationResult {
3946            result,
3947            logs,
3948            post_simulation_accounts,
3949            units_consumed,
3950            loaded_accounts_data_size,
3951            return_data,
3952            inner_instructions,
3953            fee,
3954            pre_balances,
3955            post_balances,
3956            pre_token_balances,
3957            post_token_balances,
3958        }
3959    }
3960
3961    fn get_account_overrides_for_simulation(&self, account_keys: &AccountKeys) -> AccountOverrides {
3962        let mut account_overrides = AccountOverrides::default();
3963        let slot_history_id = sysvar::slot_history::id();
3964        if account_keys.iter().any(|pubkey| *pubkey == slot_history_id) {
3965            let current_account = self.get_account_with_fixed_root(&slot_history_id);
3966            let slot_history = current_account
3967                .as_ref()
3968                .map(|account| wincode::deserialize::<SlotHistory>(account.data()).unwrap())
3969                .unwrap_or_default();
3970            if slot_history.check(self.slot()) == Check::Found {
3971                let ancestors = Ancestors::from(self.proper_ancestors().collect::<Vec<_>>());
3972                if let Some((account, _)) =
3973                    self.load_slow_with_fixed_root(&ancestors, &slot_history_id)
3974                {
3975                    account_overrides.set_slot_history(Some(account));
3976                }
3977            }
3978        }
3979        account_overrides
3980    }
3981
3982    pub fn unlock_accounts<'a, Tx: SVMMessage + 'a>(
3983        &self,
3984        txs_and_results: impl Iterator<Item = (&'a Tx, &'a Result<()>)> + Clone,
3985    ) {
3986        self.rc.accounts.unlock_accounts(txs_and_results)
3987    }
3988
3989    pub fn remove_unrooted_slots(&self, slots: &[(Slot, BankId)]) {
3990        self.rc.accounts.accounts_db.remove_unrooted_slots(slots)
3991    }
3992
3993    pub fn get_hash_age(&self, hash: &Hash) -> Option<u64> {
3994        self.blockhash_queue.read().unwrap().get_hash_age(hash)
3995    }
3996
3997    pub fn is_hash_valid_for_age(&self, hash: &Hash, max_age: usize) -> bool {
3998        self.blockhash_queue
3999            .read()
4000            .unwrap()
4001            .is_hash_valid_for_age(hash, max_age)
4002    }
4003
4004    pub fn collect_balances(
4005        &self,
4006        batch: &TransactionBatch<impl SVMMessage>,
4007    ) -> TransactionBalances {
4008        let mut balances: TransactionBalances = vec![];
4009        for transaction in batch.sanitized_transactions() {
4010            let mut transaction_balances: Vec<u64> = vec![];
4011            for account_key in transaction.account_keys().iter() {
4012                transaction_balances.push(self.get_balance(account_key));
4013            }
4014            balances.push(transaction_balances);
4015        }
4016        balances
4017    }
4018
4019    pub fn load_and_execute_transactions(
4020        &self,
4021        batch: &TransactionBatch<impl TransactionWithMeta>,
4022        max_age: usize,
4023        timings: &mut ExecuteTimings,
4024        error_counters: &mut TransactionErrorMetrics,
4025        processing_config: TransactionProcessingConfig,
4026    ) -> LoadAndExecuteTransactionsOutput {
4027        let sanitized_txs = batch.sanitized_transactions();
4028
4029        let (check_results, check_us) = measure_us!(self.check_transactions(
4030            sanitized_txs,
4031            batch.lock_results(),
4032            max_age,
4033            processing_config.strict_nonce_size_check,
4034            error_counters,
4035        ));
4036        timings.saturating_add_in_place(ExecuteTimingType::CheckUs, check_us);
4037
4038        let (blockhash, blockhash_lamports_per_signature) =
4039            self.last_blockhash_and_lamports_per_signature();
4040        let effective_epoch_of_deployments =
4041            self.epoch_schedule().get_epoch(self.slot.saturating_add(
4042                solana_program_runtime::program_cache_entry::DELAY_VISIBILITY_SLOT_OFFSET,
4043            ));
4044        let processing_environment = TransactionProcessingEnvironment {
4045            blockhash,
4046            blockhash_lamports_per_signature,
4047            alpenglow_migration_succeeded: self.is_alpenglow(),
4048            epoch_total_stake: self.get_current_epoch_total_stake(),
4049            feature_set: self.feature_set.runtime_features(),
4050            program_runtime_environments: ProgramRuntimeEnvironments::new(
4051                self.transaction_processor
4052                    .program_runtime_environment
4053                    .clone(),
4054                self.transaction_processor
4055                    .program_runtime_environment_for_epoch(effective_epoch_of_deployments),
4056            ),
4057            rent: self.rent_collector.rent.clone(),
4058        };
4059
4060        let sanitized_output = self
4061            .transaction_processor
4062            .load_and_execute_sanitized_transactions(
4063                self,
4064                sanitized_txs,
4065                check_results,
4066                &processing_environment,
4067                &processing_config,
4068            );
4069
4070        // Accumulate the errors returned by the batch processor.
4071        error_counters.accumulate(&sanitized_output.error_metrics);
4072
4073        // Accumulate the transaction batch execution timings.
4074        timings.accumulate(&sanitized_output.execute_timings);
4075
4076        let ((), collect_logs_us) =
4077            measure_us!(self.collect_logs(sanitized_txs, &sanitized_output.processing_results));
4078        timings.saturating_add_in_place(ExecuteTimingType::CollectLogsUs, collect_logs_us);
4079
4080        let mut processed_counts = ProcessedTransactionCounts::default();
4081        let err_count = &mut error_counters.total;
4082
4083        for (processing_result, tx) in sanitized_output
4084            .processing_results
4085            .iter()
4086            .zip(sanitized_txs)
4087        {
4088            if let Some(debug_keys) = &self.transaction_debug_keys {
4089                for key in tx.account_keys().iter() {
4090                    if debug_keys.contains(key) {
4091                        let result = processing_result.flattened_result();
4092                        info!("slot: {} result: {:?} tx: {:?}", self.slot, result, tx);
4093                        break;
4094                    }
4095                }
4096            }
4097
4098            if processing_result.was_processed() {
4099                // Signature count must be accumulated only if the transaction
4100                // is processed, otherwise a mismatched count between banking
4101                // and replay could occur
4102                processed_counts.signature_count +=
4103                    tx.signature_details().num_transaction_signatures();
4104                processed_counts.processed_transactions_count += 1;
4105
4106                if !tx.is_simple_vote_transaction() {
4107                    processed_counts.processed_non_vote_transactions_count += 1;
4108                }
4109            }
4110
4111            match processing_result.flattened_result() {
4112                Ok(()) => {
4113                    processed_counts.processed_with_successful_result_count += 1;
4114                }
4115                Err(err) => {
4116                    if err_count.0 == 0 {
4117                        debug!("tx error: {err:?} {tx:?}");
4118                    }
4119                    *err_count += 1;
4120                }
4121            }
4122        }
4123
4124        LoadAndExecuteTransactionsOutput {
4125            processing_results: sanitized_output.processing_results,
4126            processed_counts,
4127            balance_collector: sanitized_output.balance_collector,
4128        }
4129    }
4130
4131    fn collect_logs(
4132        &self,
4133        transactions: &[impl TransactionWithMeta],
4134        processing_results: &[TransactionProcessingResult],
4135    ) {
4136        let transaction_log_collector_config =
4137            self.transaction_log_collector_config.read().unwrap();
4138        if transaction_log_collector_config.filter == TransactionLogCollectorFilter::None {
4139            return;
4140        }
4141
4142        let collected_logs: Vec<_> = processing_results
4143            .iter()
4144            .zip(transactions)
4145            .filter_map(|(processing_result, transaction)| {
4146                // Skip log collection for unprocessed transactions
4147                let processed_tx = processing_result.processed_transaction()?;
4148                // Skip log collection for unexecuted transactions
4149                let execution_details = processed_tx.execution_details()?;
4150                Self::collect_transaction_logs(
4151                    &transaction_log_collector_config,
4152                    transaction,
4153                    execution_details,
4154                )
4155            })
4156            .collect();
4157
4158        if !collected_logs.is_empty() {
4159            let mut transaction_log_collector = self.transaction_log_collector.write().unwrap();
4160            for (log, filtered_mentioned_addresses) in collected_logs {
4161                let transaction_log_index = transaction_log_collector.logs.len();
4162                transaction_log_collector.logs.push(log);
4163                for key in filtered_mentioned_addresses.into_iter() {
4164                    transaction_log_collector
4165                        .mentioned_address_map
4166                        .entry(key)
4167                        .or_default()
4168                        .push(transaction_log_index);
4169                }
4170            }
4171        }
4172    }
4173
4174    fn collect_transaction_logs(
4175        transaction_log_collector_config: &TransactionLogCollectorConfig,
4176        transaction: &impl TransactionWithMeta,
4177        execution_details: &TransactionExecutionDetails,
4178    ) -> Option<(TransactionLogInfo, Vec<Pubkey>)> {
4179        // Skip log collection if no log messages were recorded
4180        let log_messages = execution_details.log_messages.as_ref()?;
4181
4182        let mut filtered_mentioned_addresses = Vec::new();
4183        if !transaction_log_collector_config
4184            .mentioned_addresses
4185            .is_empty()
4186        {
4187            for key in transaction.account_keys().iter() {
4188                if transaction_log_collector_config
4189                    .mentioned_addresses
4190                    .contains(key)
4191                {
4192                    filtered_mentioned_addresses.push(*key);
4193                }
4194            }
4195        }
4196
4197        let is_vote = transaction.is_simple_vote_transaction();
4198        let store = match transaction_log_collector_config.filter {
4199            TransactionLogCollectorFilter::All => {
4200                !is_vote || !filtered_mentioned_addresses.is_empty()
4201            }
4202            TransactionLogCollectorFilter::AllWithVotes => true,
4203            TransactionLogCollectorFilter::None => false,
4204            TransactionLogCollectorFilter::OnlyMentionedAddresses => {
4205                !filtered_mentioned_addresses.is_empty()
4206            }
4207        };
4208
4209        if store {
4210            Some((
4211                TransactionLogInfo {
4212                    signature: *transaction.signature(),
4213                    result: execution_details.status.clone(),
4214                    is_vote,
4215                    log_messages: log_messages.clone(),
4216                },
4217                filtered_mentioned_addresses,
4218            ))
4219        } else {
4220            None
4221        }
4222    }
4223
4224    /// Load the accounts data size, in bytes
4225    pub fn load_accounts_data_size(&self) -> u64 {
4226        self.accounts_data_size_initial
4227            .saturating_add_signed(self.load_accounts_data_size_delta())
4228    }
4229
4230    /// Load the change in accounts data size in this Bank, in bytes
4231    pub fn load_accounts_data_size_delta(&self) -> i64 {
4232        let delta_on_chain = self.load_accounts_data_size_delta_on_chain();
4233        let delta_off_chain = self.load_accounts_data_size_delta_off_chain();
4234        delta_on_chain.saturating_add(delta_off_chain)
4235    }
4236
4237    /// Load the change in accounts data size in this Bank, in bytes, from on-chain events
4238    /// i.e. transactions
4239    pub fn load_accounts_data_size_delta_on_chain(&self) -> i64 {
4240        self.accounts_data_size_delta_on_chain.load(Acquire)
4241    }
4242
4243    /// Load the change in accounts data size in this Bank, in bytes, from off-chain events
4244    /// i.e. rent collection
4245    pub fn load_accounts_data_size_delta_off_chain(&self) -> i64 {
4246        self.accounts_data_size_delta_off_chain.load(Acquire)
4247    }
4248
4249    /// Update the accounts data size delta from on-chain events by adding `amount`.
4250    /// The arithmetic saturates.
4251    fn update_accounts_data_size_delta_on_chain(&self, amount: i64) {
4252        if amount == 0 {
4253            return;
4254        }
4255
4256        self.accounts_data_size_delta_on_chain
4257            .fetch_update(AcqRel, Acquire, |accounts_data_size_delta_on_chain| {
4258                Some(accounts_data_size_delta_on_chain.saturating_add(amount))
4259            })
4260            // SAFETY: unwrap() is safe since our update fn always returns `Some`
4261            .unwrap();
4262    }
4263
4264    /// Update the accounts data size delta from off-chain events by adding `amount`.
4265    /// The arithmetic saturates.
4266    fn update_accounts_data_size_delta_off_chain(&self, amount: i64) {
4267        if amount == 0 {
4268            return;
4269        }
4270
4271        self.accounts_data_size_delta_off_chain
4272            .fetch_update(AcqRel, Acquire, |accounts_data_size_delta_off_chain| {
4273                Some(accounts_data_size_delta_off_chain.saturating_add(amount))
4274            })
4275            // SAFETY: unwrap() is safe since our update fn always returns `Some`
4276            .unwrap();
4277    }
4278
4279    /// Calculate the data size delta and update the off-chain accounts data size delta
4280    fn calculate_and_update_accounts_data_size_delta_off_chain(
4281        &self,
4282        old_data_size: usize,
4283        new_data_size: usize,
4284    ) {
4285        let data_size_delta = calculate_data_size_delta(old_data_size, new_data_size);
4286        self.update_accounts_data_size_delta_off_chain(data_size_delta);
4287    }
4288
4289    fn filter_program_errors_and_collect_fee_details(
4290        &self,
4291        processing_results: &[TransactionProcessingResult],
4292    ) {
4293        let mut accumulated_fee_details = FeeDetails::default();
4294
4295        processing_results.iter().for_each(|processing_result| {
4296            if let Ok(processed_tx) = processing_result {
4297                accumulated_fee_details.accumulate(&processed_tx.fee_details());
4298            }
4299        });
4300
4301        self.collector_fee_details
4302            .write()
4303            .unwrap()
4304            .accumulate(&accumulated_fee_details);
4305    }
4306
4307    fn update_bank_hash_stats<'a>(&self, accounts: &impl StorableAccounts<'a>) {
4308        let mut stats = BankHashStats::default();
4309        (0..accounts.len()).for_each(|i| {
4310            accounts.account(i, |account| {
4311                stats.update(&account);
4312            })
4313        });
4314        self.bank_hash_stats.accumulate(&stats);
4315    }
4316
4317    pub fn commit_transactions(
4318        &self,
4319        sanitized_txs: &[impl TransactionWithMeta],
4320        processing_results: Vec<TransactionProcessingResult>,
4321        processed_counts: &ProcessedTransactionCounts,
4322        timings: &mut ExecuteTimings,
4323    ) -> Vec<TransactionCommitResult> {
4324        assert!(
4325            !self.freeze_started(),
4326            "commit_transactions() working on a bank that is already frozen or is undergoing \
4327             freezing!"
4328        );
4329
4330        let ProcessedTransactionCounts {
4331            processed_transactions_count,
4332            processed_non_vote_transactions_count,
4333            processed_with_successful_result_count,
4334            signature_count,
4335        } = *processed_counts;
4336
4337        self.increment_transaction_count(processed_transactions_count);
4338        self.increment_non_vote_transaction_count_since_restart(
4339            processed_non_vote_transactions_count,
4340        );
4341        self.increment_signature_count(signature_count);
4342
4343        let processed_with_failure_result_count =
4344            processed_transactions_count.saturating_sub(processed_with_successful_result_count);
4345        self.transaction_error_count
4346            .fetch_add(processed_with_failure_result_count, Relaxed);
4347
4348        if processed_transactions_count > 0 {
4349            self.is_delta.store(true, Relaxed);
4350            self.transaction_entries_count.fetch_add(1, Relaxed);
4351            self.transactions_per_entry_max
4352                .fetch_max(processed_transactions_count, Relaxed);
4353        }
4354
4355        let ((), store_accounts_us) = measure_us!({
4356            // If geyser is present, we must collect `SanitizedTransaction`
4357            // references in order to comply with that interface - until it
4358            // is changed.
4359            let maybe_transaction_refs = self
4360                .accounts()
4361                .accounts_db
4362                .has_accounts_update_notifier()
4363                .then(|| {
4364                    sanitized_txs
4365                        .iter()
4366                        .map(|tx| tx.as_sanitized_transaction())
4367                        .collect::<Vec<_>>()
4368                });
4369
4370            let (accounts_to_store, transactions) = collect_accounts_to_store(
4371                sanitized_txs,
4372                &maybe_transaction_refs,
4373                &processing_results,
4374            );
4375
4376            let to_store = (self.slot(), accounts_to_store.as_slice());
4377            self.update_bank_hash_stats(&to_store);
4378            self.enqueue_on_chain_accounts_lt_hash_updates(&to_store);
4379            // See https://github.com/solana-labs/solana/pull/31455 for discussion
4380            // on *not* updating the index within a threadpool.
4381            self.rc.accounts.store_accounts_seq(
4382                to_store,
4383                self.bank_id(),
4384                transactions.as_deref(),
4385                &self.ancestors,
4386            );
4387        });
4388
4389        // Cached vote and stake accounts are synchronized with accounts-db
4390        // after each transaction.
4391        let ((), update_stakes_cache_us) =
4392            measure_us!(self.update_stakes_cache(sanitized_txs, &processing_results));
4393
4394        let ((), update_executors_us) = measure_us!({
4395            let mut cache = None;
4396            for processing_result in &processing_results {
4397                if let Some(ProcessedTransaction::Executed(executed_tx)) =
4398                    processing_result.processed_transaction()
4399                {
4400                    let programs_modified_by_tx = &executed_tx.programs_modified_by_tx;
4401                    if executed_tx.was_successful() && !programs_modified_by_tx.is_empty() {
4402                        cache
4403                            .get_or_insert_with(|| {
4404                                self.transaction_processor
4405                                    .global_program_cache
4406                                    .write()
4407                                    .unwrap()
4408                            })
4409                            .merge(
4410                                &self.transaction_processor.program_runtime_environment,
4411                                self.slot,
4412                                programs_modified_by_tx,
4413                            );
4414                    }
4415                }
4416            }
4417        });
4418
4419        let accounts_data_len_delta = processing_results
4420            .iter()
4421            .filter_map(|processing_result| processing_result.processed_transaction())
4422            .filter_map(|processed_tx| processed_tx.execution_details())
4423            .filter_map(|details| details.accounts_deltas.as_ref())
4424            .map(|deltas| {
4425                deltas
4426                    .accounts_resize_delta
4427                    .saturating_sub_unsigned(deltas.accounts_uninitialized_size)
4428            })
4429            .sum();
4430        self.update_accounts_data_size_delta_on_chain(accounts_data_len_delta);
4431
4432        let ((), update_transaction_statuses_us) =
4433            measure_us!(self.update_transaction_statuses(sanitized_txs, &processing_results));
4434
4435        self.filter_program_errors_and_collect_fee_details(&processing_results);
4436
4437        timings.saturating_add_in_place(ExecuteTimingType::StoreUs, store_accounts_us);
4438        timings.saturating_add_in_place(
4439            ExecuteTimingType::UpdateStakesCacheUs,
4440            update_stakes_cache_us,
4441        );
4442        timings.saturating_add_in_place(ExecuteTimingType::UpdateExecutorsUs, update_executors_us);
4443        timings.saturating_add_in_place(
4444            ExecuteTimingType::UpdateTransactionStatuses,
4445            update_transaction_statuses_us,
4446        );
4447
4448        Self::create_commit_results(processing_results)
4449    }
4450
4451    fn create_commit_results(
4452        processing_results: Vec<TransactionProcessingResult>,
4453    ) -> Vec<TransactionCommitResult> {
4454        processing_results
4455            .into_iter()
4456            .map(|processing_result| {
4457                let processing_result = processing_result?;
4458                let executed_units = processing_result.executed_units();
4459                let loaded_accounts_data_size = processing_result.loaded_accounts_data_size();
4460
4461                match processing_result {
4462                    ProcessedTransaction::Executed(executed_tx) => {
4463                        let successful = executed_tx.was_successful();
4464                        let execution_details = executed_tx.execution_details;
4465                        let LoadedTransaction {
4466                            accounts: loaded_accounts,
4467                            fee_details,
4468                            rollback_accounts,
4469                            ..
4470                        } = executed_tx.loaded_transaction;
4471
4472                        // Rollback value is used for failure.
4473                        let fee_payer_post_balance = if successful {
4474                            loaded_accounts[0].1.lamports()
4475                        } else {
4476                            rollback_accounts.fee_payer().1.lamports()
4477                        };
4478
4479                        Ok(CommittedTransaction {
4480                            status: execution_details.status,
4481                            log_messages: execution_details.log_messages,
4482                            inner_instructions: execution_details.inner_instructions,
4483                            return_data: execution_details.return_data,
4484                            executed_units,
4485                            fee_details,
4486                            loaded_account_stats: TransactionLoadedAccountsStats {
4487                                loaded_accounts_count: loaded_accounts.len(),
4488                                loaded_accounts_data_size,
4489                            },
4490                            fee_payer_post_balance,
4491                        })
4492                    }
4493                    ProcessedTransaction::FeesOnly(fees_only_tx) => Ok(CommittedTransaction {
4494                        status: Err(fees_only_tx.load_error),
4495                        log_messages: None,
4496                        inner_instructions: None,
4497                        return_data: None,
4498                        executed_units,
4499                        fee_details: fees_only_tx.fee_details,
4500                        loaded_account_stats: TransactionLoadedAccountsStats {
4501                            loaded_accounts_count: fees_only_tx.rollback_accounts.count(),
4502                            loaded_accounts_data_size,
4503                        },
4504                        fee_payer_post_balance: fees_only_tx
4505                            .rollback_accounts
4506                            .fee_payer()
4507                            .1
4508                            .lamports(),
4509                    }),
4510                    ProcessedTransaction::NoOp(no_op_tx) => Ok(CommittedTransaction {
4511                        status: Err(no_op_tx.validation_error),
4512                        log_messages: None,
4513                        inner_instructions: None,
4514                        return_data: None,
4515                        executed_units,
4516                        fee_details: FeeDetails::default(),
4517                        loaded_account_stats: TransactionLoadedAccountsStats {
4518                            loaded_accounts_count: 0,
4519                            loaded_accounts_data_size,
4520                        },
4521                        fee_payer_post_balance: no_op_tx.fee_payer_balance.unwrap_or(0),
4522                    }),
4523                }
4524            })
4525            .collect()
4526    }
4527
4528    fn run_incinerator(&self) {
4529        if let Some((account, _)) =
4530            self.get_account_modified_since_parent_with_fixed_root(&incinerator::id())
4531        {
4532            self.capitalization.fetch_sub(account.lamports(), Relaxed);
4533            self.store_account(&incinerator::id(), &AccountSharedData::default());
4534        }
4535    }
4536
4537    /// Returns the accounts, sorted by pubkey, that were part of accounts lt hash calculation
4538    /// This is used when writing a bank hash details file.
4539    pub(crate) fn get_accounts_for_bank_hash_details(&self) -> Vec<(Pubkey, AccountSharedData)> {
4540        let mut accounts = self
4541            .rc
4542            .accounts
4543            .accounts_db
4544            .get_pubkey_account_for_slot(self.slot());
4545        // Sort the accounts by pubkey to make diff deterministic.
4546        accounts.sort_unstable_by_key(|a| a.0);
4547        accounts
4548    }
4549
4550    pub fn cluster_type(&self) -> ClusterType {
4551        // unwrap is safe; self.cluster_type is ensured to be Some() always...
4552        // we only using Option here for ABI compatibility...
4553        self.cluster_type.unwrap()
4554    }
4555
4556    /// Process a batch of transactions.
4557    #[must_use]
4558    pub fn load_execute_and_commit_transactions(
4559        &self,
4560        batch: &TransactionBatch<impl TransactionWithMeta>,
4561        recording_config: ExecutionRecordingConfig,
4562        timings: &mut ExecuteTimings,
4563        log_messages_bytes_limit: Option<usize>,
4564    ) -> (Vec<TransactionCommitResult>, Option<BalanceCollector>) {
4565        self.do_load_execute_and_commit_transactions_with_pre_commit_callback(
4566            batch,
4567            recording_config,
4568            timings,
4569            log_messages_bytes_limit,
4570            None::<fn(&_) -> _>,
4571        )
4572        .unwrap()
4573    }
4574
4575    pub fn load_execute_and_commit_transactions_with_pre_commit_callback(
4576        &self,
4577        batch: &TransactionBatch<impl TransactionWithMeta>,
4578        recording_config: ExecutionRecordingConfig,
4579        timings: &mut ExecuteTimings,
4580        log_messages_bytes_limit: Option<usize>,
4581        pre_commit_callback: impl FnOnce(&[TransactionProcessingResult]) -> Result<()>,
4582    ) -> Result<(Vec<TransactionCommitResult>, Option<BalanceCollector>)> {
4583        self.do_load_execute_and_commit_transactions_with_pre_commit_callback(
4584            batch,
4585            recording_config,
4586            timings,
4587            log_messages_bytes_limit,
4588            Some(pre_commit_callback),
4589        )
4590    }
4591
4592    fn do_load_execute_and_commit_transactions_with_pre_commit_callback(
4593        &self,
4594        batch: &TransactionBatch<impl TransactionWithMeta>,
4595        recording_config: ExecutionRecordingConfig,
4596        timings: &mut ExecuteTimings,
4597        log_messages_bytes_limit: Option<usize>,
4598        pre_commit_callback: Option<impl FnOnce(&[TransactionProcessingResult]) -> Result<()>>,
4599    ) -> Result<(Vec<TransactionCommitResult>, Option<BalanceCollector>)> {
4600        let LoadAndExecuteTransactionsOutput {
4601            processing_results,
4602            processed_counts,
4603            balance_collector,
4604        } = self.load_and_execute_transactions(
4605            batch,
4606            self.max_processing_age(),
4607            timings,
4608            &mut TransactionErrorMetrics::default(),
4609            TransactionProcessingConfig {
4610                account_overrides: None,
4611                check_program_deployment_slot: self.check_program_deployment_slot,
4612                log_messages_bytes_limit,
4613                limit_to_load_programs: false,
4614                recording_config,
4615                drop_on_failure: false,
4616                all_or_nothing: false,
4617                strict_nonce_size_check: false,
4618                drop_noop_transactions: false,
4619            },
4620        );
4621
4622        if let Some(pre_commit_callback) = pre_commit_callback {
4623            let () = pre_commit_callback(&processing_results)?;
4624        }
4625
4626        let commit_results = self.commit_transactions(
4627            batch.sanitized_transactions(),
4628            processing_results,
4629            &processed_counts,
4630            timings,
4631        );
4632        Ok((commit_results, balance_collector))
4633    }
4634
4635    /// Process a Transaction. This is used for unit tests and simply calls the vector
4636    /// Bank::process_transactions method.
4637    pub fn process_transaction(&self, tx: &Transaction) -> Result<()> {
4638        self.try_process_transactions(std::iter::once(tx))?[0].clone()
4639    }
4640
4641    /// Process a Transaction and store metadata. This is used for tests and the banks services. It
4642    /// replicates the vector Bank::process_transaction method with metadata recording enabled.
4643    pub fn process_transaction_with_metadata(
4644        &self,
4645        tx: impl Into<VersionedTransaction>,
4646    ) -> Result<CommittedTransaction> {
4647        let txs = vec![tx.into()];
4648        let batch = self.prepare_entry_batch(txs)?;
4649
4650        let (mut commit_results, ..) = self.load_execute_and_commit_transactions(
4651            &batch,
4652            ExecutionRecordingConfig {
4653                enable_cpi_recording: false,
4654                enable_log_recording: true,
4655                enable_return_data_recording: true,
4656                enable_transaction_balance_recording: false,
4657            },
4658            &mut ExecuteTimings::default(),
4659            Some(1000 * 1000),
4660        );
4661
4662        commit_results.remove(0)
4663    }
4664
4665    /// Process multiple transaction in a single batch. This is used for benches and unit tests.
4666    /// Short circuits if any of the transactions do not pass sanitization checks.
4667    pub fn try_process_transactions<'a>(
4668        &self,
4669        txs: impl Iterator<Item = &'a Transaction>,
4670    ) -> Result<Vec<Result<()>>> {
4671        let txs = txs
4672            .map(|tx| VersionedTransaction::from(tx.clone()))
4673            .collect();
4674        self.try_process_entry_transactions(txs)
4675    }
4676
4677    /// Process multiple transaction in a single batch. This is used for benches and unit tests.
4678    /// Short circuits if any of the transactions do not pass sanitization checks.
4679    pub fn try_process_entry_transactions(
4680        &self,
4681        txs: Vec<VersionedTransaction>,
4682    ) -> Result<Vec<Result<()>>> {
4683        let batch = self.prepare_entry_batch(txs)?;
4684        Ok(self.process_transaction_batch(&batch))
4685    }
4686
4687    #[must_use]
4688    fn process_transaction_batch(
4689        &self,
4690        batch: &TransactionBatch<impl TransactionWithMeta>,
4691    ) -> Vec<Result<()>> {
4692        self.load_execute_and_commit_transactions(
4693            batch,
4694            ExecutionRecordingConfig::new_single_setting(false),
4695            &mut ExecuteTimings::default(),
4696            None,
4697        )
4698        .0
4699        .into_iter()
4700        .map(|commit_result| commit_result.and_then(|committed_tx| committed_tx.status))
4701        .collect()
4702    }
4703
4704    /// Create, sign, and process a Transaction from `keypair` to `to` of
4705    /// `n` lamports where `blockhash` is the last Entry ID observed by the client.
4706    pub fn transfer(&self, n: u64, keypair: &Keypair, to: &Pubkey) -> Result<Signature> {
4707        let blockhash = self.last_blockhash();
4708        let tx = system_transaction::transfer(keypair, to, n, blockhash);
4709        let signature = tx.signatures[0];
4710        self.process_transaction(&tx).map(|_| signature)
4711    }
4712
4713    pub fn read_balance(account: &AccountSharedData) -> u64 {
4714        account.lamports()
4715    }
4716    /// Each program would need to be able to introspect its own state
4717    /// this is hard-coded to the Budget language
4718    pub fn get_balance(&self, pubkey: &Pubkey) -> u64 {
4719        self.get_account(pubkey)
4720            .map(|x| Self::read_balance(&x))
4721            .unwrap_or(0)
4722    }
4723
4724    /// Compute all the parents of the bank in order
4725    pub fn parents(&self) -> Vec<Arc<Bank>> {
4726        self.parents_iter().collect()
4727    }
4728
4729    pub(crate) fn parents_iter(&self) -> impl Iterator<Item = Arc<Bank>> + '_ {
4730        let mut bank = self.parent();
4731        core::iter::from_fn(move || {
4732            let parent = bank.take()?;
4733            bank = parent.parent();
4734            Some(parent)
4735        })
4736    }
4737
4738    /// Compute all the parents of the bank including this bank itself
4739    pub fn parents_inclusive(self: Arc<Self>) -> Vec<Arc<Bank>> {
4740        let mut parents = Vec::with_capacity(self.ancestors.len());
4741        parents.push(Arc::clone(&self));
4742        parents.extend(self.parents_iter());
4743        parents
4744    }
4745
4746    /// fn store the single `account` with `pubkey`.
4747    /// Uses `store_accounts`, which works on a vector of accounts.
4748    pub fn store_account(&self, pubkey: &Pubkey, account: &AccountSharedData) {
4749        self.store_accounts((self.slot(), &[(pubkey, account)][..]), None)
4750    }
4751
4752    // Store `accounts`.
4753    //
4754    // - Callers must ensure there are no duplicates in `accounts`.
4755    // - `thread_pool_for_loading_accounts` is used for accounts lt hashing,
4756    //   to load the previous version of accounts in parallel.
4757    pub fn store_accounts<'a>(
4758        &self,
4759        accounts: impl StorableAccounts<'a>,
4760        thread_pool_for_loading_accounts: Option<&ThreadPool>,
4761    ) {
4762        assert!(!self.freeze_started());
4763        let mut m = Measure::start("stakes_cache.check_and_store");
4764        let new_warmup_cooldown_rate_epoch = self.new_warmup_cooldown_rate_epoch();
4765        let use_fixed_point_stake_math = self.use_fixed_point_stake_math();
4766
4767        (0..accounts.len()).for_each(|i| {
4768            accounts.account(i, |account| {
4769                self.stakes_cache.check_and_store(
4770                    account.pubkey(),
4771                    &account,
4772                    new_warmup_cooldown_rate_epoch,
4773                    use_fixed_point_stake_math,
4774                )
4775            })
4776        });
4777        self.store_accounts_without_stakes_cache(accounts, thread_pool_for_loading_accounts);
4778        m.stop();
4779        self.rc
4780            .accounts
4781            .accounts_db
4782            .stats
4783            .stakes_cache_check_and_store_us
4784            .fetch_add(m.as_us(), Relaxed);
4785    }
4786
4787    fn store_account_without_stakes_cache(&self, pubkey: &Pubkey, account: &AccountSharedData) {
4788        self.store_accounts_without_stakes_cache((self.slot(), &[(pubkey, account)][..]), None)
4789    }
4790
4791    // Store `accounts`, without updating the stakes cache.
4792    //
4793    // - Callers must ensure there are no duplicates in `accounts`.
4794    // - `thread_pool_for_loading_accounts` is used for accounts lt hashing,
4795    //   to load the previous version of accounts in parallel.
4796    fn store_accounts_without_stakes_cache<'a>(
4797        &self,
4798        accounts: impl StorableAccounts<'a>,
4799        thread_pool_for_loading_accounts: Option<&ThreadPool>,
4800    ) {
4801        assert!(!self.freeze_started());
4802        self.update_bank_hash_stats(&accounts);
4803        self.enqueue_off_chain_accounts_lt_hash_updates(
4804            &accounts,
4805            thread_pool_for_loading_accounts,
4806        );
4807        self.rc
4808            .accounts
4809            .store_accounts_par(accounts, self.bank_id(), None, &self.ancestors);
4810    }
4811
4812    pub fn force_flush_accounts_cache(&self) {
4813        self.rc
4814            .accounts
4815            .accounts_db
4816            .flush_accounts_cache(true, Some(self.slot()))
4817    }
4818
4819    /// Technically this issues (or even burns!) new lamports,
4820    /// so be extra careful for its usage
4821    pub(crate) fn store_account_and_update_capitalization(
4822        &self,
4823        pubkey: &Pubkey,
4824        new_account: &AccountSharedData,
4825    ) {
4826        let old_account_data_size = if let Some(old_account) =
4827            self.get_account_with_fixed_root_no_cache(pubkey)
4828        {
4829            match new_account.lamports().cmp(&old_account.lamports()) {
4830                std::cmp::Ordering::Greater => {
4831                    let diff = new_account.lamports() - old_account.lamports();
4832                    trace!("store_account_and_update_capitalization: increased: {pubkey} {diff}");
4833                    self.capitalization.fetch_add(diff, Relaxed);
4834                }
4835                std::cmp::Ordering::Less => {
4836                    let diff = old_account.lamports() - new_account.lamports();
4837                    trace!("store_account_and_update_capitalization: decreased: {pubkey} {diff}");
4838                    self.capitalization.fetch_sub(diff, Relaxed);
4839                }
4840                std::cmp::Ordering::Equal => {}
4841            }
4842            old_account.data().len()
4843        } else {
4844            trace!(
4845                "store_account_and_update_capitalization: created: {pubkey} {}",
4846                new_account.lamports()
4847            );
4848            self.capitalization
4849                .fetch_add(new_account.lamports(), Relaxed);
4850            0
4851        };
4852
4853        self.store_account(pubkey, new_account);
4854
4855        // If the new account has zero lamports, that means it is being closed.
4856        let new_account_data_size = if new_account.lamports() == 0 {
4857            0
4858        } else {
4859            new_account.data().len()
4860        };
4861        self.calculate_and_update_accounts_data_size_delta_off_chain(
4862            old_account_data_size,
4863            new_account_data_size,
4864        );
4865    }
4866
4867    pub fn accounts(&self) -> Arc<Accounts> {
4868        self.rc.accounts.clone()
4869    }
4870
4871    /// Recomputes cost tracker limits from active feature state.
4872    fn apply_cost_tracker_limits_for_active_features(&mut self) {
4873        let params = self.current_slot_params();
4874        let cost_limits =
4875            params.cost_limits(self.feature_set.snapshot().raise_block_limits_to_100m);
4876
4877        let mut cost_tracker = self.write_cost_tracker().unwrap();
4878        cost_tracker.set_limits(cost_limits);
4879    }
4880
4881    /// Recomputes this bank's effective partitioned-reward write budget.
4882    fn apply_partitioned_epoch_rewards_config_for_active_features(&mut self) {
4883        self.partitioned_rewards_stake_account_stores_per_block = self
4884            .current_slot_params()
4885            .partitioned_epoch_rewards_stake_account_stores_per_block();
4886    }
4887
4888    /// Applies slot-time changes for fields serialized into snapshots.
4889    fn apply_slot_time_persistent_changes(&mut self) {
4890        let params = self.current_slot_params();
4891        self.ns_per_slot = params.ns_per_slot();
4892        self.slots_per_year = params.slots_per_year();
4893        self.rent_collector.slots_per_year = params.slots_per_year();
4894        if !self.feature_set.is_active(&feature_set::alpenglow::id())
4895            && self.hashes_per_tick().is_some()
4896        {
4897            self.set_hashes_per_tick(params.hashes_per_tick());
4898        }
4899    }
4900
4901    /// Verifies bank fields are consistent with current slot params.
4902    fn assert_bank_matches_slot_params(&self) {
4903        let params = self.current_slot_params();
4904        assert_eq!(
4905            self.ns_per_slot,
4906            params.ns_per_slot(),
4907            "snapshot slot-time ns_per_slot mismatch"
4908        );
4909        assert_eq!(
4910            self.slots_per_year.to_bits(),
4911            params.slots_per_year().to_bits(),
4912            "snapshot slot-time slots_per_year mismatch"
4913        );
4914        assert_eq!(
4915            self.rent_collector.slots_per_year.to_bits(),
4916            params.slots_per_year().to_bits(),
4917            "snapshot slot-time rent_collector.slots_per_year mismatch"
4918        );
4919        let hashes_per_tick = self.hashes_per_tick();
4920        if !self.feature_set.is_active(&feature_set::alpenglow::id()) && hashes_per_tick.is_some() {
4921            assert_eq!(
4922                hashes_per_tick,
4923                params.hashes_per_tick(),
4924                "snapshot slot-time hashes_per_tick mismatch"
4925            );
4926        }
4927        assert_eq!(
4928            self.entry_bytes_budget().slot_limit(),
4929            params.max_entry_bytes_per_slot(),
4930            "snapshot slot-time entry byte budget mismatch"
4931        );
4932    }
4933
4934    /// Applies slot-time changes for runtime-only fields. This function is
4935    /// expected to be idempotent.
4936    fn apply_slot_time_runtime_changes(&mut self) {
4937        self.entry_bytes_consumed =
4938            EntryBytesBudget::new(self.current_slot_params().max_entry_bytes_per_slot());
4939        self.apply_cost_tracker_limits_for_active_features();
4940        self.apply_partitioned_epoch_rewards_config_for_active_features();
4941    }
4942
4943    fn apply_simd_0339_invoke_cost_changes(&mut self) {
4944        let simd_0268_active = self.feature_set.snapshot().raise_cpi_nesting_limit_to_8;
4945        let compute_budget = self
4946            .compute_budget()
4947            .as_ref()
4948            .unwrap_or(&ComputeBudget::new_with_defaults(simd_0268_active))
4949            .to_cost();
4950
4951        self.transaction_processor
4952            .set_execution_cost(compute_budget);
4953    }
4954
4955    /// This is called from genesis and snapshot restore
4956    fn apply_activated_features(&mut self) {
4957        // Update active set of reserved account keys which are not allowed to be write locked
4958        self.reserved_account_keys = {
4959            let mut reserved_keys = ReservedAccountKeys::clone(&self.reserved_account_keys);
4960            reserved_keys.update_active_set(&self.feature_set);
4961            Arc::new(reserved_keys)
4962        };
4963
4964        // Many fields are not serialized in snapshot or any configs. Rebuild
4965        // them from the feature set so the initial bank state is consistent.
4966        self.refresh_slot_params();
4967        self.apply_slot_time_runtime_changes();
4968        self.apply_simd_0339_invoke_cost_changes();
4969
4970        let program_runtime_environment =
4971            self.create_program_runtime_environment(&self.feature_set);
4972        self.transaction_processor
4973            .global_program_cache
4974            .write()
4975            .unwrap()
4976            .latest_root_slot = self.slot;
4977        self.transaction_processor
4978            .epoch_boundary_preparation
4979            .write()
4980            .unwrap()
4981            .upcoming_epoch = self.epoch;
4982        self.transaction_processor.program_runtime_environment = program_runtime_environment;
4983
4984        // Load all active built-in programs after the program runtime environment has been initialized
4985        self.add_active_builtin_programs();
4986    }
4987
4988    fn create_program_runtime_environment(
4989        &self,
4990        feature_set: &FeatureSet,
4991    ) -> ProgramRuntimeEnvironment {
4992        let simd_0268_active = feature_set.snapshot().raise_cpi_nesting_limit_to_8;
4993        let compute_budget = self
4994            .compute_budget()
4995            .as_ref()
4996            .unwrap_or(&ComputeBudget::new_with_defaults(simd_0268_active))
4997            .to_budget();
4998        create_program_runtime_environment(
4999            &feature_set.runtime_features(),
5000            &compute_budget,
5001            false, /* deployment */
5002            false, /* debugging_features */
5003        )
5004        .unwrap()
5005    }
5006
5007    pub fn set_tick_height(&self, tick_height: u64) {
5008        self.tick_height.store(tick_height, Relaxed)
5009    }
5010
5011    pub fn set_inflation(&self, inflation: Inflation) {
5012        *self.inflation.write().unwrap() = inflation;
5013    }
5014
5015    /// Get a snapshot of the current set of hard forks
5016    pub fn hard_forks(&self) -> HardForks {
5017        self.hard_forks.read().unwrap().clone()
5018    }
5019
5020    pub fn register_hard_fork(&self, new_hard_fork_slot: Slot) {
5021        let bank_slot = self.slot();
5022
5023        let lock = self.freeze_lock();
5024        let bank_frozen = *lock != Hash::default();
5025        if new_hard_fork_slot < bank_slot {
5026            warn!(
5027                "Hard fork at slot {new_hard_fork_slot} ignored, the hard fork is older than the \
5028                 bank at slot {bank_slot} that attempted to register it."
5029            );
5030        } else if (new_hard_fork_slot == bank_slot) && bank_frozen {
5031            warn!(
5032                "Hard fork at slot {new_hard_fork_slot} ignored, the hard fork is the same slot \
5033                 as the bank at slot {bank_slot} that attempted to register it, but that bank is \
5034                 already frozen."
5035            );
5036        } else {
5037            self.hard_forks
5038                .write()
5039                .unwrap()
5040                .register(new_hard_fork_slot);
5041        }
5042    }
5043
5044    pub fn register_hard_forks(&self, new_hard_fork_slots: Option<&Vec<Slot>>) {
5045        if let Some(slots) = new_hard_fork_slots {
5046            slots
5047                .iter()
5048                .for_each(|hard_fork_slot| self.register_hard_fork(*hard_fork_slot));
5049        }
5050    }
5051
5052    pub fn get_account_with_fixed_root_no_cache(
5053        &self,
5054        pubkey: &Pubkey,
5055    ) -> Option<AccountSharedData> {
5056        self.rc
5057            .accounts
5058            .load_with_fixed_root_do_not_populate_read_cache(&self.ancestors, pubkey)
5059            .map(|(acc, _slot)| acc)
5060    }
5061
5062    // Hi! leaky abstraction here....
5063    // try to use get_account_with_fixed_root() if it's called ONLY from on-chain runtime account
5064    // processing. That alternative fn provides more safety.
5065    pub fn get_account(&self, pubkey: &Pubkey) -> Option<AccountSharedData> {
5066        self.get_account_modified_slot(pubkey)
5067            .map(|(acc, _slot)| acc)
5068    }
5069
5070    // Hi! leaky abstraction here....
5071    // use this over get_account() if it's called ONLY from on-chain runtime account
5072    // processing (i.e. from in-band replay/banking stage; that ensures root is *fixed* while
5073    // running).
5074    // pro: safer assertion can be enabled inside AccountsDb
5075    // con: panics!() if called from off-chain processing
5076    pub fn get_account_with_fixed_root(&self, pubkey: &Pubkey) -> Option<AccountSharedData> {
5077        self.get_account_modified_slot_with_fixed_root(pubkey)
5078            .map(|(acc, _slot)| acc)
5079    }
5080
5081    // See note above get_account_with_fixed_root() about when to prefer this function
5082    pub fn get_account_modified_slot_with_fixed_root(
5083        &self,
5084        pubkey: &Pubkey,
5085    ) -> Option<(AccountSharedData, Slot)> {
5086        self.load_slow_with_fixed_root(&self.ancestors, pubkey)
5087    }
5088
5089    pub fn get_account_modified_slot(&self, pubkey: &Pubkey) -> Option<(AccountSharedData, Slot)> {
5090        self.load_slow(&self.ancestors, pubkey)
5091    }
5092
5093    fn load_slow(
5094        &self,
5095        ancestors: &Ancestors,
5096        pubkey: &Pubkey,
5097    ) -> Option<(AccountSharedData, Slot)> {
5098        // get_account (= primary this fn caller) may be called from on-chain Bank code even if we
5099        // try hard to use get_account_with_fixed_root for that purpose...
5100        // so pass safer LoadHint:Unspecified here as a fallback
5101        self.rc.accounts.load_without_fixed_root(ancestors, pubkey)
5102    }
5103
5104    fn load_slow_with_fixed_root(
5105        &self,
5106        ancestors: &Ancestors,
5107        pubkey: &Pubkey,
5108    ) -> Option<(AccountSharedData, Slot)> {
5109        self.rc.accounts.load_with_fixed_root(ancestors, pubkey)
5110    }
5111
5112    pub fn get_program_accounts(
5113        &self,
5114        program_id: &Pubkey,
5115    ) -> ScanResult<Vec<KeyedAccountSharedData>> {
5116        self.rc
5117            .accounts
5118            .load_by_program(&self.ancestors, self.bank_id, program_id)
5119    }
5120
5121    pub fn get_filtered_program_accounts<F: Fn(&AccountSharedData) -> bool>(
5122        &self,
5123        program_id: &Pubkey,
5124        filter: F,
5125    ) -> ScanResult<Vec<KeyedAccountSharedData>> {
5126        self.rc.accounts.load_by_program_with_filter(
5127            &self.ancestors,
5128            self.bank_id,
5129            program_id,
5130            filter,
5131        )
5132    }
5133
5134    pub fn get_filtered_indexed_accounts<F: Fn(&AccountSharedData) -> bool>(
5135        &self,
5136        index_key: &IndexKey,
5137        filter: F,
5138        byte_limit_for_scan: Option<usize>,
5139    ) -> ScanResult<Vec<KeyedAccountSharedData>> {
5140        self.rc.accounts.load_by_index_key_with_filter(
5141            &self.ancestors,
5142            self.bank_id,
5143            index_key,
5144            filter,
5145            byte_limit_for_scan,
5146        )
5147    }
5148
5149    pub fn account_indexes_include_key(&self, key: &Pubkey) -> bool {
5150        self.rc.accounts.account_indexes_include_key(key)
5151    }
5152
5153    // Scans all the accounts this bank can load, applying `scan_func`
5154    pub fn scan_all_accounts<F>(&self, scan_func: F) -> ScanResult<()>
5155    where
5156        F: FnMut(Option<(&Pubkey, AccountSharedData, Slot)>),
5157    {
5158        self.rc
5159            .accounts
5160            .scan_all(&self.ancestors, self.bank_id, scan_func)
5161    }
5162
5163    pub fn get_program_accounts_modified_since_parent(
5164        &self,
5165        program_id: &Pubkey,
5166    ) -> Vec<KeyedAccountSharedData> {
5167        self.rc
5168            .accounts
5169            .load_by_program_slot(self.slot(), Some(program_id))
5170    }
5171
5172    pub fn get_transaction_logs(
5173        &self,
5174        address: Option<&Pubkey>,
5175    ) -> Option<Vec<TransactionLogInfo>> {
5176        self.transaction_log_collector
5177            .read()
5178            .unwrap()
5179            .get_logs_for_address(address)
5180    }
5181
5182    /// Returns all the accounts stored in this slot
5183    pub fn get_all_accounts_modified_since_parent(&self) -> Vec<KeyedAccountSharedData> {
5184        self.rc.accounts.load_by_program_slot(self.slot(), None)
5185    }
5186
5187    // if you want get_account_modified_since_parent without fixed_root, please define so...
5188    fn get_account_modified_since_parent_with_fixed_root(
5189        &self,
5190        pubkey: &Pubkey,
5191    ) -> Option<(AccountSharedData, Slot)> {
5192        let just_self: Ancestors = Ancestors::from(vec![self.slot()]);
5193        if let Some((account, slot)) = self.load_slow_with_fixed_root(&just_self, pubkey)
5194            && slot == self.slot()
5195        {
5196            return Some((account, slot));
5197        }
5198        None
5199    }
5200
5201    pub fn get_largest_accounts(
5202        &self,
5203        num: usize,
5204        filter_by_address: &HashSet<Pubkey>,
5205        filter: AccountAddressFilter,
5206    ) -> ScanResult<Vec<(Pubkey, u64)>> {
5207        self.rc.accounts.load_largest_accounts(
5208            &self.ancestors,
5209            self.bank_id,
5210            num,
5211            filter_by_address,
5212            filter,
5213        )
5214    }
5215
5216    /// Return the accumulated executed transaction count
5217    pub fn transaction_count(&self) -> u64 {
5218        self.transaction_count.load(Relaxed)
5219    }
5220
5221    /// Returns the number of non-vote transactions processed without error
5222    /// since the most recent boot from snapshot or genesis.
5223    /// This value is not shared though the network, nor retained
5224    /// within snapshots, but is preserved in `Bank::new_from_parent`.
5225    pub fn non_vote_transaction_count_since_restart(&self) -> u64 {
5226        self.non_vote_transaction_count_since_restart.load(Relaxed)
5227    }
5228
5229    /// Return the transaction count executed only in this bank
5230    pub fn executed_transaction_count(&self) -> u64 {
5231        self.transaction_count()
5232            .saturating_sub(self.parent().map_or(0, |parent| parent.transaction_count()))
5233    }
5234
5235    pub fn transaction_error_count(&self) -> u64 {
5236        self.transaction_error_count.load(Relaxed)
5237    }
5238
5239    pub fn transaction_entries_count(&self) -> u64 {
5240        self.transaction_entries_count.load(Relaxed)
5241    }
5242
5243    pub fn transactions_per_entry_max(&self) -> u64 {
5244        self.transactions_per_entry_max.load(Relaxed)
5245    }
5246
5247    pub fn max_data_shreds_per_slot(&self) -> u32 {
5248        self.max_data_shreds_per_slot_for_slot(self.slot())
5249    }
5250
5251    pub fn max_code_shreds_per_slot(&self) -> u32 {
5252        self.max_code_shreds_per_slot_for_slot(self.slot())
5253    }
5254
5255    /// Returns the data shred limit applicable to `slot`.
5256    ///
5257    /// Limit changes are delayed by an epoch, so a root bank can derive the
5258    /// limit for any slot inside the shred intake window.
5259    pub fn max_data_shreds_per_slot_for_slot(&self, slot: Slot) -> u32 {
5260        self.slot_params_at_slot(slot).max_data_shreds_per_slot()
5261    }
5262
5263    /// Returns the code shred limit applicable to `slot`.
5264    ///
5265    /// Limit changes are delayed by an epoch, so a root bank can derive the
5266    /// limit for any slot inside the shred intake window.
5267    pub fn max_code_shreds_per_slot_for_slot(&self, slot: Slot) -> u32 {
5268        self.slot_params_at_slot(slot).max_code_shreds_per_slot()
5269    }
5270
5271    pub fn max_entry_bytes_per_slot(&self) -> u64 {
5272        self.entry_bytes_budget().slot_limit()
5273    }
5274
5275    pub fn entry_bytes_budget(&self) -> &EntryBytesBudget {
5276        &self.entry_bytes_consumed
5277    }
5278
5279    fn increment_transaction_count(&self, tx_count: u64) {
5280        self.transaction_count.fetch_add(tx_count, Relaxed);
5281    }
5282
5283    fn increment_non_vote_transaction_count_since_restart(&self, tx_count: u64) {
5284        self.non_vote_transaction_count_since_restart
5285            .fetch_add(tx_count, Relaxed);
5286    }
5287
5288    pub fn signature_count(&self) -> u64 {
5289        self.signature_count.load(Relaxed)
5290    }
5291
5292    fn increment_signature_count(&self, signature_count: u64) {
5293        self.signature_count.fetch_add(signature_count, Relaxed);
5294    }
5295
5296    pub fn get_signature_status_processed_since_parent(
5297        &self,
5298        signature: &Signature,
5299    ) -> Option<Result<()>> {
5300        if let Some((slot, status)) = self.get_signature_status_slot(signature)
5301            && slot <= self.slot()
5302        {
5303            return Some(status);
5304        }
5305        None
5306    }
5307
5308    pub fn get_signature_status_with_blockhash(
5309        &self,
5310        signature: &Signature,
5311        blockhash: &Hash,
5312    ) -> Option<Result<()>> {
5313        let rcache = self.status_cache.read().unwrap();
5314        rcache
5315            .get_status(signature, blockhash, &self.ancestors)
5316            .map(|v| v.1)
5317    }
5318
5319    pub fn get_committed_transaction_status_and_slot(
5320        &self,
5321        message_hash: &Hash,
5322        transaction_blockhash: &Hash,
5323    ) -> Option<(Slot, bool)> {
5324        let rcache = self.status_cache.read().unwrap();
5325        rcache
5326            .get_status(message_hash, transaction_blockhash, &self.ancestors)
5327            .map(|(slot, status)| (slot, status.is_ok()))
5328    }
5329
5330    pub fn get_signature_status_slot(&self, signature: &Signature) -> Option<(Slot, Result<()>)> {
5331        let rcache = self.status_cache.read().unwrap();
5332        rcache.get_status_any_blockhash(signature, &self.ancestors)
5333    }
5334
5335    pub fn get_signature_status(&self, signature: &Signature) -> Option<Result<()>> {
5336        self.get_signature_status_slot(signature).map(|v| v.1)
5337    }
5338
5339    pub fn has_signature(&self, signature: &Signature) -> bool {
5340        self.get_signature_status_slot(signature).is_some()
5341    }
5342
5343    /// Hash the `accounts` HashMap. This represents a validator's interpretation
5344    ///  of the delta of the ledger since the last vote and up to now
5345    fn hash_internal_state(&self) -> Hash {
5346        let measure_total = Measure::start("");
5347        let slot = self.slot();
5348
5349        let mut hash = hashv(&[
5350            self.parent_hash.as_ref(),
5351            &self.signature_count().to_le_bytes(),
5352            self.last_blockhash().as_ref(),
5353        ]);
5354
5355        let accounts_lt_hash_checksum = {
5356            let accounts_lt_hash = &*self.accounts_lt_hash.lock().unwrap();
5357            let lt_hash_bytes = bytemuck::must_cast_slice(&accounts_lt_hash.0.0);
5358            hash = hashv(&[hash.as_ref(), lt_hash_bytes]);
5359            accounts_lt_hash.0.checksum()
5360        };
5361
5362        let buf = self
5363            .hard_forks
5364            .read()
5365            .unwrap()
5366            .get_hash_data(slot, self.parent_slot());
5367        if let Some(buf) = buf {
5368            let hard_forked_hash = hashv(&[hash.as_ref(), &buf]);
5369            warn!("hard fork at slot {slot} by hashing {buf:?}: {hash} => {hard_forked_hash}");
5370            hash = hard_forked_hash;
5371        }
5372
5373        #[cfg(feature = "dev-context-only-utils")]
5374        let hash_override = self
5375            .hash_overrides
5376            .lock()
5377            .unwrap()
5378            .get_bank_hash_override(slot)
5379            .copied()
5380            .inspect(|&hash_override| {
5381                if hash_override != hash {
5382                    info!(
5383                        "bank: slot: {}: overrode bank hash: {} with {}",
5384                        self.slot(),
5385                        hash,
5386                        hash_override
5387                    );
5388                }
5389            });
5390        // Avoid to optimize out `hash` along with the whole computation by super smart rustc.
5391        // hash_override is used by ledger-tool's simulate-block-production, which prefers
5392        // the actual bank freezing processing for accurate simulation.
5393        #[cfg(feature = "dev-context-only-utils")]
5394        let hash = hash_override.unwrap_or(std::hint::black_box(hash));
5395
5396        let bank_hash_stats = self.bank_hash_stats.load();
5397
5398        let total_us = measure_total.end_as_us();
5399
5400        datapoint_info!(
5401            "bank-hash_internal_state",
5402            ("slot", slot, i64),
5403            ("total_us", total_us, i64),
5404        );
5405        info!(
5406            "bank frozen: {slot} hash: {hash} signature_count: {} last_blockhash: {} \
5407             capitalization: {}, accounts_lt_hash checksum: {accounts_lt_hash_checksum}, stats: \
5408             {bank_hash_stats:?}",
5409            self.signature_count(),
5410            self.last_blockhash(),
5411            self.capitalization(),
5412        );
5413        hash
5414    }
5415
5416    /// Used by ledger tool to run a final hash calculation once all ledger replay has completed.
5417    /// This should not be called by validator code.
5418    pub fn run_final_hash_calc(&self) {
5419        self.force_flush_accounts_cache();
5420        // note that this slot may not be a root
5421        _ = self.verify_accounts(None);
5422    }
5423
5424    /// Verify the account state as part of startup, typically from a snapshot.
5425    ///
5426    /// This fn compares the calculated accounts lt hash against the stored value in the bank.
5427    ///
5428    /// Normal validator operation will calculate the accounts lt hash during index generation.
5429    /// Tests/ledger-tool may not have the calculated value from index generation (or the bank
5430    /// being verified is different from the snapshot/startup bank), and thus will be calculated in
5431    /// this function, using the accounts index for input, running in the foreground.
5432    ///
5433    /// Returns true if all is good.
5434    ///
5435    /// Only intended to be called at startup, or from tests/ledger-tool.
5436    #[must_use]
5437    fn verify_accounts(&self, calculated_accounts_lt_hash: Option<&AccountsLtHash>) -> bool {
5438        let accounts_db = &self.rc.accounts.accounts_db;
5439
5440        fn check_lt_hash(
5441            expected_accounts_lt_hash: &AccountsLtHash,
5442            calculated_accounts_lt_hash: &AccountsLtHash,
5443        ) -> bool {
5444            let is_ok = calculated_accounts_lt_hash == expected_accounts_lt_hash;
5445            if !is_ok {
5446                let expected = expected_accounts_lt_hash.0.checksum();
5447                let calculated = calculated_accounts_lt_hash.0.checksum();
5448                error!(
5449                    "Verifying accounts failed: accounts lattice hashes do not match, expected: \
5450                     {expected}, calculated: {calculated}",
5451                );
5452            }
5453            is_ok
5454        }
5455
5456        info!("Verifying accounts...");
5457        let start = Instant::now();
5458        let expected_accounts_lt_hash = self.accounts_lt_hash.lock().unwrap().clone();
5459        let is_ok = if let Some(calculated_accounts_lt_hash) = calculated_accounts_lt_hash {
5460            check_lt_hash(&expected_accounts_lt_hash, calculated_accounts_lt_hash)
5461        } else {
5462            let calculated_accounts_lt_hash =
5463                accounts_db.calculate_accounts_lt_hash_at_startup_from_index(&self.ancestors);
5464            check_lt_hash(&expected_accounts_lt_hash, &calculated_accounts_lt_hash)
5465        };
5466        info!("Verifying accounts... Done in {:?}", start.elapsed());
5467        is_ok
5468    }
5469
5470    /// Get this bank's storages to use for snapshots.
5471    ///
5472    /// If a base slot is provided, return only the storages that are *higher* than this slot.
5473    pub fn get_snapshot_storages(&self, base_slot: Option<Slot>) -> Vec<Arc<AccountStorageEntry>> {
5474        // if a base slot is provided, request storages starting at the slot *after*
5475        let start_slot = base_slot.map_or(0, |slot| slot.saturating_add(1));
5476        // we want to *include* the storage at our slot
5477        let requested_slots = start_slot..=self.slot();
5478
5479        self.rc.accounts.accounts_db.get_storages(requested_slots).0
5480    }
5481
5482    #[must_use]
5483    fn verify_hash(&self) -> bool {
5484        assert!(self.is_frozen());
5485        let calculated_hash = self.hash_internal_state();
5486        let expected_hash = self.hash();
5487
5488        if calculated_hash == expected_hash {
5489            true
5490        } else {
5491            warn!(
5492                "verify failed: slot: {}, {} (calculated) != {} (expected)",
5493                self.slot(),
5494                calculated_hash,
5495                expected_hash
5496            );
5497            false
5498        }
5499    }
5500
5501    /// Verify the transaction signatures, hash and other metadata.
5502    pub fn verify_transaction(
5503        &self,
5504        tx: VersionedTransaction,
5505        verification_mode: TransactionVerificationMode,
5506    ) -> Result<RuntimeTransaction<SanitizedTransaction>> {
5507        // Discard v1 transactions until feature gate is activated.
5508        if !self.feature_set.snapshot().enable_tx_v1
5509            && tx.version() == TransactionVersion::Number(1)
5510        {
5511            return Err(TransactionError::UnsupportedVersion);
5512        }
5513
5514        let serialized_message = tx.message.serialize();
5515        self.verify_transaction_with_serialized_message(tx, &serialized_message, verification_mode)
5516    }
5517
5518    /// Verify the transaction signatures, hash and other metadata, using the provided serialized
5519    /// message.
5520    ///
5521    /// Verifying a transaction requires the serialized message to calculate the message hash. Use
5522    /// this function if the message is already available. Note that the serialized message MUST
5523    /// correspond to the transaction's message.
5524    pub fn verify_transaction_with_serialized_message(
5525        &self,
5526        tx: VersionedTransaction,
5527        serialized_message: &[u8],
5528        verification_mode: TransactionVerificationMode,
5529    ) -> Result<RuntimeTransaction<SanitizedTransaction>> {
5530        // Discard v1 transactions until feature gate is activated.
5531        let enable_tx_v1 = self.feature_set.snapshot().enable_tx_v1;
5532        if !enable_tx_v1 && tx.version() == TransactionVersion::Number(1) {
5533            return Err(TransactionError::UnsupportedVersion);
5534        }
5535        let max_transaction_size = match tx.version() {
5536            TransactionVersion::Number(1) if enable_tx_v1 => {
5537                solana_message::v1::MAX_TRANSACTION_SIZE
5538            }
5539            _ => PACKET_DATA_SIZE,
5540        } as u64;
5541
5542        // WARNING: Any pending features added here most likely must also be checked in
5543        //          `Bank::resanitize_transaction_minimally`.
5544        let sanitized_tx = {
5545            let size =
5546                wincode::serialized_size(&tx).map_err(|_| TransactionError::SanitizeFailure)?;
5547            if size > max_transaction_size {
5548                return Err(TransactionError::SanitizeFailure);
5549            }
5550
5551            // SIMD-0160, check instruction limit before signature verification
5552            if tx.message.instructions().len()
5553                > solana_transaction_context::MAX_INSTRUCTION_TRACE_LENGTH
5554            {
5555                return Err(solana_transaction_error::TransactionError::SanitizeFailure);
5556            }
5557
5558            let message_hash = if verification_mode == TransactionVerificationMode::FullVerification
5559            {
5560                tx.verify_and_hash_message()?
5561            } else {
5562                VersionedMessage::hash_raw_message(serialized_message)
5563            };
5564
5565            RuntimeTransaction::try_create(
5566                tx,
5567                MessageHash::Precomputed(message_hash),
5568                None,
5569                self,
5570                self.get_reserved_account_keys(),
5571            )
5572        }?;
5573
5574        Ok(sanitized_tx)
5575    }
5576
5577    /// Checks if the transaction violates the bank's reserved keys.
5578    /// This needs to be checked upon epoch boundary crosses because the
5579    /// reserved key set may have changed since the initial sanitization.
5580    pub fn check_reserved_keys(&self, tx: &impl SVMMessage) -> Result<()> {
5581        // Check keys against the reserved set - these failures simply require us
5582        // to re-sanitize the transaction. We do not need to drop the transaction.
5583        let reserved_keys = self.get_reserved_account_keys();
5584        for (index, key) in tx.account_keys().iter().enumerate() {
5585            if tx.is_writable(index) && reserved_keys.contains(key) {
5586                return Err(TransactionError::ResanitizationNeeded);
5587            }
5588        }
5589
5590        Ok(())
5591    }
5592
5593    /// Calculates and returns the capitalization.
5594    ///
5595    /// Panics if capitalization overflows a u64.
5596    ///
5597    /// Note, this is *very* expensive!  It walks the whole accounts index,
5598    /// account-by-account, summing each account's balance.
5599    ///
5600    /// Only intended to be called at startup by ledger-tool or tests.
5601    /// (cannot be made DCOU due to solana-program-test)
5602    pub fn calculate_capitalization_for_tests(&self) -> u64 {
5603        self.rc
5604            .accounts
5605            .accounts_db
5606            .calculate_capitalization_at_startup_from_index(&self.ancestors)
5607    }
5608
5609    /// Sets the capitalization.
5610    ///
5611    /// Only intended to be called by ledger-tool or tests.
5612    /// (cannot be made DCOU due to solana-program-test)
5613    pub fn set_capitalization_for_tests(&self, capitalization: u64) {
5614        self.capitalization.store(capitalization, Relaxed);
5615    }
5616
5617    /// Returns the `SnapshotHash` for this bank's slot
5618    ///
5619    /// This fn is used at startup to verify the bank was rebuilt correctly.
5620    pub fn get_snapshot_hash(&self) -> SnapshotHash {
5621        SnapshotHash::new(self.accounts_lt_hash.lock().unwrap().0.checksum())
5622    }
5623
5624    /// A snapshot bank should be purged of 0 lamport accounts which are not part of the hash
5625    /// calculation and could shield other real accounts.
5626    pub fn verify_snapshot_bank(
5627        &self,
5628        skip_shrink: bool,
5629        force_clean: bool,
5630        latest_full_snapshot_slot: Slot,
5631        calculated_accounts_lt_hash: Option<&AccountsLtHash>,
5632    ) -> bool {
5633        let (verified_accounts, verify_accounts_time_us) = measure_us!({
5634            let should_verify_accounts = !self.rc.accounts.accounts_db.skip_initial_hash_calc;
5635            if should_verify_accounts {
5636                self.verify_accounts(calculated_accounts_lt_hash)
5637            } else {
5638                info!("Verifying accounts... Skipped.");
5639                true
5640            }
5641        });
5642
5643        let (_, clean_time_us) = measure_us!({
5644            let should_clean = force_clean || (!skip_shrink && self.slot() > 0);
5645            if should_clean {
5646                info!("Cleaning...");
5647                // We cannot clean past the latest full snapshot's slot because we are about to
5648                // perform an accounts hash calculation *up to that slot*.  If we cleaned *past*
5649                // that slot, then accounts could be removed from older storages, which would
5650                // change the accounts hash.
5651                self.rc
5652                    .accounts
5653                    .accounts_db
5654                    .clean_accounts(Some(latest_full_snapshot_slot), true);
5655                info!("Cleaning... Done.");
5656            } else {
5657                info!("Cleaning... Skipped.");
5658            }
5659        });
5660
5661        let (_, shrink_time_us) = measure_us!({
5662            let should_shrink = !skip_shrink && self.slot() > 0;
5663            if should_shrink {
5664                info!("Shrinking...");
5665                self.rc.accounts.accounts_db.shrink_all_slots(
5666                    true,
5667                    // we cannot allow the snapshot slot to be shrunk
5668                    Some(self.slot()),
5669                );
5670                info!("Shrinking... Done.");
5671            } else {
5672                info!("Shrinking... Skipped.");
5673            }
5674        });
5675
5676        info!("Verifying bank...");
5677        let (verified_bank, verify_bank_time_us) = measure_us!(self.verify_hash());
5678        info!("Verifying bank... Done.");
5679
5680        datapoint_info!(
5681            "verify_snapshot_bank",
5682            ("clean_us", clean_time_us, i64),
5683            ("shrink_us", shrink_time_us, i64),
5684            ("verify_accounts_us", verify_accounts_time_us, i64),
5685            ("verify_bank_us", verify_bank_time_us, i64),
5686        );
5687
5688        verified_accounts && verified_bank
5689    }
5690
5691    /// Return the number of hashes per tick
5692    pub fn hashes_per_tick(&self) -> Option<u64> {
5693        *self.hashes_per_tick.read().unwrap()
5694    }
5695
5696    /// Return the number of ticks per slot
5697    pub fn ticks_per_slot(&self) -> u64 {
5698        self.ticks_per_slot
5699    }
5700
5701    /// Return the target number of ticks per second for this bank.
5702    pub fn ticks_per_second(&self) -> u64 {
5703        let ticks_per_slot = u128::from(self.ticks_per_slot.max(1));
5704        let ns_per_tick = self.ns_per_slot.saturating_div(ticks_per_slot).max(1);
5705        u64::try_from(1_000_000_000u128.saturating_div(ns_per_tick))
5706            .expect("ticks per second must fit in u64")
5707    }
5708
5709    /// Return the number of slots per year
5710    pub fn slots_per_year(&self) -> f64 {
5711        self.slots_per_year
5712    }
5713
5714    /// Return the number of ticks since genesis.
5715    pub fn tick_height(&self) -> u64 {
5716        self.tick_height.load(Relaxed)
5717    }
5718
5719    /// Return the inflation parameters of the Bank
5720    pub fn inflation(&self) -> Inflation {
5721        *self.inflation.read().unwrap()
5722    }
5723
5724    /// Return the rent collector for this Bank
5725    pub fn rent_collector(&self) -> &RentCollector {
5726        &self.rent_collector
5727    }
5728
5729    /// Return the total capitalization of the Bank
5730    pub fn capitalization(&self) -> u64 {
5731        self.capitalization.load(Relaxed)
5732    }
5733
5734    /// Return this bank's max_tick_height
5735    pub fn max_tick_height(&self) -> u64 {
5736        self.max_tick_height
5737    }
5738
5739    /// Return the block_height of this bank
5740    pub fn block_height(&self) -> u64 {
5741        self.block_height
5742    }
5743
5744    /// Return the number of slots per epoch for the given epoch
5745    pub fn get_slots_in_epoch(&self, epoch: Epoch) -> u64 {
5746        self.epoch_schedule().get_slots_in_epoch(epoch)
5747    }
5748
5749    /// returns the epoch for which this bank's leader_schedule_slot_offset and slot would
5750    ///  need to cache leader_schedule
5751    pub fn get_leader_schedule_epoch(&self, slot: Slot) -> Epoch {
5752        self.epoch_schedule().get_leader_schedule_epoch(slot)
5753    }
5754
5755    /// a bank-level cache of vote accounts and stake delegation info
5756    fn update_stakes_cache(
5757        &self,
5758        txs: &[impl SVMMessage],
5759        processing_results: &[TransactionProcessingResult],
5760    ) {
5761        debug_assert_eq!(txs.len(), processing_results.len());
5762        let new_warmup_cooldown_rate_epoch = self.new_warmup_cooldown_rate_epoch();
5763        let use_fixed_point_stake_math = self.use_fixed_point_stake_math();
5764        txs.iter()
5765            .zip(processing_results)
5766            .filter_map(|(tx, processing_result)| {
5767                processing_result
5768                    .processed_transaction()
5769                    .map(|processed_tx| (tx, processed_tx))
5770            })
5771            .filter_map(|(tx, processed_tx)| {
5772                processed_tx
5773                    .executed_transaction()
5774                    .map(|executed_tx| (tx, executed_tx))
5775            })
5776            .filter(|(_, executed_tx)| executed_tx.was_successful())
5777            .flat_map(|(tx, executed_tx)| {
5778                let num_account_keys = tx.account_keys().len();
5779                let loaded_tx = &executed_tx.loaded_transaction;
5780                loaded_tx.accounts.iter().take(num_account_keys)
5781            })
5782            .for_each(|(pubkey, account)| {
5783                // note that this could get timed to: self.rc.accounts.accounts_db.stats.stakes_cache_check_and_store_us,
5784                //  but this code path is captured separately in ExecuteTimingType::UpdateStakesCacheUs
5785                self.stakes_cache.check_and_store(
5786                    pubkey,
5787                    account,
5788                    new_warmup_cooldown_rate_epoch,
5789                    use_fixed_point_stake_math,
5790                );
5791            });
5792    }
5793
5794    /// current vote accounts for this bank along with the stake
5795    ///   attributed to each account
5796    pub fn vote_accounts(&self) -> Arc<VoteAccountsHashMap> {
5797        let stakes = self.stakes_cache.stakes();
5798        Arc::from(stakes.vote_accounts())
5799    }
5800
5801    /// Vote account for the given vote account pubkey.
5802    pub fn get_vote_account(&self, vote_account: &Pubkey) -> Option<VoteAccount> {
5803        let stakes = self.stakes_cache.stakes();
5804        let vote_account = stakes.vote_accounts().get(vote_account)?;
5805        Some(vote_account.clone())
5806    }
5807
5808    /// Get the EpochStakes for the current Bank::epoch
5809    pub fn current_epoch_stakes(&self) -> &VersionedEpochStakes {
5810        // The stakes for a given epoch (E) in self.epoch_stakes are keyed by leader schedule epoch
5811        // (E + 1) so the stakes for the current epoch are stored at self.epoch_stakes[E + 1]
5812        self.epoch_stakes
5813            .get(&self.epoch.saturating_add(1))
5814            .expect("Current epoch stakes must exist")
5815    }
5816
5817    /// Get the EpochStakes for a given epoch
5818    pub fn epoch_stakes(&self, epoch: Epoch) -> Option<&VersionedEpochStakes> {
5819        self.epoch_stakes.get(&epoch)
5820    }
5821
5822    /// Verify a BLS certificate's signature using this bank's epoch stakes.
5823    pub fn verify_certificate(
5824        &self,
5825        cert: UnverifiedCertificate,
5826    ) -> std::result::Result<Certificate, CertVerifyError> {
5827        let slot = cert.cert_type.slot();
5828        let epoch_stakes = self
5829            .epoch_stakes_from_slot(slot)
5830            .ok_or(CertVerifyError::MissingRankMap)?;
5831        let key_to_rank_map = epoch_stakes.bls_pubkey_to_rank_map();
5832        let total_stake = key_to_rank_map.total_stake();
5833
5834        let cert =
5835            cert_verify::verify_certificate(cert, key_to_rank_map.len(), total_stake, |rank| {
5836                key_to_rank_map
5837                    .get_pubkey_stake_entry(rank)
5838                    .map(|entry| (entry.stake, entry.bls_pubkey))
5839            })?;
5840
5841        Ok(cert)
5842    }
5843
5844    pub fn epoch_stakes_map(&self) -> &HashMap<Epoch, VersionedEpochStakes> {
5845        &self.epoch_stakes
5846    }
5847
5848    /// Returns a mapping from validator [`Pubkey`] to stake in Lamports for the current Bank::epoch.
5849    pub fn current_epoch_staked_nodes(&self) -> Arc<HashMap<Pubkey, u64>> {
5850        self.current_epoch_stakes().stakes().staked_nodes()
5851    }
5852
5853    /// Returns a mapping from validator [`Pubkey`] to stake in Lamports for the given epoch.
5854    pub fn epoch_staked_nodes(&self, epoch: Epoch) -> Option<Arc<HashMap<Pubkey, u64>>> {
5855        Some(self.epoch_stakes.get(&epoch)?.stakes().staked_nodes())
5856    }
5857
5858    /// Returns the total stake in Lamports for the given epoch.
5859    pub fn epoch_total_stake(&self, epoch: Epoch) -> Option<u64> {
5860        self.epoch_stakes
5861            .get(&epoch)
5862            .map(|epoch_stakes| epoch_stakes.total_stake())
5863    }
5864
5865    /// Returns the total stake in Lamports for the current Bank::epoch.
5866    pub fn get_current_epoch_total_stake(&self) -> u64 {
5867        self.current_epoch_stakes().total_stake()
5868    }
5869
5870    /// Returns a mapping from [`Pubkey`] to (stake in Lamports and [`VoteAccount`]) for the given epoch.
5871    pub fn epoch_vote_accounts(&self, epoch: Epoch) -> Option<&VoteAccountsHashMap> {
5872        let epoch_stakes = self.epoch_stakes.get(&epoch)?.stakes();
5873        Some(epoch_stakes.vote_accounts().as_ref())
5874    }
5875
5876    /// Returns a mapping from [`Pubkey`] to (stake in Lamports and [`VoteAccount`]) for the current Bank::epoch.
5877    pub fn get_current_epoch_vote_accounts(&self) -> &VoteAccountsHashMap {
5878        self.current_epoch_stakes()
5879            .stakes()
5880            .vote_accounts()
5881            .as_ref()
5882    }
5883
5884    /// Get the fixed authorized voter for the given vote account for the
5885    /// current epoch
5886    pub fn epoch_authorized_voter(&self, vote_account: &Pubkey) -> Option<&Pubkey> {
5887        self.epoch_stakes
5888            .get(&self.epoch)
5889            .expect("Epoch stakes for bank's own epoch must exist")
5890            .epoch_authorized_voters()
5891            .get(vote_account)
5892    }
5893
5894    /// Get the fixed set of vote accounts for the given node id for the
5895    /// current epoch
5896    pub fn epoch_vote_accounts_for_node_id(&self, node_id: &Pubkey) -> Option<&NodeVoteAccounts> {
5897        self.epoch_stakes
5898            .get(&self.epoch)
5899            .expect("Epoch stakes for bank's own epoch must exist")
5900            .node_id_to_vote_accounts()
5901            .get(node_id)
5902    }
5903
5904    /// Returns the total stake in Lamports belonging to vote accounts associated with the given node_id for the given epoch.
5905    pub fn epoch_node_id_to_stake(&self, epoch: Epoch, node_id: &Pubkey) -> Option<u64> {
5906        self.epoch_stakes(epoch)
5907            .and_then(|epoch_stakes| epoch_stakes.node_id_to_stake(node_id))
5908    }
5909
5910    /// Returns the total stake in Lamports of all vote accounts for current Bank::epoch.
5911    pub fn total_epoch_stake(&self) -> u64 {
5912        self.epoch_stakes
5913            .get(&self.epoch)
5914            .expect("Epoch stakes for bank's own epoch must exist")
5915            .total_stake()
5916    }
5917
5918    /// Get the fixed stake of the given vote account for the current epoch
5919    pub fn epoch_vote_account_stake(&self, vote_account: &Pubkey) -> u64 {
5920        *self
5921            .epoch_vote_accounts(self.epoch())
5922            .expect("Bank epoch vote accounts must contain entry for the bank's own epoch")
5923            .get(vote_account)
5924            .map(|(stake, _)| stake)
5925            .unwrap_or(&0)
5926    }
5927
5928    /// given a slot, return the epoch and offset into the epoch this slot falls
5929    /// e.g. with a fixed number for slots_per_epoch, the calculation is simply:
5930    ///
5931    ///  ( slot/slots_per_epoch, slot % slots_per_epoch )
5932    ///
5933    pub fn get_epoch_and_slot_index(&self, slot: Slot) -> (Epoch, SlotIndex) {
5934        self.epoch_schedule().get_epoch_and_slot_index(slot)
5935    }
5936
5937    pub fn get_epoch_info(&self) -> EpochInfo {
5938        let absolute_slot = self.slot();
5939        let block_height = self.block_height();
5940        let (epoch, slot_index) = self.get_epoch_and_slot_index(absolute_slot);
5941        let slots_in_epoch = self.get_slots_in_epoch(epoch);
5942        let transaction_count = Some(self.transaction_count());
5943        EpochInfo {
5944            epoch,
5945            slot_index,
5946            slots_in_epoch,
5947            absolute_slot,
5948            block_height,
5949            transaction_count,
5950        }
5951    }
5952
5953    pub fn is_empty(&self) -> bool {
5954        !self.is_delta.load(Relaxed)
5955    }
5956
5957    pub fn add_mockup_builtin(&mut self, program_id: Pubkey, builtin: BuiltinFunctionRegisterer) {
5958        self.add_builtin(
5959            program_id,
5960            "mockup",
5961            ProgramCacheEntry::new_builtin(self.slot, builtin),
5962        );
5963    }
5964
5965    pub fn add_precompile(&mut self, program_id: &Pubkey) {
5966        debug!("Adding precompiled program {program_id}");
5967        self.add_precompiled_account(program_id);
5968        debug!("Added precompiled program {program_id:?}");
5969    }
5970
5971    // Call AccountsDb::clean_accounts()
5972    //
5973    // This fn is meant to be called by the snapshot handler in Accounts Background Service.  If
5974    // calling from elsewhere, ensure the same invariants hold/expectations are met.
5975    pub(crate) fn clean_accounts(&self) {
5976        // Don't clean the slot we're snapshotting because it may have zero-lamport
5977        // accounts that were included in the bank delta hash when the bank was frozen,
5978        // and if we clean them here, any newly created snapshot's hash for this bank
5979        // may not match the frozen hash.
5980        //
5981        // So when we're snapshotting, the highest slot to clean is lowered by one.
5982        let highest_slot_to_clean = self.slot().saturating_sub(1);
5983
5984        self.rc
5985            .accounts
5986            .accounts_db
5987            .clean_accounts(Some(highest_slot_to_clean), false);
5988    }
5989
5990    pub fn print_accounts_stats(&self) {
5991        self.rc.accounts.accounts_db.print_accounts_stats("");
5992    }
5993
5994    pub fn shrink_candidate_slots(&self) -> usize {
5995        self.rc
5996            .accounts
5997            .accounts_db
5998            .shrink_candidate_slots(self.epoch_schedule())
5999    }
6000
6001    pub(crate) fn shrink_ancient_slots(&self) {
6002        self.rc
6003            .accounts
6004            .accounts_db
6005            .shrink_ancient_slots(self.epoch_schedule())
6006    }
6007
6008    pub fn read_cost_tracker(&self) -> LockResult<RwLockReadGuard<'_, CostTracker>> {
6009        self.cost_tracker.read()
6010    }
6011
6012    pub fn write_cost_tracker(&self) -> LockResult<RwLockWriteGuard<'_, CostTracker>> {
6013        self.cost_tracker.write()
6014    }
6015
6016    // Check if the wallclock time from bank creation to now has exceeded the allotted
6017    // time for transaction processing
6018    pub fn should_bank_still_be_processing_txs(
6019        bank_creation_time: &Instant,
6020        max_tx_ingestion_nanos: u128,
6021    ) -> bool {
6022        // Do this check outside of the PoH lock, hence not a method on PohRecorder
6023        bank_creation_time.elapsed().as_nanos() <= max_tx_ingestion_nanos
6024    }
6025
6026    pub fn deactivate_feature(&mut self, id: &Pubkey) {
6027        let mut feature_set = Arc::make_mut(&mut self.feature_set).clone();
6028        feature_set.deactivate(id);
6029        self.feature_set = Arc::new(feature_set);
6030        self.refresh_slot_params();
6031    }
6032
6033    pub fn activate_feature(&mut self, id: &Pubkey) {
6034        let mut feature_set = Arc::make_mut(&mut self.feature_set).clone();
6035        feature_set.activate(id, 0);
6036        self.feature_set = Arc::new(feature_set);
6037        self.refresh_slot_params();
6038    }
6039
6040    pub fn fill_bank_with_ticks_for_tests(&self) {
6041        self.do_fill_bank_with_ticks_for_tests(&BankWithScheduler::no_scheduler_available())
6042    }
6043
6044    pub(crate) fn do_fill_bank_with_ticks_for_tests(&self, scheduler: &InstalledSchedulerRwLock) {
6045        if self.tick_height.load(Relaxed) < self.max_tick_height {
6046            let last_blockhash = self.last_blockhash();
6047            while self.last_blockhash() == last_blockhash {
6048                self.register_tick(&Hash::new_unique(), scheduler)
6049            }
6050        } else {
6051            warn!("Bank already reached max tick height, cannot fill it with more ticks");
6052        }
6053    }
6054
6055    /// Get a set of all actively reserved account keys that are not allowed to
6056    /// be write-locked during transaction processing.
6057    pub fn get_reserved_account_keys(&self) -> &HashSet<Pubkey> {
6058        &self.reserved_account_keys.active
6059    }
6060
6061    /// Compute and apply all activated features, initialize the transaction
6062    /// processor, and recalculate partitioned rewards if needed
6063    fn initialize_after_snapshot_restore<F, TP>(&mut self, rewards_thread_pool_builder: F)
6064    where
6065        F: FnOnce() -> TP,
6066        TP: std::borrow::Borrow<ThreadPool>,
6067    {
6068        self.transaction_processor =
6069            TransactionBatchProcessor::new_uninitialized(self.slot, self.epoch);
6070        if let Some(compute_budget) = &self.compute_budget {
6071            self.transaction_processor
6072                .set_execution_cost(compute_budget.to_cost());
6073        }
6074
6075        self.compute_and_apply_features_after_snapshot_restore();
6076        self.stakes_cache.refresh_delegated_stakes(
6077            self.new_warmup_cooldown_rate_epoch(),
6078            self.use_fixed_point_stake_math(),
6079        );
6080
6081        self.recalculate_partitioned_rewards_if_active(rewards_thread_pool_builder);
6082
6083        self.transaction_processor
6084            .fill_missing_sysvar_cache_entries(self);
6085    }
6086
6087    /// Compute and apply all activated features and also add accounts for builtins
6088    fn compute_and_apply_genesis_features(&mut self) {
6089        // Update the feature set to include all features active at this slot
6090        let feature_set = self.compute_active_feature_set(false).0;
6091        self.feature_set = Arc::new(feature_set);
6092
6093        // Apply rent deprecation feature if it's active at genesis
6094        // After feature cleanup, assert that rent exemption threshold is 1.0
6095        if self
6096            .feature_set
6097            .snapshot()
6098            .deprecate_rent_exemption_threshold
6099        {
6100            self.rent_collector.deprecate_rent_exemption_threshold();
6101        }
6102
6103        // Apply the doubled disinflation rate if it's active at genesis (the
6104        // re-anchor is a no-op for `initial` at year zero). Not needed on
6105        // snapshot restore: the serialized bank fields carry the result.
6106        if self
6107            .feature_set
6108            .is_active(&feature_set::double_disinflation_rate::id())
6109        {
6110            self.apply_double_disinflation_rate();
6111        }
6112
6113        // Add built-in program accounts to the bank if they don't already exist
6114        self.add_builtin_program_accounts();
6115
6116        self.apply_activated_features();
6117    }
6118
6119    /// SIMD-0550: double the taper, re-anchoring `initial` so the inflation
6120    /// rate stays continuous at the point of activation.
6121    fn apply_double_disinflation_rate(&mut self) {
6122        let year = self.slot_in_year_for_inflation();
6123        let mut inflation = *self.inflation.read().unwrap();
6124        let anchor_rate = inflation.total(year);
6125        let taper = feature_set::double_disinflation_rate::TAPER;
6126        inflation.taper = taper;
6127        inflation.initial = anchor_rate / (1.0 - taper).powf(year);
6128        // The lock is shared with parent and sibling banks; replace it instead
6129        // of writing through it so every boundary bank anchors off the
6130        // pre-activation schedule and other forks never observe the change.
6131        self.inflation = Arc::new(RwLock::new(inflation));
6132    }
6133
6134    /// Compute and apply all activated features but do not add built-in
6135    /// accounts because we shouldn't modify accounts db for a completed bank
6136    fn compute_and_apply_features_after_snapshot_restore(&mut self) {
6137        // Update the feature set to include all features active at this slot
6138        let feature_set = self.compute_active_feature_set(false).0;
6139        self.feature_set = Arc::new(feature_set);
6140
6141        self.apply_activated_features();
6142        self.assert_bank_matches_slot_params();
6143    }
6144
6145    /// This is called from each epoch boundary
6146    fn compute_and_apply_new_feature_activations(&mut self) {
6147        let include_pending = true;
6148        let (feature_set, new_feature_activations) =
6149            self.compute_active_feature_set(include_pending);
6150        self.feature_set = Arc::new(feature_set);
6151        self.refresh_slot_params();
6152
6153        // Update activation slot of features in `new_feature_activations`
6154        for feature_id in new_feature_activations.iter() {
6155            if let Some(mut account) = self.get_account_with_fixed_root(feature_id)
6156                && let Some(mut feature) = feature::state::from_account(&account)
6157            {
6158                feature.activated_at = Some(self.slot());
6159                if feature::state::to_account(&feature, &mut account).is_some() {
6160                    self.store_account(feature_id, &account);
6161                }
6162                info!("Feature {} activated at slot {}", feature_id, self.slot());
6163            }
6164        }
6165
6166        // Update active set of reserved account keys which are not allowed to be write locked
6167        self.reserved_account_keys = {
6168            let mut reserved_keys = ReservedAccountKeys::clone(&self.reserved_account_keys);
6169            reserved_keys.update_active_set(&self.feature_set);
6170            Arc::new(reserved_keys)
6171        };
6172
6173        if new_feature_activations.contains(&feature_set::deprecate_rent_exemption_threshold::id())
6174        {
6175            self.rent_collector.deprecate_rent_exemption_threshold();
6176            self.update_rent();
6177        }
6178
6179        // SIMD-0437 feature gates: all assume rent exemption threshold has been deprecated
6180        // (SIMD-0194), so rent.lamports_per_byte can be set directly. These gates are
6181        // expected to activate in order; if multiple activate in one epoch, the lowest
6182        // activated lamports_per_byte value will be used. If features are activated out of
6183        // order, the most recently activated value will be used.
6184        let rent_feature_gates = [
6185            (
6186                feature_set::set_lamports_per_byte_to_6333::id(),
6187                feature_set::set_lamports_per_byte_to_6333::LAMPORTS_PER_BYTE,
6188            ),
6189            (
6190                feature_set::set_lamports_per_byte_to_5080::id(),
6191                feature_set::set_lamports_per_byte_to_5080::LAMPORTS_PER_BYTE,
6192            ),
6193            (
6194                feature_set::set_lamports_per_byte_to_2575::id(),
6195                feature_set::set_lamports_per_byte_to_2575::LAMPORTS_PER_BYTE,
6196            ),
6197            (
6198                feature_set::set_lamports_per_byte_to_1322::id(),
6199                feature_set::set_lamports_per_byte_to_1322::LAMPORTS_PER_BYTE,
6200            ),
6201            (
6202                feature_set::set_lamports_per_byte_to_696::id(),
6203                feature_set::set_lamports_per_byte_to_696::LAMPORTS_PER_BYTE,
6204            ),
6205        ];
6206        for (feature_id, lamports_per_byte) in rent_feature_gates {
6207            if new_feature_activations.contains(&feature_id) {
6208                self.rent_collector.rent.lamports_per_byte = lamports_per_byte;
6209                self.update_rent();
6210            }
6211        }
6212
6213        // SIMD-0438 feature gate: reset lamports per byte to legacy value of 6960. Safeguard
6214        // intended to be activated if rent reduction causes issues in the cluster.
6215        // Note: if this is activated in the same epoch as a 437 feature gate (above), the
6216        // safeguard must override it.
6217        if new_feature_activations.contains(&feature_set::set_lamports_per_byte_to_6960::id()) {
6218            self.rent_collector.rent.lamports_per_byte =
6219                feature_set::set_lamports_per_byte_to_6960::LAMPORTS_PER_BYTE;
6220            self.update_rent();
6221        }
6222
6223        if new_feature_activations.contains(&feature_set::pico_inflation::id()) {
6224            *self.inflation.write().unwrap() = Inflation::pico();
6225            self.fee_rate_governor.burn_percent = solana_fee_calculator::DEFAULT_BURN_PERCENT;
6226        }
6227
6228        if !new_feature_activations.is_disjoint(&self.feature_set.full_inflation_features_enabled())
6229        {
6230            *self.inflation.write().unwrap() = Inflation::full();
6231            self.fee_rate_governor.burn_percent = solana_fee_calculator::DEFAULT_BURN_PERCENT;
6232        }
6233
6234        if new_feature_activations.contains(&feature_set::double_disinflation_rate::id()) {
6235            self.apply_double_disinflation_rate();
6236        }
6237
6238        // Apply unconditionally: this is relatively cheap and idempotent.
6239        self.apply_slot_time_persistent_changes();
6240        self.apply_slot_time_runtime_changes();
6241
6242        self.apply_new_builtin_program_feature_transitions(&new_feature_activations);
6243
6244        if new_feature_activations.contains(&feature_set::replace_spl_token_with_p_token::id())
6245            && let Err(e) = self.upgrade_loader_v2_program_with_loader_v3_program(
6246                &feature_set::replace_spl_token_with_p_token::SPL_TOKEN_PROGRAM_ID,
6247                &feature_set::replace_spl_token_with_p_token::PTOKEN_PROGRAM_BUFFER,
6248                self.feature_set
6249                    .snapshot()
6250                    .relax_programdata_account_check_migration,
6251                "replace_spl_token_with_p_token",
6252            )
6253        {
6254            warn!(
6255                "Failed to replace SPL Token with p-token buffer '{}': {e}",
6256                feature_set::replace_spl_token_with_p_token::PTOKEN_PROGRAM_BUFFER,
6257            );
6258        }
6259
6260        if new_feature_activations.contains(&feature_set::upgrade_bpf_stake_program_to_v5::id())
6261            && let Err(e) = self.upgrade_core_bpf_program(
6262                &solana_sdk_ids::stake::id(),
6263                &feature_set::upgrade_bpf_stake_program_to_v5::buffer::id(),
6264                "upgrade_stake_program_to_v5",
6265            )
6266        {
6267            error!("Failed to upgrade Core BPF Stake program: {e}");
6268        }
6269
6270        if new_feature_activations.contains(&feature_set::upgrade_bpf_stake_program_to_v5_1::id())
6271            && let Err(e) = self.upgrade_core_bpf_program(
6272                &solana_sdk_ids::stake::id(),
6273                &feature_set::upgrade_bpf_stake_program_to_v5_1::buffer::id(),
6274                "upgrade_stake_program_to_v5_1",
6275            )
6276        {
6277            error!("Failed to upgrade Core BPF Stake program: {e}");
6278        }
6279    }
6280
6281    fn apply_new_builtin_program_feature_transitions(
6282        &mut self,
6283        new_feature_activations: &AHashSet<Pubkey>,
6284    ) {
6285        for builtin in BUILTINS.iter() {
6286            if let Some(feature_id) = builtin.enable_feature_id
6287                && new_feature_activations.contains(&feature_id)
6288            {
6289                self.add_builtin(
6290                    builtin.program_id,
6291                    builtin.name,
6292                    ProgramCacheEntry::new_builtin(
6293                        self.feature_set.activated_slot(&feature_id).unwrap_or(0),
6294                        builtin.register_fn,
6295                    ),
6296                );
6297            }
6298
6299            if let Some(core_bpf_migration_config) = &builtin.core_bpf_migration_config {
6300                // If the builtin is set to be migrated to Core BPF on feature
6301                // activation, perform the migration which will remove it from
6302                // the builtins list and the cache.
6303                if new_feature_activations.contains(&core_bpf_migration_config.feature_id)
6304                    && let Err(e) = self.migrate_builtin_to_core_bpf(
6305                        &builtin.program_id,
6306                        core_bpf_migration_config,
6307                        self.feature_set
6308                            .snapshot()
6309                            .relax_programdata_account_check_migration,
6310                    )
6311                {
6312                    warn!(
6313                        "Failed to migrate builtin {} to Core BPF: {}",
6314                        builtin.name, e
6315                    );
6316                }
6317            };
6318        }
6319
6320        // Migrate any necessary stateless builtins to core BPF.
6321        // Stateless builtins do not have an `enable_feature_id` since they
6322        // do not exist on-chain.
6323        for stateless_builtin in STATELESS_BUILTINS.iter() {
6324            if let Some(core_bpf_migration_config) = &stateless_builtin.core_bpf_migration_config
6325                && new_feature_activations.contains(&core_bpf_migration_config.feature_id)
6326                && let Err(e) = self.migrate_builtin_to_core_bpf(
6327                    &stateless_builtin.program_id,
6328                    core_bpf_migration_config,
6329                    self.feature_set
6330                        .snapshot()
6331                        .relax_programdata_account_check_migration,
6332                )
6333            {
6334                warn!(
6335                    "Failed to migrate stateless builtin {} to Core BPF: {}",
6336                    stateless_builtin.name, e
6337                );
6338            }
6339        }
6340
6341        for precompile in get_precompiles() {
6342            if let Some(feature_id) = &precompile.feature
6343                && new_feature_activations.contains(feature_id)
6344            {
6345                self.add_precompile(&precompile.program_id);
6346            }
6347        }
6348    }
6349
6350    fn adjust_sysvar_balance_for_rent(&self, account: &mut AccountSharedData) {
6351        account.set_lamports(
6352            self.get_minimum_balance_for_rent_exemption(account.data().len())
6353                .max(account.lamports()),
6354        );
6355    }
6356
6357    /// Compute the active feature set based on the current bank state,
6358    /// and return it together with the set of newly activated features.
6359    fn compute_active_feature_set(&self, include_pending: bool) -> (FeatureSet, AHashSet<Pubkey>) {
6360        let mut active = self.feature_set.active().clone();
6361        let mut inactive = AHashSet::new();
6362        let mut pending = AHashSet::new();
6363        let slot = self.slot();
6364
6365        for feature_id in self.feature_set.inactive() {
6366            let mut activated = None;
6367            if let Some(account) = self.get_account_with_fixed_root(feature_id)
6368                && let Some(feature) = feature::state::from_account(&account)
6369            {
6370                match feature.activated_at {
6371                    None if include_pending => {
6372                        // Feature activation is pending
6373                        pending.insert(*feature_id);
6374                        activated = Some(slot);
6375                    }
6376                    Some(activation_slot) if slot >= activation_slot => {
6377                        // Feature has been activated already
6378                        activated = Some(activation_slot);
6379                    }
6380                    _ => {}
6381                }
6382            }
6383            if let Some(slot) = activated {
6384                active.insert(*feature_id, slot);
6385            } else {
6386                inactive.insert(*feature_id);
6387            }
6388        }
6389
6390        (FeatureSet::new(active, inactive), pending)
6391    }
6392
6393    /// If `feature_id` is pending to be activated at the next epoch boundary, return
6394    /// the first slot at which it will be active (the epoch boundary).
6395    pub fn compute_pending_activation_slot(&self, feature_id: &Pubkey) -> Option<Slot> {
6396        let account = self.get_account_with_fixed_root(feature_id)?;
6397        let feature = feature::from_account(&account)?;
6398        if feature.activated_at.is_some() {
6399            // Feature is already active
6400            return None;
6401        }
6402        // Feature will be active at the next epoch boundary
6403        let active_epoch = self.epoch + 1;
6404        Some(self.epoch_schedule.get_first_slot_in_epoch(active_epoch))
6405    }
6406
6407    fn add_active_builtin_programs(&mut self) {
6408        for builtin in BUILTINS.iter() {
6409            // The `builtin_is_bpf` flag is used to handle the case where a
6410            // builtin is scheduled to be enabled by one feature gate and
6411            // later migrated to Core BPF by another.
6412            //
6413            // There should never be a case where a builtin is set to be
6414            // migrated to Core BPF and is also set to be enabled on feature
6415            // activation on the same feature gate. However, the
6416            // `builtin_is_bpf` flag will handle this case as well, electing
6417            // to first attempt the migration to Core BPF.
6418            //
6419            // The migration to Core BPF will fail gracefully because the
6420            // program account will not exist. The builtin will subsequently
6421            // be enabled, but it will never be migrated to Core BPF.
6422            //
6423            // Using the same feature gate for both enabling and migrating a
6424            // builtin to Core BPF should be strictly avoided.
6425            let builtin_is_bpf = builtin.core_bpf_migration_config.is_some() && {
6426                self.get_account(&builtin.program_id)
6427                    .map(|a| a.owner() == &bpf_loader_upgradeable::id())
6428                    .unwrap_or(false)
6429            };
6430
6431            // If the builtin has already been migrated to Core BPF, do not
6432            // add it to the bank's builtins.
6433            if builtin_is_bpf {
6434                continue;
6435            }
6436
6437            let builtin_is_active = builtin
6438                .enable_feature_id
6439                .map(|feature_id| self.feature_set.is_active(&feature_id))
6440                .unwrap_or(true);
6441
6442            if builtin_is_active {
6443                let activation_slot = builtin
6444                    .enable_feature_id
6445                    .and_then(|feature_id| self.feature_set.activated_slot(&feature_id))
6446                    .unwrap_or(0);
6447                self.transaction_processor.add_builtin(
6448                    builtin.program_id,
6449                    ProgramCacheEntry::new_builtin(activation_slot, builtin.register_fn),
6450                );
6451            }
6452        }
6453    }
6454
6455    fn add_builtin_program_accounts(&mut self) {
6456        for builtin in BUILTINS.iter() {
6457            // The `builtin_is_bpf` flag is used to handle the case where a
6458            // builtin is scheduled to be enabled by one feature gate and
6459            // later migrated to Core BPF by another.
6460            //
6461            // There should never be a case where a builtin is set to be
6462            // migrated to Core BPF and is also set to be enabled on feature
6463            // activation on the same feature gate. However, the
6464            // `builtin_is_bpf` flag will handle this case as well, electing
6465            // to first attempt the migration to Core BPF.
6466            //
6467            // The migration to Core BPF will fail gracefully because the
6468            // program account will not exist. The builtin will subsequently
6469            // be enabled, but it will never be migrated to Core BPF.
6470            //
6471            // Using the same feature gate for both enabling and migrating a
6472            // builtin to Core BPF should be strictly avoided.
6473            let builtin_is_bpf = builtin.core_bpf_migration_config.is_some() && {
6474                self.get_account(&builtin.program_id)
6475                    .map(|a| a.owner() == &bpf_loader_upgradeable::id())
6476                    .unwrap_or(false)
6477            };
6478
6479            // If the builtin has already been migrated to Core BPF, do not
6480            // add it to the bank's builtins.
6481            if builtin_is_bpf {
6482                continue;
6483            }
6484
6485            let builtin_is_active = builtin
6486                .enable_feature_id
6487                .map(|feature_id| self.feature_set.is_active(&feature_id))
6488                .unwrap_or(true);
6489
6490            if builtin_is_active {
6491                self.add_builtin_account(builtin.name, &builtin.program_id);
6492            }
6493        }
6494
6495        for precompile in get_precompiles() {
6496            let precompile_is_active = precompile
6497                .feature
6498                .as_ref()
6499                .map(|feature_id| self.feature_set.is_active(feature_id))
6500                .unwrap_or(true);
6501
6502            if precompile_is_active {
6503                self.add_precompile(&precompile.program_id);
6504            }
6505        }
6506    }
6507
6508    /// Calculates the accounts data size of all accounts
6509    ///
6510    /// Panics if total overflows a u64.
6511    ///
6512    /// Note, this may be *very* expensive, as *all* accounts are accessed.
6513    ///
6514    /// Only intended to be called by tests or when the number of accounts is small.
6515    pub fn calculate_accounts_data_size(&self) -> ScanResult<u64> {
6516        let mut accounts_data_size: u64 = 0;
6517        self.scan_all_accounts(|address_account_slot| {
6518            let Some((_address, account, _slot)) = address_account_slot else {
6519                return;
6520            };
6521            accounts_data_size = accounts_data_size
6522                .checked_add(account.data().len() as u64)
6523                .expect("accounts data size cannot overflow");
6524        })?;
6525        Ok(accounts_data_size)
6526    }
6527
6528    pub fn is_in_slot_hashes_history(&self, slot: &Slot) -> bool {
6529        if slot < &self.slot
6530            && let Ok(slot_hashes) = self.transaction_processor.sysvar_cache().get_slot_hashes()
6531        {
6532            return slot_hashes.get(slot).is_some();
6533        }
6534        false
6535    }
6536
6537    pub fn check_program_deployment_slot(&self) -> bool {
6538        self.check_program_deployment_slot
6539    }
6540
6541    pub fn set_check_program_deployment_slot(&mut self, check: bool) {
6542        self.check_program_deployment_slot = check;
6543    }
6544
6545    pub fn fee_structure(&self) -> &FeeStructure {
6546        &self.fee_structure
6547    }
6548
6549    pub fn parent_block_id(&self) -> Option<Hash> {
6550        self.parent().and_then(|p| p.block_id())
6551    }
6552
6553    pub fn block_id(&self) -> Option<Hash> {
6554        *self.block_id.read().unwrap()
6555    }
6556
6557    pub fn set_block_id(&self, block_id: Option<Hash>) {
6558        let mut block_id_w = self.block_id.write().unwrap();
6559        debug_assert!(block_id_w.is_none() || *block_id_w == block_id);
6560        *block_id_w = block_id
6561    }
6562
6563    pub fn compute_budget(&self) -> Option<ComputeBudget> {
6564        self.compute_budget
6565    }
6566
6567    pub fn add_builtin(&self, program_id: Pubkey, name: &str, builtin: ProgramCacheEntry) {
6568        debug!("Adding program {name} under {program_id:?}");
6569        self.add_builtin_account(name, &program_id);
6570        self.transaction_processor.add_builtin(program_id, builtin);
6571        debug!("Added program {name} under {program_id:?}");
6572    }
6573
6574    // NOTE: must hold idempotent for the same set of arguments
6575    /// Add a builtin program account
6576    fn add_builtin_account(&self, name: &str, program_id: &Pubkey) {
6577        let existing_genuine_program =
6578            self.get_account_with_fixed_root(program_id)
6579                .and_then(|account| {
6580                    // it's very unlikely to be squatted at program_id as non-system account because of burden to
6581                    // find victim's pubkey/hash. So, when account.owner is indeed native_loader's, it's
6582                    // safe to assume it's a genuine program.
6583                    if native_loader::check_id(account.owner()) {
6584                        Some(account)
6585                    } else {
6586                        // malicious account is pre-occupying at program_id
6587                        self.burn_and_purge_account(program_id, account);
6588                        None
6589                    }
6590                });
6591
6592        // introducing builtin program
6593        if existing_genuine_program.is_some() {
6594            // The existing account is sufficient
6595            return;
6596        }
6597
6598        assert!(
6599            !self.freeze_started(),
6600            "Can't change frozen bank by adding not-existing new builtin program ({name}, \
6601             {program_id}). Maybe, inconsistent program activation is detected on snapshot \
6602             restore?"
6603        );
6604
6605        // Add a bogus executable builtin account, which will be loaded and ignored.
6606        let (lamports, rent_epoch) =
6607            self.inherit_specially_retained_account_fields(&existing_genuine_program);
6608        let account: AccountSharedData = AccountSharedData::from(Account {
6609            lamports,
6610            data: name.as_bytes().to_vec(),
6611            owner: solana_sdk_ids::native_loader::id(),
6612            executable: true,
6613            rent_epoch,
6614        });
6615        self.store_account_and_update_capitalization(program_id, &account);
6616    }
6617
6618    pub fn get_bank_hash_stats(&self) -> BankHashStats {
6619        self.bank_hash_stats.load()
6620    }
6621
6622    pub fn clear_epoch_rewards_cache(&self) {
6623        self.epoch_rewards_calculation_cache.lock().unwrap().clear();
6624    }
6625
6626    /// Sets the accounts lt hash, only to be used by SnapshotMinimizer
6627    pub fn set_accounts_lt_hash_for_snapshot_minimizer(&self, accounts_lt_hash: AccountsLtHash) {
6628        *self.accounts_lt_hash.lock().unwrap() = accounts_lt_hash;
6629    }
6630
6631    /// Return total transaction fee collected
6632    pub fn get_collector_fee_details(&self) -> CollectorFeeDetails {
6633        self.collector_fee_details.read().unwrap().clone()
6634    }
6635
6636    /// Minimum balance a vote account must hold to survive SIMD-0357 filtering
6637    /// under the current feature set. When `alpenglow` is active the threshold
6638    /// also includes one epoch's worth of VAT burn.
6639    pub fn minimum_vote_account_balance_for_vat(&self) -> u64 {
6640        let vote_account_rent_exempt_minimum = self
6641            .rent_collector
6642            .rent
6643            .minimum_balance(VoteStateV4::size_of());
6644        if self.feature_set.snapshot().alpenglow {
6645            vote_account_rent_exempt_minimum + self.vat_to_burn_per_epoch()
6646        } else {
6647            vote_account_rent_exempt_minimum
6648        }
6649    }
6650
6651    /// Returns the `Stakes` as filtered by SIMD-0357
6652    /// See `VoteAccounts::clone_and_filter_for_vat` for the full criteria
6653    pub fn get_top_epoch_stakes(&self) -> Stakes<StakeAccount<Delegation>> {
6654        self.stakes_cache.stakes().clone_and_filter_for_vat(
6655            MAX_ALPENGLOW_VOTE_ACCOUNTS,
6656            self.minimum_vote_account_balance_for_vat(),
6657        )
6658    }
6659
6660    /// Calculates and sets block id for `bank`.
6661    ///
6662    /// This fn operates recursively. Since calculating the block id requires
6663    /// the bank's parent's block id, if the bank's parent's block id is unset,
6664    /// it will be calculated and set first.
6665    ///
6666    /// Note this fn will also freeze `bank`.
6667    ///
6668    /// Only to be called from dev contexts.
6669    /// Couldn't make the fn actually DCOU, since it is called by
6670    /// Validator::new() when warping a slot.
6671    pub fn calculate_and_set_block_id_for_dcou(bank: &Bank) {
6672        if bank.block_id().is_some() {
6673            // done!
6674            return;
6675        }
6676
6677        let Some(parent) = bank.parent() else {
6678            // If bank doesn't have a parent, then use bank hash for block id,
6679            // as parent's block id is not available for the calculation below.
6680            // Must freeze() to ensure bank hash has been calculated.
6681            bank.freeze();
6682            bank.set_block_id(Some(bank.hash()));
6683            return;
6684        };
6685
6686        let parent_block_id = parent.block_id().unwrap_or_else(|| {
6687            // if the parent's block id isn't set, we recurse so it gets set
6688            Self::calculate_and_set_block_id_for_dcou(&parent);
6689            parent.block_id().unwrap()
6690        });
6691
6692        // must freeze() to ensure bank hash has been calculated
6693        bank.freeze();
6694        let block_id =
6695            solana_sha256_hasher::hashv(&[parent_block_id.as_ref(), bank.hash().as_ref()]);
6696        bank.set_block_id(Some(block_id));
6697    }
6698
6699    pub(crate) fn get_alpenglow_migration_slot(&self) -> Option<Slot> {
6700        let genesis_cert = self.get_alpenglow_genesis_certificate()?;
6701        Some(genesis_cert.block.slot)
6702    }
6703}
6704
6705impl InvokeContextCallback for Bank {
6706    fn get_epoch_stake(&self) -> u64 {
6707        self.get_current_epoch_total_stake()
6708    }
6709
6710    fn get_epoch_stake_for_vote_account(&self, vote_address: &Pubkey) -> u64 {
6711        self.get_current_epoch_vote_accounts()
6712            .get(vote_address)
6713            .map(|(stake, _)| *stake)
6714            .unwrap_or(0)
6715    }
6716
6717    fn is_precompile(&self, program_id: &Pubkey) -> bool {
6718        is_precompile(program_id, |feature_id: &Pubkey| {
6719            self.feature_set.is_active(feature_id)
6720        })
6721    }
6722
6723    fn process_precompile(
6724        &self,
6725        program_id: &Pubkey,
6726        data: &[u8],
6727        instruction_datas: Vec<&[u8]>,
6728    ) -> std::result::Result<(), PrecompileError> {
6729        if let Some(precompile) = get_precompile(program_id, |feature_id: &Pubkey| {
6730            self.feature_set.is_active(feature_id)
6731        }) {
6732            precompile.verify(data, &instruction_datas, &self.feature_set)
6733        } else {
6734            Err(PrecompileError::InvalidPublicKey)
6735        }
6736    }
6737}
6738
6739impl TransactionProcessingCallback for Bank {
6740    fn get_account_shared_data(&self, pubkey: &Pubkey) -> Option<(AccountSharedData, Slot)> {
6741        self.rc
6742            .accounts
6743            .load_with_fixed_root(&self.ancestors, pubkey)
6744    }
6745
6746    fn inspect_account(&self, _address: &Pubkey, _account_state: AccountState, _is_writable: bool) {
6747        // nothing to do here
6748    }
6749}
6750
6751impl fmt::Debug for Bank {
6752    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6753        f.debug_struct("Bank")
6754            .field("slot", &self.slot)
6755            .field("bank_id", &self.bank_id)
6756            .field("block_height", &self.block_height)
6757            .field("parent_slot", &self.parent_slot)
6758            .field("capitalization", &self.capitalization())
6759            .finish_non_exhaustive()
6760    }
6761}
6762
6763#[cfg(feature = "dev-context-only-utils")]
6764impl Bank {
6765    /// Shared bank constructor used by `new_for_txn_tests` and
6766    /// `new_for_block_tests`. Builds only the `Bank` struct from deserialized
6767    /// fields with the supplied `leader`, `stakes_cache`, and
6768    /// `accounts_data_size_initial`. All post-init (feature application,
6769    /// sysvar cache fill, partitioned rewards recalc,
6770    /// `prepare_for_block_execution`, etc.) is the caller's responsibility.
6771    fn new_from_fields_for_tests(
6772        bank_rc: BankRc,
6773        fields: BankFieldsToDeserialize,
6774        feature_set: FeatureSet,
6775        epoch_stakes: HashMap<Epoch, VersionedEpochStakes>,
6776        leader: SlotLeader,
6777        stakes_cache: StakesCache,
6778        accounts_data_size_initial: u64,
6779    ) -> Self {
6780        let slot = fields.slot;
6781        let epoch = fields.epoch_schedule.get_epoch(slot);
6782        let ancestors = Ancestors::from(vec![slot]);
6783        let rent = Self::load_rent_from_account_for_snapshot_load(&bank_rc.accounts, &ancestors);
6784
6785        let accounts = Accounts::new(Arc::clone(&bank_rc.accounts.accounts_db));
6786        let mut bank = Self::default_with_accounts(accounts);
6787
6788        bank.rc = bank_rc;
6789        bank.blockhash_queue = RwLock::new(fields.blockhash_queue);
6790        bank.ancestors = ancestors;
6791        bank.hash = RwLock::new(fields.hash);
6792        bank.parent_hash = fields.parent_hash;
6793        bank.parent_slot = fields.parent_slot;
6794        bank.hard_forks = Arc::new(RwLock::new(fields.hard_forks));
6795        bank.transaction_count = AtomicU64::new(fields.transaction_count);
6796        bank.tick_height = AtomicU64::new(fields.tick_height);
6797        bank.signature_count = AtomicU64::new(fields.signature_count);
6798        bank.capitalization = AtomicU64::new(fields.capitalization);
6799        bank.max_tick_height = fields.max_tick_height;
6800        bank.hashes_per_tick = RwLock::new(fields.hashes_per_tick);
6801        bank.ticks_per_slot = fields.ticks_per_slot;
6802        bank.ns_per_slot = fields.ns_per_slot;
6803        bank.genesis_creation_time = fields.genesis_creation_time;
6804        bank.slots_per_year = fields.slots_per_year;
6805        bank.slot = slot;
6806        bank.epoch = epoch;
6807        bank.block_height = fields.block_height;
6808        bank.leader = leader;
6809        bank.fee_rate_governor = fields.fee_rate_governor;
6810        bank.rent_collector = RentCollector::new(
6811            epoch,
6812            fields.epoch_schedule.clone(),
6813            fields.slots_per_year,
6814            rent,
6815        );
6816        bank.epoch_schedule = fields.epoch_schedule;
6817        bank.inflation = Arc::new(RwLock::new(fields.inflation));
6818        bank.stakes_cache = stakes_cache;
6819        bank.epoch_stakes = epoch_stakes;
6820        bank.is_delta = AtomicBool::new(fields.is_delta);
6821        bank.cluster_type = Some(ClusterType::Development);
6822        bank.feature_set = Arc::new(feature_set);
6823        bank.freeze_started = AtomicBool::new(fields.hash != Hash::default());
6824        bank.accounts_data_size_initial = accounts_data_size_initial;
6825        bank.transaction_processor = TransactionBatchProcessor::new_uninitialized(slot, epoch);
6826        bank.accounts_lt_hash = Mutex::new(fields.accounts_lt_hash);
6827        bank.bank_hash_stats = AtomicBankHashStats::new(&fields.bank_hash_stats);
6828        bank.refresh_slot_params_with_baseline(SlotParams::genesis_baseline(
6829            bank.ns_per_slot,
6830            bank.slots_per_year,
6831            bank.hashes_per_tick(),
6832            bank.partitioned_rewards_stake_account_stores_per_block,
6833        ));
6834
6835        bank
6836    }
6837
6838    /// Create a bank for transaction testing. Constructs the bank struct,
6839    /// applies activated features, and fills missing sysvar cache entries.
6840    /// Skips block-level setup (`prepare_for_block_execution`, partitioned
6841    /// rewards recalc) and snapshot fields (stakes loading, debug keys,
6842    /// accounts data size) that are irrelevant to individual transaction
6843    /// execution.
6844    ///
6845    /// **Important:** The returned bank must be inserted into a
6846    /// [`BankForks`] before calling `load_and_execute_transactions`,
6847    /// because the program cache requires a `ForkGraph` to be present.
6848    pub fn new_for_txn_tests(
6849        bank_rc: BankRc,
6850        fields: BankFieldsToDeserialize,
6851        feature_set: FeatureSet,
6852        epoch_stakes: HashMap<Epoch, VersionedEpochStakes>,
6853    ) -> Self {
6854        let leader = SlotLeader {
6855            id: fields.leader_id,
6856            vote_address: Pubkey::default(),
6857        };
6858        let mut bank = Self::new_from_fields_for_tests(
6859            bank_rc,
6860            fields,
6861            feature_set,
6862            epoch_stakes,
6863            leader,
6864            StakesCache::default(), /* Irrelevant for txn tests */
6865            0,                      /* Irrelevant to txn execution */
6866        );
6867
6868        bank.apply_activated_features();
6869        bank.transaction_processor
6870            .fill_missing_sysvar_cache_entries(&bank);
6871
6872        bank
6873    }
6874
6875    /// Create a bank for block testing. Constructs the bank struct,
6876    /// applies activated features, recalculates partitioned rewards if
6877    /// mid-distribution, and runs `prepare_for_block_execution` to
6878    /// complete the `_new_from_parent`-equivalent initialization
6879    /// (epoch processing, sysvar updates, LT hash cache).
6880    ///
6881    /// **Important:** The returned bank must be inserted into a
6882    /// [`BankForks`] before calling `load_and_execute_transactions`,
6883    /// because the program cache requires a `ForkGraph` to be present.
6884    pub fn new_for_block_tests(
6885        bank_rc: BankRc,
6886        fields: BankFieldsToDeserialize,
6887        feature_set: FeatureSet,
6888        epoch_stakes: HashMap<Epoch, VersionedEpochStakes>,
6889        stakes: Stakes<StakeAccount<Delegation>>,
6890        accounts_data_size_initial: u64,
6891    ) -> Self {
6892        let parent_epoch = fields.epoch_schedule.get_epoch(fields.parent_slot);
6893        let parent_capitalization = fields.capitalization;
6894        let leader =
6895            Self::slot_leader_from_epoch_stakes(fields.slot, &fields.epoch_schedule, &epoch_stakes);
6896
6897        let mut bank = Self::new_from_fields_for_tests(
6898            bank_rc,
6899            fields,
6900            feature_set,
6901            epoch_stakes,
6902            leader,
6903            StakesCache::new(stakes),
6904            accounts_data_size_initial,
6905        );
6906
6907        bank.apply_activated_features();
6908        bank.stakes_cache.refresh_delegated_stakes(
6909            bank.new_warmup_cooldown_rate_epoch(),
6910            bank.use_fixed_point_stake_math(),
6911        );
6912
6913        // If booting mid-distribution, recalculate reward partitions from the
6914        // EpochRewards sysvar (mirrors initialize_after_snapshot_restore).
6915        bank.recalculate_partitioned_rewards_if_active(|| {
6916            rayon::ThreadPoolBuilder::new()
6917                .num_threads(1)
6918                .build()
6919                .expect("single-threaded rayon pool")
6920        });
6921
6922        bank.prepare_for_block_execution(
6923            parent_epoch,
6924            bank.parent_slot,
6925            parent_capitalization,
6926            bank.block_height.saturating_sub(1),
6927            null_tracer(),
6928        );
6929
6930        bank
6931    }
6932
6933    pub fn wrap_with_bank_forks_for_tests(self) -> (Arc<Self>, Arc<RwLock<BankForks>>) {
6934        let bank_forks = BankForks::new_rw_arc(self);
6935        let bank = bank_forks.read().unwrap().root_bank();
6936        (bank, bank_forks)
6937    }
6938
6939    pub fn default_for_tests() -> Self {
6940        let accounts_db = AccountsDb::default_for_tests();
6941        let accounts = Accounts::new(Arc::new(accounts_db));
6942        Self::default_with_accounts(accounts)
6943    }
6944
6945    pub fn new_with_bank_forks_for_tests(
6946        genesis_config: &GenesisConfig,
6947    ) -> (Arc<Self>, Arc<RwLock<BankForks>>) {
6948        let bank = Self::new_for_tests(genesis_config);
6949        bank.wrap_with_bank_forks_for_tests()
6950    }
6951
6952    pub fn new_for_tests(genesis_config: &GenesisConfig) -> Self {
6953        Self::new_with_paths_for_tests(genesis_config, None, vec![], None)
6954    }
6955
6956    pub fn new_with_mockup_builtin_for_tests(
6957        genesis_config: &GenesisConfig,
6958        program_id: Pubkey,
6959        builtin: BuiltinFunctionRegisterer,
6960    ) -> (Arc<Self>, Arc<RwLock<BankForks>>) {
6961        let mut bank = Self::new_for_tests(genesis_config);
6962        bank.add_mockup_builtin(program_id, builtin);
6963        bank.wrap_with_bank_forks_for_tests()
6964    }
6965
6966    pub fn new_with_paths_for_tests(
6967        genesis_config: &GenesisConfig,
6968        test_config: Option<BankTestConfig>,
6969        paths: Vec<PathBuf>,
6970        leader: Option<SlotLeader>,
6971    ) -> Self {
6972        let test_config = test_config.unwrap_or_default();
6973        let mut bank = Self::new_from_genesis(
6974            genesis_config,
6975            Arc::new(RuntimeConfig::default()),
6976            paths,
6977            None,
6978            test_config.accounts_db_config,
6979            None,
6980            leader,
6981            Arc::default(),
6982            None,
6983            None,
6984        );
6985        // Keep test-bank fee structure aligned with the genesis fee configuration.
6986        bank.set_fee_structure(&FeeStructure {
6987            lamports_per_signature: genesis_config.fee_rate_governor.lamports_per_signature,
6988            ..FeeStructure::default()
6989        });
6990        bank
6991    }
6992
6993    pub fn new_for_benches(genesis_config: &GenesisConfig) -> Self {
6994        Self::new_with_paths_for_benches(genesis_config, Vec::new())
6995    }
6996
6997    /// Intended for use by benches only.
6998    /// create new bank with the given config and paths.
6999    pub fn new_with_paths_for_benches(genesis_config: &GenesisConfig, paths: Vec<PathBuf>) -> Self {
7000        Self::new_from_genesis(
7001            genesis_config,
7002            Arc::<RuntimeConfig>::default(),
7003            paths,
7004            None,
7005            ACCOUNTS_DB_CONFIG_FOR_BENCHMARKS,
7006            None,
7007            Some(SlotLeader::new_unique()),
7008            Arc::default(),
7009            None,
7010            None,
7011        )
7012    }
7013
7014    pub fn new_from_parent_with_bank_forks(
7015        bank_forks: &RwLock<BankForks>,
7016        parent: Arc<Bank>,
7017        leader: SlotLeader,
7018        slot: Slot,
7019    ) -> Arc<Self> {
7020        let bank = Bank::new_from_parent(parent, leader, slot);
7021        bank_forks
7022            .write()
7023            .unwrap()
7024            .insert(bank)
7025            .clone_without_scheduler()
7026    }
7027
7028    /// Prepare a transaction batch from a list of legacy transactions. Used for tests only.
7029    pub fn prepare_batch_for_tests(
7030        &self,
7031        txs: Vec<Transaction>,
7032    ) -> TransactionBatch<'_, '_, RuntimeTransaction<SanitizedTransaction>> {
7033        let sanitized_txs = txs
7034            .into_iter()
7035            .map(RuntimeTransaction::from_transaction_for_tests)
7036            .collect::<Vec<_>>();
7037        TransactionBatch::new(
7038            self.try_lock_accounts(&sanitized_txs),
7039            self,
7040            OwnedOrBorrowed::Owned(sanitized_txs),
7041        )
7042    }
7043
7044    /// Set the initial accounts data size
7045    /// NOTE: This fn is *ONLY FOR TESTS*
7046    pub fn set_accounts_data_size_initial_for_tests(&mut self, amount: u64) {
7047        self.accounts_data_size_initial = amount;
7048    }
7049
7050    /// Update the accounts data size off-chain delta
7051    /// NOTE: This fn is *ONLY FOR TESTS*
7052    pub fn update_accounts_data_size_delta_off_chain_for_tests(&self, amount: i64) {
7053        self.update_accounts_data_size_delta_off_chain(amount)
7054    }
7055
7056    /// Process multiple transaction in a single batch. This is used for benches and unit tests.
7057    ///
7058    /// # Panics
7059    ///
7060    /// Panics if any of the transactions do not pass sanitization checks.
7061    #[must_use]
7062    pub fn process_transactions<'a>(
7063        &self,
7064        txs: impl Iterator<Item = &'a Transaction>,
7065    ) -> Vec<Result<()>> {
7066        self.try_process_transactions(txs).unwrap()
7067    }
7068
7069    /// Process entry transactions in a single batch. This is used for benches and unit tests.
7070    ///
7071    /// # Panics
7072    ///
7073    /// Panics if any of the transactions do not pass sanitization checks.
7074    #[must_use]
7075    pub fn process_entry_transactions(&self, txs: Vec<VersionedTransaction>) -> Vec<Result<()>> {
7076        self.try_process_entry_transactions(txs).unwrap()
7077    }
7078
7079    pub fn get_sysvar_cache_for_tests(&self) -> SysvarCache {
7080        self.transaction_processor.get_sysvar_cache_for_tests()
7081    }
7082
7083    pub fn calculate_accounts_lt_hash_for_tests(&self) -> AccountsLtHash {
7084        self.rc
7085            .accounts
7086            .accounts_db
7087            .calculate_accounts_lt_hash_at_startup_from_index(&self.ancestors)
7088    }
7089
7090    pub fn get_transaction_processor(&self) -> &TransactionBatchProcessor<BankForks> {
7091        &self.transaction_processor
7092    }
7093
7094    pub fn set_fee_structure(&mut self, fee_structure: &FeeStructure) {
7095        self.fee_structure = fee_structure.clone();
7096    }
7097
7098    pub fn load_program(
7099        &self,
7100        pubkey: &Pubkey,
7101        effective_epoch: Epoch,
7102    ) -> Option<Arc<ProgramCacheEntry>> {
7103        let environments = self
7104            .transaction_processor
7105            .program_runtime_environment_for_epoch(effective_epoch);
7106        load_program_with_pubkey(
7107            self,
7108            &environments,
7109            pubkey,
7110            self.slot(),
7111            &mut ExecuteTimings::default(), // Called by ledger-tool, metrics not accumulated.
7112        )
7113        .map(|(loaded_program, _last_modification_slot)| loaded_program)
7114    }
7115
7116    pub fn withdraw(&self, pubkey: &Pubkey, lamports: u64) -> Result<()> {
7117        match self.get_account_with_fixed_root(pubkey) {
7118            Some(mut account) => {
7119                let min_balance = match get_system_account_kind(&account) {
7120                    Some(SystemAccountKind::Nonce) => self
7121                        .rent_collector
7122                        .rent
7123                        .minimum_balance(nonce::state::State::size()),
7124                    _ => 0,
7125                };
7126
7127                lamports
7128                    .checked_add(min_balance)
7129                    .filter(|required_balance| *required_balance <= account.lamports())
7130                    .ok_or(TransactionError::InsufficientFundsForFee)?;
7131                account
7132                    .checked_sub_lamports(lamports)
7133                    .map_err(|_| TransactionError::InsufficientFundsForFee)?;
7134                self.store_account(pubkey, &account);
7135
7136                Ok(())
7137            }
7138            None => Err(TransactionError::AccountNotFound),
7139        }
7140    }
7141
7142    pub fn set_hash_overrides(&self, hash_overrides: HashOverrides) {
7143        *self.hash_overrides.lock().unwrap() = hash_overrides;
7144    }
7145
7146    /// Get stake and stake node accounts
7147    pub(crate) fn get_stake_accounts(&self, minimized_account_set: &DashSet<Pubkey>) {
7148        self.stakes_cache
7149            .stakes()
7150            .stake_delegations()
7151            .iter()
7152            .for_each(|(pubkey, _)| {
7153                minimized_account_set.insert(*pubkey);
7154            });
7155
7156        self.stakes_cache
7157            .stakes()
7158            .staked_nodes()
7159            .par_iter()
7160            .for_each(|(pubkey, _)| {
7161                minimized_account_set.insert(*pubkey);
7162            });
7163    }
7164
7165    /// Returns true when this bank is using slot params beyond its genesis baseline.
7166    pub fn slot_time_reduction_active(&self) -> bool {
7167        self.ns_per_slot != self.slot_params.baseline_params().ns_per_slot()
7168    }
7169}
7170
7171/// Returns a thread pool intended to be used for reward calculation. This
7172/// includes both crossing an epoch boundary and loading banks from snapshots.
7173///
7174/// # Performance
7175///
7176/// Initializing the thread pool takes 10ms. The first call to this function
7177/// initializes the thread pool, and subsequent calls re-use it. Make sure this
7178/// function is not called for the first time on a hot path, especially at an
7179/// epoch boundary.
7180pub(crate) fn rewards_calculation_thread_pool() -> &'static ThreadPool {
7181    static NEW_EPOCH_THREAD_POOL: OnceLock<ThreadPool> = OnceLock::new();
7182    NEW_EPOCH_THREAD_POOL.get_or_init(|| {
7183        rayon::ThreadPoolBuilder::new()
7184            .thread_name(|i| format!("solBnkClcRwds{i:02}"))
7185            .build()
7186            .expect("new epoch boundary rayon threadpool")
7187    })
7188}
7189
7190/// Compute how much an account has changed size.  This function is useful when the data size delta
7191/// needs to be computed and passed to an `update_accounts_data_size_delta` function.
7192fn calculate_data_size_delta(old_data_size: usize, new_data_size: usize) -> i64 {
7193    assert!(old_data_size <= i64::MAX as usize);
7194    assert!(new_data_size <= i64::MAX as usize);
7195    let old_data_size = old_data_size as i64;
7196    let new_data_size = new_data_size as i64;
7197
7198    new_data_size.saturating_sub(old_data_size)
7199}
7200
7201impl Drop for Bank {
7202    fn drop(&mut self) {
7203        if let Some(drop_callback) = self.drop_callback.read().unwrap().0.as_ref() {
7204            drop_callback.callback(self);
7205        } else {
7206            // Default case for tests
7207            self.rc
7208                .accounts
7209                .accounts_db
7210                .purge_slot(self.slot(), self.bank_id(), false);
7211        }
7212    }
7213}
7214
7215/// utility function used for testing and benchmarking.
7216pub mod test_utils {
7217    use {
7218        super::Bank,
7219        crate::installed_scheduler_pool::BankWithScheduler,
7220        solana_account::{ReadableAccount, WritableAccount, state_traits::StateMut},
7221        solana_instruction::error::LamportsError,
7222        solana_pubkey::Pubkey,
7223        solana_sha256_hasher::hashv,
7224        solana_vote_interface::state::VoteStateV4,
7225        solana_vote_program::vote_state::{BlockTimestamp, VoteStateVersions},
7226        std::sync::Arc,
7227    };
7228    pub fn goto_end_of_slot(bank: Arc<Bank>) {
7229        goto_end_of_slot_with_scheduler(&BankWithScheduler::new_without_scheduler(bank))
7230    }
7231
7232    pub fn goto_end_of_slot_with_scheduler(bank: &BankWithScheduler) {
7233        let mut tick_hash = bank.last_blockhash();
7234        loop {
7235            tick_hash = hashv(&[tick_hash.as_ref(), &[42]]);
7236            bank.register_tick(&tick_hash);
7237            if tick_hash == bank.last_blockhash() {
7238                bank.freeze();
7239                return;
7240            }
7241        }
7242    }
7243
7244    pub fn update_vote_account_timestamp(
7245        timestamp: BlockTimestamp,
7246        bank: &Bank,
7247        vote_pubkey: &Pubkey,
7248    ) {
7249        let mut vote_account = bank.get_account(vote_pubkey).unwrap_or_default();
7250        let mut vote_state = VoteStateV4::deserialize(vote_account.data(), vote_pubkey)
7251            .ok()
7252            .unwrap_or_default();
7253        vote_state.last_timestamp = timestamp;
7254        let versioned = VoteStateVersions::new_v4(vote_state);
7255        vote_account.set_state(&versioned).unwrap();
7256        bank.store_account(vote_pubkey, &vote_account);
7257    }
7258
7259    pub fn deposit(
7260        bank: &Bank,
7261        pubkey: &Pubkey,
7262        lamports: u64,
7263    ) -> std::result::Result<u64, LamportsError> {
7264        // This doesn't collect rents intentionally.
7265        // Rents should only be applied to actual TXes
7266        let mut account = bank
7267            .get_account_with_fixed_root_no_cache(pubkey)
7268            .unwrap_or_default();
7269        account.checked_add_lamports(lamports)?;
7270        bank.store_account(pubkey, &account);
7271        Ok(account.lamports())
7272    }
7273}