Skip to main content

sui_types/sui_system_state/
mod.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use self::sui_system_state_inner_v1::{SuiSystemStateInnerV1, ValidatorV1};
5use self::sui_system_state_summary::{SuiSystemStateSummary, SuiValidatorSummary};
6use crate::base_types::ObjectID;
7use crate::collection_types::Bag;
8use crate::committee::CommitteeWithNetworkMetadata;
9use crate::dynamic_field::{
10    Field, get_dynamic_field_from_store, get_dynamic_field_object_from_store,
11};
12use crate::error::{SuiError, SuiErrorKind};
13use crate::gas::GasCostSummary;
14use crate::object::{MoveObject, Object};
15use crate::storage::ObjectStore;
16use crate::sui_system_state::epoch_start_sui_system_state::EpochStartSystemState;
17use crate::sui_system_state::sui_system_state_inner_v2::SuiSystemStateInnerV2;
18use crate::versioned::Versioned;
19use crate::{MoveTypeTagTrait, SUI_SYSTEM_ADDRESS, SUI_SYSTEM_STATE_OBJECT_ID, id::UID};
20use anyhow::Result;
21use enum_dispatch::enum_dispatch;
22use move_core_types::{ident_str, identifier::IdentStr, language_storage::StructTag};
23use serde::de::DeserializeOwned;
24use serde::{Deserialize, Serialize};
25use std::fmt;
26use sui_protocol_config::{ProtocolConfig, ProtocolVersion};
27
28pub mod epoch_start_sui_system_state;
29pub mod mock;
30pub mod sui_system_state_inner_v1;
31pub mod sui_system_state_inner_v2;
32pub mod sui_system_state_summary;
33
34#[cfg(msim)]
35mod simtest_sui_system_state_inner;
36#[cfg(msim)]
37use self::simtest_sui_system_state_inner::{
38    SimTestSuiSystemStateInnerDeepV2, SimTestSuiSystemStateInnerShallowV2,
39    SimTestSuiSystemStateInnerV1, SimTestValidatorDeepV2, SimTestValidatorV1,
40};
41
42const SUI_SYSTEM_STATE_WRAPPER_STRUCT_NAME: &IdentStr = ident_str!("SuiSystemState");
43
44pub const SUI_SYSTEM_MODULE_NAME: &IdentStr = ident_str!("sui_system");
45pub const SUI_SYSTEM_STATE_INNER_MODULE_NAME: &IdentStr = ident_str!("sui_system_state_inner");
46pub const SUI_SYSTEM_STATE_INNER_V1_STRUCT_NAME: &IdentStr = ident_str!("SuiSystemStateInner");
47pub const SUI_SYSTEM_STATE_INNER_V2_STRUCT_NAME: &IdentStr = ident_str!("SuiSystemStateInnerV2");
48pub const VALIDATOR_MODULE_NAME: &IdentStr = ident_str!("validator");
49pub const VALIDATOR_STRUCT_NAME: &IdentStr = ident_str!("Validator");
50pub const ADVANCE_EPOCH_FUNCTION_NAME: &IdentStr = ident_str!("advance_epoch");
51pub const ADVANCE_EPOCH_SAFE_MODE_FUNCTION_NAME: &IdentStr = ident_str!("advance_epoch_safe_mode");
52
53#[cfg(msim)]
54pub const SUI_SYSTEM_STATE_SIM_TEST_V1: u64 = 18446744073709551605; // u64::MAX - 10
55#[cfg(msim)]
56pub const SUI_SYSTEM_STATE_SIM_TEST_SHALLOW_V2: u64 = 18446744073709551606; // u64::MAX - 9
57#[cfg(msim)]
58pub const SUI_SYSTEM_STATE_SIM_TEST_DEEP_V2: u64 = 18446744073709551607; // u64::MAX - 8
59
60/// Rust version of the Move sui::sui_system::SuiSystemState type
61/// This represents the object with 0x5 ID.
62/// In Rust, this type should be rarely used since it's just a thin
63/// wrapper used to access the inner object.
64/// Within this module, we use it to determine the current version of the system state inner object type,
65/// so that we could deserialize the inner object correctly.
66/// Outside of this module, we only use it in genesis snapshot and testing.
67#[derive(Debug, Serialize, Deserialize, Clone)]
68pub struct SuiSystemStateWrapper {
69    pub id: UID,
70    pub version: u64,
71}
72
73impl SuiSystemStateWrapper {
74    pub fn type_() -> StructTag {
75        StructTag {
76            address: SUI_SYSTEM_ADDRESS,
77            name: SUI_SYSTEM_STATE_WRAPPER_STRUCT_NAME.to_owned(),
78            module: SUI_SYSTEM_MODULE_NAME.to_owned(),
79            type_params: vec![],
80        }
81    }
82
83    /// Advances epoch in safe mode natively in Rust, without involking Move.
84    /// This ensures that there cannot be any failure from Move and is guaranteed to succeed.
85    /// Returns the old and new inner system state object.
86    pub fn advance_epoch_safe_mode(
87        &self,
88        params: &AdvanceEpochParams,
89        object_store: &dyn ObjectStore,
90        protocol_config: &ProtocolConfig,
91    ) -> (Object, Object) {
92        let id = self.id.id.bytes;
93        let old_field_object = get_dynamic_field_object_from_store(object_store, id, &self.version)
94            .expect("Dynamic field object of wrapper should always be present in the object store");
95        let mut new_field_object = old_field_object.clone();
96        let move_object = new_field_object
97            .data
98            .try_as_move_mut()
99            .expect("Dynamic field object must be a Move object");
100        match self.version {
101            1 => {
102                Self::advance_epoch_safe_mode_impl::<SuiSystemStateInnerV1>(
103                    move_object,
104                    params,
105                    protocol_config,
106                );
107            }
108            2 => {
109                Self::advance_epoch_safe_mode_impl::<SuiSystemStateInnerV2>(
110                    move_object,
111                    params,
112                    protocol_config,
113                );
114            }
115            #[cfg(msim)]
116            SUI_SYSTEM_STATE_SIM_TEST_V1 => {
117                Self::advance_epoch_safe_mode_impl::<SimTestSuiSystemStateInnerV1>(
118                    move_object,
119                    params,
120                    protocol_config,
121                );
122            }
123            #[cfg(msim)]
124            SUI_SYSTEM_STATE_SIM_TEST_SHALLOW_V2 => {
125                Self::advance_epoch_safe_mode_impl::<SimTestSuiSystemStateInnerShallowV2>(
126                    move_object,
127                    params,
128                    protocol_config,
129                );
130            }
131            #[cfg(msim)]
132            SUI_SYSTEM_STATE_SIM_TEST_DEEP_V2 => {
133                Self::advance_epoch_safe_mode_impl::<SimTestSuiSystemStateInnerDeepV2>(
134                    move_object,
135                    params,
136                    protocol_config,
137                );
138            }
139            _ => unreachable!(),
140        }
141        (old_field_object, new_field_object)
142    }
143
144    fn advance_epoch_safe_mode_impl<T>(
145        move_object: &mut MoveObject,
146        params: &AdvanceEpochParams,
147        protocol_config: &ProtocolConfig,
148    ) where
149        T: Serialize + DeserializeOwned + SuiSystemStateTrait,
150    {
151        let mut field: Field<u64, T> =
152            bcs::from_bytes(move_object.contents()).expect("bcs deserialization should never fail");
153        tracing::info!(
154            "Advance epoch safe mode: current epoch: {}, protocol_version: {}, system_state_version: {}",
155            field.value.epoch(),
156            field.value.protocol_version(),
157            field.value.system_state_version()
158        );
159        field.value.advance_epoch_safe_mode(params);
160        tracing::info!(
161            "Safe mode activated. New epoch: {}, protocol_version: {}, system_state_version: {}",
162            field.value.epoch(),
163            field.value.protocol_version(),
164            field.value.system_state_version()
165        );
166        let new_contents = bcs::to_bytes(&field).expect("bcs serialization should never fail");
167        move_object
168            .update_contents_advance_epoch_safe_mode(new_contents, protocol_config)
169            .expect("Update sui system object content cannot fail since it should be small or unbounded");
170    }
171}
172
173/// This is the standard API that all inner system state object type should implement.
174#[enum_dispatch]
175pub trait SuiSystemStateTrait {
176    fn epoch(&self) -> u64;
177    fn reference_gas_price(&self) -> u64;
178    fn protocol_version(&self) -> u64;
179    fn system_state_version(&self) -> u64;
180    fn epoch_start_timestamp_ms(&self) -> u64;
181    fn epoch_duration_ms(&self) -> u64;
182    fn extra_fields(&self) -> &Bag;
183    fn safe_mode(&self) -> bool;
184    fn safe_mode_gas_cost_summary(&self) -> GasCostSummary;
185    fn advance_epoch_safe_mode(&mut self, params: &AdvanceEpochParams);
186    fn get_current_epoch_committee(&self) -> CommitteeWithNetworkMetadata;
187    fn get_pending_active_validators<S: ObjectStore + ?Sized>(
188        &self,
189        object_store: &S,
190    ) -> Result<Vec<SuiValidatorSummary>, SuiError>;
191    fn into_epoch_start_state(self) -> EpochStartSystemState;
192    fn into_sui_system_state_summary(self) -> SuiSystemStateSummary;
193}
194
195/// SuiSystemState provides an abstraction over multiple versions of the inner SuiSystemStateInner object.
196/// This should be the primary interface to the system state object in Rust.
197/// We use enum dispatch to dispatch all methods defined in SuiSystemStateTrait to the actual
198/// implementation in the inner types.
199#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
200#[enum_dispatch(SuiSystemStateTrait)]
201pub enum SuiSystemState {
202    V1(SuiSystemStateInnerV1),
203    V2(SuiSystemStateInnerV2),
204    #[cfg(msim)]
205    SimTestV1(SimTestSuiSystemStateInnerV1),
206    #[cfg(msim)]
207    SimTestShallowV2(SimTestSuiSystemStateInnerShallowV2),
208    #[cfg(msim)]
209    SimTestDeepV2(SimTestSuiSystemStateInnerDeepV2),
210}
211
212/// This is the fixed type used by genesis.
213pub type SuiSystemStateInnerGenesis = SuiSystemStateInnerV1;
214pub type SuiValidatorGenesis = ValidatorV1;
215
216impl SuiSystemState {
217    /// Always return the version that we will be using for genesis.
218    /// Genesis always uses this version regardless of the current version.
219    /// Note that since it's possible for the actual genesis of the network to diverge from the
220    /// genesis of the latest Rust code, it's important that we only use this for tooling purposes.
221    pub fn into_genesis_version_for_tooling(self) -> SuiSystemStateInnerGenesis {
222        match self {
223            SuiSystemState::V1(inner) => inner,
224            _ => unreachable!(),
225        }
226    }
227
228    pub fn version(&self) -> u64 {
229        self.system_state_version()
230    }
231}
232
233pub fn get_sui_system_state_wrapper(
234    object_store: &dyn ObjectStore,
235) -> Result<SuiSystemStateWrapper, SuiError> {
236    let wrapper = object_store
237        .get_object(&SUI_SYSTEM_STATE_OBJECT_ID)
238        // Don't panic here on None because object_store is a generic store.
239        .ok_or_else(|| {
240            SuiErrorKind::SuiSystemStateReadError(
241                "SuiSystemStateWrapper object not found".to_owned(),
242            )
243        })?;
244    let move_object = wrapper.data.try_as_move().ok_or_else(|| {
245        SuiErrorKind::SuiSystemStateReadError(
246            "SuiSystemStateWrapper object must be a Move object".to_owned(),
247        )
248    })?;
249    let result = bcs::from_bytes::<SuiSystemStateWrapper>(move_object.contents())
250        .map_err(|err| SuiErrorKind::SuiSystemStateReadError(err.to_string()))?;
251    Ok(result)
252}
253
254/// The ID of the system state's inner object for `version`: the dynamic field of the
255/// `SuiSystemState` wrapper (`0x5`) keyed by the wrapper's `version`.
256pub fn sui_system_state_inner_id(version: u64) -> ObjectID {
257    crate::dynamic_field::derive_dynamic_field_id(
258        SUI_SYSTEM_STATE_OBJECT_ID,
259        &move_core_types::language_storage::TypeTag::U64,
260        &version.to_le_bytes(),
261    )
262    .expect("a u64 key type tag always serializes")
263}
264
265pub fn get_sui_system_state(object_store: &dyn ObjectStore) -> Result<SuiSystemState, SuiError> {
266    let wrapper = get_sui_system_state_wrapper(object_store)?;
267    let id = wrapper.id.id.bytes;
268    match wrapper.version {
269        1 => {
270            let result: SuiSystemStateInnerV1 =
271                get_dynamic_field_from_store(object_store, id, &wrapper.version).map_err(
272                    |err| {
273                        SuiErrorKind::DynamicFieldReadError(format!(
274                            "Failed to load sui system state inner object with ID {:?} and version {:?}: {:?}",
275                            id, wrapper.version, err
276                        ))
277                    },
278                )?;
279            Ok(SuiSystemState::V1(result))
280        }
281        2 => {
282            let result: SuiSystemStateInnerV2 =
283                get_dynamic_field_from_store(object_store, id, &wrapper.version).map_err(
284                    |err| {
285                        SuiErrorKind::DynamicFieldReadError(format!(
286                            "Failed to load sui system state inner object with ID {:?} and version {:?}: {:?}",
287                            id, wrapper.version, err
288                        ))
289                    },
290                )?;
291            Ok(SuiSystemState::V2(result))
292        }
293        #[cfg(msim)]
294        SUI_SYSTEM_STATE_SIM_TEST_V1 => {
295            let result: SimTestSuiSystemStateInnerV1 =
296                get_dynamic_field_from_store(object_store, id, &wrapper.version).map_err(
297                    |err| {
298                        SuiErrorKind::DynamicFieldReadError(format!(
299                            "Failed to load sui system state inner object with ID {:?} and version {:?}: {:?}",
300                            id, wrapper.version, err
301                        ))
302                    },
303                )?;
304            Ok(SuiSystemState::SimTestV1(result))
305        }
306        #[cfg(msim)]
307        SUI_SYSTEM_STATE_SIM_TEST_SHALLOW_V2 => {
308            let result: SimTestSuiSystemStateInnerShallowV2 =
309                get_dynamic_field_from_store(object_store, id, &wrapper.version).map_err(
310                    |err| {
311                        SuiErrorKind::DynamicFieldReadError(format!(
312                            "Failed to load sui system state inner object with ID {:?} and version {:?}: {:?}",
313                            id, wrapper.version, err
314                        ))
315                    },
316                )?;
317            Ok(SuiSystemState::SimTestShallowV2(result))
318        }
319        #[cfg(msim)]
320        SUI_SYSTEM_STATE_SIM_TEST_DEEP_V2 => {
321            let result: SimTestSuiSystemStateInnerDeepV2 =
322                get_dynamic_field_from_store(object_store, id, &wrapper.version).map_err(
323                    |err| {
324                        SuiErrorKind::DynamicFieldReadError(format!(
325                            "Failed to load sui system state inner object with ID {:?} and version {:?}: {:?}",
326                            id, wrapper.version, err
327                        ))
328                    },
329                )?;
330            Ok(SuiSystemState::SimTestDeepV2(result))
331        }
332        _ => Err(SuiErrorKind::SuiSystemStateReadError(format!(
333            "Unsupported SuiSystemState version: {}",
334            wrapper.version
335        ))
336        .into()),
337    }
338}
339
340/// Given a system state type version, and the ID of the table, along with a key, retrieve the
341/// dynamic field as a Validator type. We need the version to determine which inner type to use for
342/// the Validator type. This is assuming that the validator is stored in the table as
343/// ValidatorWrapper type.
344pub fn get_validator_from_table<K>(
345    object_store: &dyn ObjectStore,
346    table_id: ObjectID,
347    key: &K,
348) -> Result<SuiValidatorSummary, SuiError>
349where
350    K: Clone + MoveTypeTagTrait + Serialize + DeserializeOwned + fmt::Debug,
351{
352    let field: ValidatorWrapper = get_dynamic_field_from_store(object_store, table_id, key)
353        .map_err(|err| {
354            SuiErrorKind::SuiSystemStateReadError(format!(
355                "Failed to load validator wrapper from table: {:?}",
356                err
357            ))
358        })?;
359    let versioned = field.inner;
360    let version = versioned.version;
361    match version {
362        1 => {
363            let validator: ValidatorV1 =
364                get_dynamic_field_from_store(object_store, versioned.id.id.bytes, &version)
365                    .map_err(|err| {
366                        SuiErrorKind::SuiSystemStateReadError(format!(
367                            "Failed to load inner validator from the wrapper: {:?}",
368                            err
369                        ))
370                    })?;
371            Ok(validator.into_sui_validator_summary())
372        }
373        #[cfg(msim)]
374        SUI_SYSTEM_STATE_SIM_TEST_V1 => {
375            let validator: SimTestValidatorV1 =
376                get_dynamic_field_from_store(object_store, versioned.id.id.bytes, &version)
377                    .map_err(|err| {
378                        SuiErrorKind::SuiSystemStateReadError(format!(
379                            "Failed to load inner validator from the wrapper: {:?}",
380                            err
381                        ))
382                    })?;
383            Ok(validator.into_sui_validator_summary())
384        }
385        #[cfg(msim)]
386        SUI_SYSTEM_STATE_SIM_TEST_DEEP_V2 => {
387            let validator: SimTestValidatorDeepV2 =
388                get_dynamic_field_from_store(object_store, versioned.id.id.bytes, &version)
389                    .map_err(|err| {
390                        SuiErrorKind::SuiSystemStateReadError(format!(
391                            "Failed to load inner validator from the wrapper: {:?}",
392                            err
393                        ))
394                    })?;
395            Ok(validator.into_sui_validator_summary())
396        }
397        _ => Err(SuiErrorKind::SuiSystemStateReadError(format!(
398            "Unsupported Validator version: {}",
399            version
400        ))
401        .into()),
402    }
403}
404
405pub fn get_validators_from_table_vec<S, ValidatorType>(
406    object_store: &S,
407    table_id: ObjectID,
408    table_size: u64,
409) -> Result<Vec<ValidatorType>, SuiError>
410where
411    S: ObjectStore + ?Sized,
412    ValidatorType: Serialize + DeserializeOwned,
413{
414    let mut validators = vec![];
415    for i in 0..table_size {
416        let validator: ValidatorType = get_dynamic_field_from_store(&object_store, table_id, &i)
417            .map_err(|err| {
418                SuiErrorKind::SuiSystemStateReadError(format!(
419                    "Failed to load validator from table: {:?}",
420                    err
421                ))
422            })?;
423        validators.push(validator);
424    }
425    Ok(validators)
426}
427
428#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq, Default)]
429pub struct PoolTokenExchangeRate {
430    sui_amount: u64,
431    pool_token_amount: u64,
432}
433
434impl PoolTokenExchangeRate {
435    /// Rate of the staking pool, pool token amount : Sui amount
436    pub fn rate(&self) -> f64 {
437        if self.sui_amount == 0 {
438            1_f64
439        } else {
440            self.pool_token_amount as f64 / self.sui_amount as f64
441        }
442    }
443
444    pub fn new(sui_amount: u64, pool_token_amount: u64) -> Self {
445        Self {
446            sui_amount,
447            pool_token_amount,
448        }
449    }
450}
451
452#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
453pub struct ValidatorWrapper {
454    pub inner: Versioned,
455}
456
457#[derive(Debug)]
458pub struct AdvanceEpochParams {
459    pub epoch: u64,
460    pub next_protocol_version: ProtocolVersion,
461    pub storage_charge: u64,
462    pub computation_charge: u64,
463    pub storage_rebate: u64,
464    pub non_refundable_storage_fee: u64,
465    pub storage_fund_reinvest_rate: u64,
466    pub reward_slashing_rate: u64,
467    pub epoch_start_timestamp_ms: u64,
468}
469
470#[cfg(msim)]
471pub mod advance_epoch_result_injection {
472    use crate::error::ExecutionErrorTrait;
473    use crate::{
474        committee::EpochId, error::ExecutionError, execution::ResultWithTimings,
475        execution_status::ExecutionErrorKind,
476    };
477    /// Override the result of advance_epoch in the range [start, end).
478    static OVERRIDE: std::sync::Mutex<Option<(EpochId, EpochId)>> = std::sync::Mutex::new(None);
479
480    /// Override the result of advance_epoch transaction if new epoch is in the provided range [start, end).
481    pub fn set_override(value: Option<(EpochId, EpochId)>) {
482        *OVERRIDE.lock().unwrap() = value;
483    }
484
485    /// This function is used to modify the result of advance_epoch transaction for testing.
486    /// If the override is set, the result will be an execution error, otherwise the original result will be returned.
487    pub fn maybe_modify_result(
488        result: ResultWithTimings<(), ExecutionError>,
489        current_epoch: EpochId,
490    ) -> ResultWithTimings<(), ExecutionError> {
491        if let Some((start, end)) = *OVERRIDE.lock().unwrap() {
492            if current_epoch >= start && current_epoch < end {
493                return Err((
494                    ExecutionError::new(ExecutionErrorKind::FunctionNotFound, None),
495                    vec![],
496                ));
497            }
498        }
499        result
500    }
501
502    /// This function is used to modify the result of advance_epoch transaction for testing.
503    /// If the override is set, the result will be an execution error, otherwise the original result will be returned.
504    pub fn maybe_modify_result_for<E: ExecutionErrorTrait>(
505        result: ResultWithTimings<(), E>,
506        current_epoch: EpochId,
507    ) -> ResultWithTimings<(), E> {
508        if let Some((start, end)) = *OVERRIDE.lock().unwrap() {
509            if current_epoch >= start && current_epoch < end {
510                return Err((
511                    // TODO use E constructor
512                    ExecutionError::new(ExecutionErrorKind::FunctionNotFound, None).into(),
513                    vec![],
514                ));
515            }
516        }
517        result
518    }
519
520    // For old execution versions that don't report timings
521    pub fn maybe_modify_result_legacy(
522        result: Result<(), ExecutionError>,
523        current_epoch: EpochId,
524    ) -> Result<(), ExecutionError> {
525        if let Some((start, end)) = *OVERRIDE.lock().unwrap() {
526            if current_epoch >= start && current_epoch < end {
527                return Err(ExecutionError::new(
528                    ExecutionErrorKind::FunctionNotFound,
529                    None,
530                ));
531            }
532        }
533        result
534    }
535}