1use 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; #[cfg(msim)]
56pub const SUI_SYSTEM_STATE_SIM_TEST_SHALLOW_V2: u64 = 18446744073709551606; #[cfg(msim)]
58pub const SUI_SYSTEM_STATE_SIM_TEST_DEEP_V2: u64 = 18446744073709551607; #[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 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#[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#[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
212pub type SuiSystemStateInnerGenesis = SuiSystemStateInnerV1;
214pub type SuiValidatorGenesis = ValidatorV1;
215
216impl SuiSystemState {
217 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 .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
254pub 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
340pub 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 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 static OVERRIDE: std::sync::Mutex<Option<(EpochId, EpochId)>> = std::sync::Mutex::new(None);
479
480 pub fn set_override(value: Option<(EpochId, EpochId)>) {
482 *OVERRIDE.lock().unwrap() = value;
483 }
484
485 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 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 ExecutionError::new(ExecutionErrorKind::FunctionNotFound, None).into(),
513 vec![],
514 ));
515 }
516 }
517 result
518 }
519
520 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}