1#[cfg(msim)]
5pub use msim::*;
6
7#[cfg(msim)]
8use std::hash::Hasher;
9
10use std::sync::atomic::{AtomicUsize, Ordering};
11
12pub use ::rand as rand_crate;
14pub use anemo;
15pub use anemo_tower;
16pub use fastcrypto;
17pub use lru;
18pub use mysten_network;
19pub use sui_framework;
20pub use sui_types;
21pub use telemetry_subscribers;
22pub use tempfile;
23pub use tower;
24
25#[cfg(msim)]
26pub mod configs {
27 use msim::*;
28 use std::collections::HashMap;
29 use std::ops::Range;
30 use std::time::Duration;
31
32 use tracing::info;
33
34 fn ms_to_dur(range: Range<u64>) -> Range<Duration> {
35 Duration::from_millis(range.start)..Duration::from_millis(range.end)
36 }
37
38 pub fn constant_latency_ms(latency: u64) -> SimConfig {
40 uniform_latency_ms(latency..(latency + 1))
41 }
42
43 pub fn uniform_latency_ms(range: Range<u64>) -> SimConfig {
45 let range = ms_to_dur(range);
46 SimConfig {
47 net: NetworkConfig {
48 latency: LatencyConfig {
49 default_latency: LatencyDistribution::uniform(range),
50 ..Default::default()
51 },
52 ..Default::default()
53 },
54 }
55 }
56
57 pub fn bimodal_latency_ms(
59 baseline: Range<u64>,
61 degraded: Range<u64>,
63 degraded_freq: f64,
65 ) -> SimConfig {
66 let baseline = ms_to_dur(baseline);
67 let degraded = ms_to_dur(degraded);
68 SimConfig {
69 net: NetworkConfig {
70 latency: LatencyConfig {
71 default_latency: LatencyDistribution::bimodal(
72 baseline,
73 degraded,
74 degraded_freq,
75 ),
76 ..Default::default()
77 },
78 ..Default::default()
79 },
80 }
81 }
82
83 pub fn env_config(
85 default: SimConfig,
87 env_configs: impl IntoIterator<Item = (&'static str, SimConfig)>,
90 ) -> SimConfig {
91 let mut env_configs = HashMap::<&'static str, SimConfig>::from_iter(env_configs);
92 if let Some(env) = std::env::var("SUI_SIM_CONFIG").ok() {
93 if let Some(cfg) = env_configs.remove(env.as_str()) {
94 info!("Using test config for SUI_SIM_CONFIG={}", env);
95 cfg
96 } else {
97 panic!(
98 "No config found for SUI_SIM_CONFIG={}. Available configs are: {:?}",
99 env,
100 env_configs.keys()
101 );
102 }
103 } else {
104 info!("Using default test config");
105 default
106 }
107 }
108}
109
110static NODE_COUNT: AtomicUsize = AtomicUsize::new(0);
111
112pub struct NodeLeakDetector(());
113
114impl NodeLeakDetector {
115 pub fn new() -> Self {
116 NODE_COUNT.fetch_add(1, Ordering::SeqCst);
117 Self(())
118 }
119
120 pub fn get_current_node_count() -> usize {
121 NODE_COUNT.load(Ordering::SeqCst)
122 }
123}
124
125impl Default for NodeLeakDetector {
126 fn default() -> Self {
127 Self::new()
128 }
129}
130
131impl Drop for NodeLeakDetector {
132 fn drop(&mut self) {
133 NODE_COUNT.fetch_sub(1, Ordering::SeqCst);
134 }
135}
136
137#[cfg(not(msim))]
138#[macro_export]
139macro_rules! return_if_killed {
140 () => {};
141}
142
143#[cfg(msim)]
144pub fn current_simnode_id() -> msim::task::NodeId {
145 msim::runtime::NodeHandle::current().id()
146}
147
148pub fn has_mainnet_protocol_config_override() -> bool {
149 use sui_types::{digests::ChainIdentifier, supported_protocol_versions::Chain};
150
151 ChainIdentifier::default().chain() == Chain::Mainnet
152}
153
154#[cfg(msim)]
155pub mod random {
156 use super::*;
157
158 use rand_crate::{Rng, SeedableRng, rngs::SmallRng, thread_rng};
159 use serde::Serialize;
160 use std::collections::HashSet;
161 use std::hash::Hash;
162 use std::sync::{Mutex, OnceLock};
163
164 pub fn deterministic_probability<T: Hash>(value: T, chance: f32) -> bool {
167 static SEED: OnceLock<u64> = OnceLock::new();
170 let seed = *SEED.get_or_init(|| thread_rng().r#gen());
171
172 chance > {
173 let mut hasher = std::collections::hash_map::DefaultHasher::new();
174 seed.hash(&mut hasher);
175 value.hash(&mut hasher);
176 let mut rng = SmallRng::seed_from_u64(hasher.finish());
177 rng.gen_range(0.0..1.0)
178 }
179 }
180
181 pub fn deterministic_probability_once<T: Hash + Serialize>(value: T, chance: f32) -> bool {
184 static FAILING_VALUES: Mutex<Option<HashSet<(msim::task::NodeId, Vec<u8>)>>> =
185 Mutex::new(None);
186
187 let bytes = bcs::to_bytes(&value).unwrap();
188 let key = (current_simnode_id(), bytes);
189
190 let mut guard = FAILING_VALUES.lock().unwrap();
191 let failing_values = guard.get_or_insert_with(HashSet::new);
192 if failing_values.contains(&key) {
193 false
194 } else if deterministic_probability(value, chance) {
195 failing_values.insert(key);
196 true
197 } else {
198 false
199 }
200 }
201}