Skip to main content

cfx_executor/state/state_object/
mod.rs

1//! A caching and checkpoint layer built upon semantically meaningful database
2//! interfaces, providing interfaces and logics for managing accounts and global
3//! statistics to the execution engine.
4
5/// Contract Manager: Responsible for creating and deleting contract objects.
6mod contract_manager;
7
8/// Implements access functions for the basic fields (e.g., balance, nonce) of
9/// `State`.
10mod basic_fields;
11
12/// Cache Layer: Implements a read-through write-back cache logic and provides
13/// interfaces for reading and writing account data. It also handles the logic
14/// for loading extension fields of an account.
15mod cache_layer;
16
17/// Checkpoints: Defines the account entry type within checkpoint layers and
18/// implements checkpoint maintenance logic.
19mod checkpoints;
20
21/// Implements functions for the storage collateral of `State`.
22mod collateral;
23
24/// Implements functions for committing `State` changes to db.
25mod commit;
26
27/// Implements access functions global statistic variables of `State`.
28mod global_statistics;
29
30mod warm;
31
32/// Implements functions for the PoS rewarding of `State`.
33mod pos;
34
35mod save;
36
37/// Implements functions for the sponsorship mechanism of `State`.
38mod sponsor;
39
40/// Implements functions for the staking mechanism of `State`.
41mod staking;
42
43/// Implements access functions for the account storage entries of `State`.
44mod storage_entry;
45
46mod reward;
47
48mod state_override;
49
50#[cfg(test)]
51mod tests;
52
53pub use self::{
54    collateral::{initialize_cip107, settle_collateral_for_all},
55    commit::StateCommitResult,
56    pos::{distribute_pos_interest, update_pos_status},
57    reward::initialize_cip137,
58    sponsor::COMMISSION_PRIVILEGE_SPECIAL_KEY,
59    staking::initialize_or_update_dao_voted_params,
60};
61pub(crate) use reward::burnt_gas_price;
62#[cfg(test)]
63pub use tests::{get_state_by_epoch_id, get_state_for_genesis_write};
64
65use self::checkpoints::CheckpointLayer;
66use super::{
67    checkpoints::LazyDiscardedVec,
68    global_stat::GlobalStat,
69    overlay_account::{
70        AccountEntry, AccountEntryWithWarm, OverlayAccount, RequireFields,
71    },
72};
73use crate::substate::Substate;
74use cfx_statedb::{Result as DbResult, StateDbExt, StateDbGeneric as StateDb};
75use cfx_types::{AddressWithSpace, H256};
76use parking_lot::RwLock;
77use std::collections::{BTreeSet, HashMap, HashSet};
78
79/// A caching and checkpoint layer built upon semantically meaningful database
80/// interfaces, providing interfaces and logics for managing accounts and global
81/// statistics to the execution engine.
82pub struct State {
83    /// The backend database
84    pub(super) db: StateDb,
85
86    /// Caches for the account entries
87    ///
88    /// WARNING: Don't delete cache entries outside of `State::commit`, unless
89    /// you are familiar with checkpoint maintenance.
90    pub cache: RwLock<HashMap<AddressWithSpace, AccountEntryWithWarm>>,
91
92    pub committed_cache: HashMap<AddressWithSpace, AccountEntry>,
93    tx_access_list: Option<HashMap<AddressWithSpace, HashSet<H256>>>,
94
95    /// In-memory global statistic variables.
96    // TODO: try not to make it special?
97    global_stat: GlobalStat,
98
99    /// Checkpoint layers for the account entries
100    // TODO: it seems `RwLock` is not necessary here. But we need to change the
101    // signature of `write_account` from `&self` to `&mut self` first
102    checkpoints: RwLock<LazyDiscardedVec<CheckpointLayer>>,
103}
104
105impl State {
106    pub fn new(db: StateDb) -> DbResult<Self> {
107        let initialized = db.is_initialized()?;
108
109        let world_stat = if initialized {
110            GlobalStat::loaded(&db)?
111        } else {
112            GlobalStat::assert_non_inited(&db)?;
113            GlobalStat::new()
114        };
115
116        Ok(State {
117            db,
118            cache: Default::default(),
119            committed_cache: Default::default(),
120            checkpoints: Default::default(),
121            tx_access_list: None,
122            global_stat: world_stat,
123        })
124    }
125
126    pub fn prefetch_accounts(
127        &mut self, addresses: BTreeSet<AddressWithSpace>,
128        pool: &rayon::ThreadPool,
129    ) -> DbResult<()> {
130        use rayon::prelude::*;
131
132        // Consume the iterator inside install so execution does not depend on
133        // the global Rayon pool, whose RPC jobs may wait for consensus locks.
134        pool.install(|| {
135            addresses
136                .into_par_iter()
137                .map(|addr| self.prefetch(&addr, RequireFields::Code))
138                .collect::<DbResult<()>>()
139        })?;
140
141        assert!(self.committed_cache.is_empty());
142        self.commit_cache(false);
143        Ok(())
144    }
145}