1use super::Node;
5use anyhow::Result;
6use futures::future::try_join_all;
7use rand::rngs::OsRng;
8use std::collections::HashMap;
9use std::net::SocketAddr;
10use std::num::NonZeroUsize;
11use std::time::Duration;
12use std::{
13 ops,
14 path::{Path, PathBuf},
15};
16use sui_types::traffic_control::{PolicyConfig, RemoteFirewallConfig};
17
18#[cfg(msim)]
19use sui_config::node::ExecutionTimeObserverConfig;
20use sui_config::node::{AuthorityOverloadConfig, DBCheckpointConfig, RunWithRange};
21use sui_config::{ExecutionCacheConfig, NodeConfig};
22use sui_macros::nondeterministic;
23use sui_node::SuiNodeHandle;
24use sui_protocol_config::{Chain, ProtocolVersion};
25use sui_swarm_config::genesis_config::{AccountConfig, GenesisConfig, ValidatorGenesisConfig};
26use sui_swarm_config::network_config::NetworkConfig;
27use sui_swarm_config::network_config_builder::{
28 CommitteeConfig, ConfigBuilder, FundsWithdrawSchedulerTypeConfig,
29 GlobalStateHashV2EnabledConfig, ProtocolVersionsConfig, SupportedProtocolVersionsCallback,
30};
31use sui_swarm_config::node_config_builder::FullnodeConfigBuilder;
32use sui_types::base_types::AuthorityName;
33use sui_types::object::Object;
34use sui_types::supported_protocol_versions::SupportedProtocolVersions;
35use tempfile::TempDir;
36use tracing::info;
37
38pub struct SwarmBuilder<R = OsRng> {
39 rng: R,
40 dir: Option<PathBuf>,
42 committee: CommitteeConfig,
43 genesis_config: Option<GenesisConfig>,
44 network_config: Option<NetworkConfig>,
45 chain_override: Option<Chain>,
46 additional_objects: Vec<Object>,
47 fullnode_count: usize,
48 fullnode_rpc_port: Option<u16>,
49 fullnode_rpc_addr: Option<SocketAddr>,
50 fullnode_rpc_config: Option<sui_config::RpcConfig>,
51 supported_protocol_versions_config: ProtocolVersionsConfig,
52 fullnode_supported_protocol_versions_config: Option<ProtocolVersionsConfig>,
54 db_checkpoint_config: DBCheckpointConfig,
55 jwk_fetch_interval: Option<Duration>,
56 num_unpruned_validators: Option<usize>,
57 authority_overload_config: Option<AuthorityOverloadConfig>,
58 execution_cache_config: Option<ExecutionCacheConfig>,
59 data_ingestion_dir: Option<PathBuf>,
60 fullnode_run_with_range: Option<RunWithRange>,
61 fullnode_policy_config: Option<PolicyConfig>,
62 fullnode_fw_config: Option<RemoteFirewallConfig>,
63 max_submit_position: Option<usize>,
64 submit_delay_step_override_millis: Option<u64>,
65 global_state_hash_v2_enabled_config: GlobalStateHashV2EnabledConfig,
66 funds_withdraw_scheduler_type_config: Option<FundsWithdrawSchedulerTypeConfig>,
67 disable_fullnode_pruning: bool,
68 state_sync_config: Option<sui_config::p2p::StateSyncConfig>,
69 #[cfg(msim)]
70 execution_time_observer_config: Option<ExecutionTimeObserverConfig>,
71}
72
73impl SwarmBuilder {
74 #[allow(clippy::new_without_default)]
75 pub fn new() -> Self {
76 Self {
77 rng: OsRng,
78 dir: None,
79 committee: CommitteeConfig::Size(NonZeroUsize::new(1).unwrap()),
80 genesis_config: None,
81 network_config: None,
82 chain_override: None,
83 additional_objects: vec![],
84 fullnode_count: 0,
85 fullnode_rpc_port: None,
86 fullnode_rpc_addr: None,
87 fullnode_rpc_config: None,
88 supported_protocol_versions_config: ProtocolVersionsConfig::Default,
89 fullnode_supported_protocol_versions_config: None,
90 db_checkpoint_config: DBCheckpointConfig::default(),
91 jwk_fetch_interval: None,
92 num_unpruned_validators: None,
93 authority_overload_config: None,
94 execution_cache_config: None,
95 data_ingestion_dir: None,
96 fullnode_run_with_range: None,
97 fullnode_policy_config: None,
98 fullnode_fw_config: None,
99 max_submit_position: None,
100 submit_delay_step_override_millis: None,
101 global_state_hash_v2_enabled_config: GlobalStateHashV2EnabledConfig::Global(true),
102 funds_withdraw_scheduler_type_config: None,
103 disable_fullnode_pruning: false,
104 state_sync_config: None,
105 #[cfg(msim)]
106 execution_time_observer_config: None,
107 }
108 }
109}
110
111impl<R> SwarmBuilder<R> {
112 pub fn rng<N: rand::RngCore + rand::CryptoRng>(self, rng: N) -> SwarmBuilder<N> {
113 SwarmBuilder {
114 rng,
115 dir: self.dir,
116 committee: self.committee,
117 genesis_config: self.genesis_config,
118 network_config: self.network_config,
119 chain_override: self.chain_override,
120 additional_objects: self.additional_objects,
121 fullnode_count: self.fullnode_count,
122 fullnode_rpc_port: self.fullnode_rpc_port,
123 fullnode_rpc_addr: self.fullnode_rpc_addr,
124 fullnode_rpc_config: self.fullnode_rpc_config.clone(),
125 supported_protocol_versions_config: self.supported_protocol_versions_config,
126 fullnode_supported_protocol_versions_config: self
127 .fullnode_supported_protocol_versions_config,
128 db_checkpoint_config: self.db_checkpoint_config,
129 jwk_fetch_interval: self.jwk_fetch_interval,
130 num_unpruned_validators: self.num_unpruned_validators,
131 authority_overload_config: self.authority_overload_config,
132 execution_cache_config: self.execution_cache_config,
133 data_ingestion_dir: self.data_ingestion_dir,
134 fullnode_run_with_range: self.fullnode_run_with_range,
135 fullnode_policy_config: self.fullnode_policy_config,
136 fullnode_fw_config: self.fullnode_fw_config,
137 max_submit_position: self.max_submit_position,
138 submit_delay_step_override_millis: self.submit_delay_step_override_millis,
139 global_state_hash_v2_enabled_config: self.global_state_hash_v2_enabled_config,
140 funds_withdraw_scheduler_type_config: self.funds_withdraw_scheduler_type_config,
141 disable_fullnode_pruning: self.disable_fullnode_pruning,
142 state_sync_config: self.state_sync_config,
143 #[cfg(msim)]
144 execution_time_observer_config: self.execution_time_observer_config,
145 }
146 }
147
148 pub fn dir<P: Into<PathBuf>>(mut self, dir: P) -> Self {
154 self.dir = Some(dir.into());
155 self
156 }
157
158 pub fn committee_size(mut self, committee_size: NonZeroUsize) -> Self {
162 self.committee = CommitteeConfig::Size(committee_size);
163 self
164 }
165
166 pub fn with_validators(mut self, validators: Vec<ValidatorGenesisConfig>) -> Self {
167 self.committee = CommitteeConfig::Validators(validators);
168 self
169 }
170
171 pub fn with_genesis_config(mut self, genesis_config: GenesisConfig) -> Self {
172 assert!(self.network_config.is_none() && self.genesis_config.is_none());
173 self.genesis_config = Some(genesis_config);
174 self
175 }
176
177 pub fn with_chain_override(mut self, chain: Chain) -> Self {
178 assert!(self.chain_override.is_none());
179 self.chain_override = Some(chain);
180 self
181 }
182
183 pub fn with_num_unpruned_validators(mut self, n: usize) -> Self {
184 assert!(self.network_config.is_none());
185 self.num_unpruned_validators = Some(n);
186 self
187 }
188
189 pub fn with_jwk_fetch_interval(mut self, i: Duration) -> Self {
190 self.jwk_fetch_interval = Some(i);
191 self
192 }
193
194 pub fn with_network_config(mut self, network_config: NetworkConfig) -> Self {
195 assert!(self.network_config.is_none() && self.genesis_config.is_none());
196 self.network_config = Some(network_config);
197 self
198 }
199
200 pub fn with_accounts(mut self, accounts: Vec<AccountConfig>) -> Self {
201 self.get_or_init_genesis_config().accounts = accounts;
202 self
203 }
204
205 pub fn with_objects<I: IntoIterator<Item = Object>>(mut self, objects: I) -> Self {
206 self.additional_objects.extend(objects);
207 self
208 }
209
210 pub fn with_fullnode_count(mut self, fullnode_count: usize) -> Self {
211 self.fullnode_count = fullnode_count;
212 self
213 }
214
215 pub fn with_fullnode_rpc_port(mut self, fullnode_rpc_port: u16) -> Self {
216 assert!(self.fullnode_rpc_addr.is_none());
217 self.fullnode_rpc_port = Some(fullnode_rpc_port);
218 self
219 }
220
221 pub fn with_fullnode_rpc_addr(mut self, fullnode_rpc_addr: SocketAddr) -> Self {
222 assert!(self.fullnode_rpc_port.is_none());
223 self.fullnode_rpc_addr = Some(fullnode_rpc_addr);
224 self
225 }
226
227 pub fn with_fullnode_rpc_config(mut self, fullnode_rpc_config: sui_config::RpcConfig) -> Self {
228 self.fullnode_rpc_config = Some(fullnode_rpc_config);
229 self
230 }
231
232 pub fn with_epoch_duration_ms(mut self, epoch_duration_ms: u64) -> Self {
233 self.get_or_init_genesis_config()
234 .parameters
235 .epoch_duration_ms = epoch_duration_ms;
236 self
237 }
238
239 pub fn with_protocol_version(mut self, v: ProtocolVersion) -> Self {
240 self.get_or_init_genesis_config()
241 .parameters
242 .protocol_version = v;
243 self
244 }
245
246 pub fn with_supported_protocol_versions(mut self, c: SupportedProtocolVersions) -> Self {
247 self.supported_protocol_versions_config = ProtocolVersionsConfig::Global(c);
248 self
249 }
250
251 pub fn with_supported_protocol_version_callback(
252 mut self,
253 func: SupportedProtocolVersionsCallback,
254 ) -> Self {
255 self.supported_protocol_versions_config = ProtocolVersionsConfig::PerValidator(func);
256 self
257 }
258
259 pub fn with_supported_protocol_versions_config(mut self, c: ProtocolVersionsConfig) -> Self {
260 self.supported_protocol_versions_config = c;
261 self
262 }
263
264 pub fn with_global_state_hash_v2_enabled_config(
265 mut self,
266 c: GlobalStateHashV2EnabledConfig,
267 ) -> Self {
268 self.global_state_hash_v2_enabled_config = c;
269 self
270 }
271
272 pub fn with_funds_withdraw_scheduler_type_config(
273 mut self,
274 c: FundsWithdrawSchedulerTypeConfig,
275 ) -> Self {
276 self.funds_withdraw_scheduler_type_config = Some(c);
277 self
278 }
279
280 #[cfg(msim)]
281 pub fn with_execution_time_observer_config(mut self, c: ExecutionTimeObserverConfig) -> Self {
282 self.execution_time_observer_config = Some(c);
283 self
284 }
285
286 pub fn with_fullnode_supported_protocol_versions_config(
287 mut self,
288 c: ProtocolVersionsConfig,
289 ) -> Self {
290 self.fullnode_supported_protocol_versions_config = Some(c);
291 self
292 }
293
294 pub fn with_db_checkpoint_config(mut self, db_checkpoint_config: DBCheckpointConfig) -> Self {
295 self.db_checkpoint_config = db_checkpoint_config;
296 self
297 }
298
299 pub fn with_authority_overload_config(
300 mut self,
301 authority_overload_config: AuthorityOverloadConfig,
302 ) -> Self {
303 assert!(self.network_config.is_none());
304 self.authority_overload_config = Some(authority_overload_config);
305 self
306 }
307
308 pub fn with_execution_cache_config(
309 mut self,
310 execution_cache_config: ExecutionCacheConfig,
311 ) -> Self {
312 self.execution_cache_config = Some(execution_cache_config);
313 self
314 }
315
316 pub fn with_data_ingestion_dir(mut self, path: PathBuf) -> Self {
317 self.data_ingestion_dir = Some(path);
318 self
319 }
320
321 pub fn with_state_sync_config(mut self, config: sui_config::p2p::StateSyncConfig) -> Self {
322 self.state_sync_config = Some(config);
323 self
324 }
325
326 pub fn with_fullnode_run_with_range(mut self, run_with_range: Option<RunWithRange>) -> Self {
327 if let Some(run_with_range) = run_with_range {
328 self.fullnode_run_with_range = Some(run_with_range);
329 }
330 self
331 }
332
333 pub fn with_fullnode_policy_config(mut self, config: Option<PolicyConfig>) -> Self {
334 self.fullnode_policy_config = config;
335 self
336 }
337
338 pub fn with_fullnode_fw_config(mut self, config: Option<RemoteFirewallConfig>) -> Self {
339 self.fullnode_fw_config = config;
340 self
341 }
342
343 fn get_or_init_genesis_config(&mut self) -> &mut GenesisConfig {
344 if self.genesis_config.is_none() {
345 assert!(self.network_config.is_none());
346 self.genesis_config = Some(GenesisConfig::for_local_testing());
347 }
348 self.genesis_config.as_mut().unwrap()
349 }
350
351 pub fn with_max_submit_position(mut self, max_submit_position: usize) -> Self {
352 self.max_submit_position = Some(max_submit_position);
353 self
354 }
355
356 pub fn with_disable_fullnode_pruning(mut self) -> Self {
357 self.disable_fullnode_pruning = true;
358 self
359 }
360
361 pub fn with_submit_delay_step_override_millis(
362 mut self,
363 submit_delay_step_override_millis: u64,
364 ) -> Self {
365 self.submit_delay_step_override_millis = Some(submit_delay_step_override_millis);
366 self
367 }
368}
369
370impl<R: rand::RngCore + rand::CryptoRng> SwarmBuilder<R> {
371 pub fn build(self) -> Swarm {
373 let dir = if let Some(dir) = self.dir {
374 SwarmDirectory::Persistent(dir)
375 } else {
376 SwarmDirectory::new_temporary()
377 };
378
379 let ingest_data = self.data_ingestion_dir.clone();
380
381 let network_config = self.network_config.unwrap_or_else(|| {
382 let mut config_builder = ConfigBuilder::new(dir.as_ref());
383
384 if let Some(genesis_config) = self.genesis_config {
385 config_builder = config_builder.with_genesis_config(genesis_config);
386 }
387
388 if let Some(chain_override) = self.chain_override {
389 config_builder = config_builder.with_chain_override(chain_override);
390 }
391
392 if let Some(num_unpruned_validators) = self.num_unpruned_validators {
393 config_builder =
394 config_builder.with_num_unpruned_validators(num_unpruned_validators);
395 }
396
397 if let Some(jwk_fetch_interval) = self.jwk_fetch_interval {
398 config_builder = config_builder.with_jwk_fetch_interval(jwk_fetch_interval);
399 }
400
401 if let Some(authority_overload_config) = self.authority_overload_config {
402 config_builder =
403 config_builder.with_authority_overload_config(authority_overload_config);
404 }
405
406 if let Some(execution_cache_config) = self.execution_cache_config {
407 config_builder = config_builder.with_execution_cache_config(execution_cache_config);
408 }
409
410 if let Some(path) = self.data_ingestion_dir {
411 config_builder = config_builder.with_data_ingestion_dir(path);
412 }
413
414 if let Some(max_submit_position) = self.max_submit_position {
415 config_builder = config_builder.with_max_submit_position(max_submit_position);
416 }
417
418 if let Some(submit_delay_step_override_millis) = self.submit_delay_step_override_millis
419 {
420 config_builder = config_builder
421 .with_submit_delay_step_override_millis(submit_delay_step_override_millis);
422 }
423
424 #[allow(unused_mut)]
425 let mut final_builder = config_builder
426 .committee(self.committee)
427 .rng(self.rng)
428 .with_objects(self.additional_objects)
429 .with_supported_protocol_versions_config(
430 self.supported_protocol_versions_config.clone(),
431 )
432 .with_global_state_hash_v2_enabled_config(
433 self.global_state_hash_v2_enabled_config.clone(),
434 );
435
436 if let Some(funds_withdraw_scheduler_type_config) =
437 self.funds_withdraw_scheduler_type_config.clone()
438 {
439 final_builder = final_builder.with_funds_withdraw_scheduler_type_config(
440 funds_withdraw_scheduler_type_config,
441 );
442 }
443
444 if let Some(state_sync_config) = self.state_sync_config.clone() {
445 final_builder = final_builder.with_state_sync_config(state_sync_config);
446 }
447
448 #[cfg(msim)]
449 if let Some(execution_time_observer_config) = self.execution_time_observer_config {
450 final_builder = final_builder
451 .with_execution_time_observer_config(execution_time_observer_config);
452 }
453
454 final_builder.build()
455 });
456
457 let mut nodes: HashMap<_, _> = network_config
458 .validator_configs()
459 .iter()
460 .map(|config| {
461 info!(
462 "SwarmBuilder configuring validator with name {}",
463 config.protocol_public_key()
464 );
465 (config.protocol_public_key(), Node::new(config.to_owned()))
466 })
467 .collect();
468
469 let mut fullnode_config_builder = FullnodeConfigBuilder::new()
470 .with_config_directory(dir.as_ref().into())
471 .with_db_checkpoint_config(self.db_checkpoint_config.clone())
472 .with_run_with_range(self.fullnode_run_with_range)
473 .with_policy_config(self.fullnode_policy_config)
474 .with_data_ingestion_dir(ingest_data)
475 .with_fw_config(self.fullnode_fw_config)
476 .with_disable_pruning(self.disable_fullnode_pruning);
477
478 if let Some(state_sync_config) = self.state_sync_config.clone() {
479 fullnode_config_builder =
480 fullnode_config_builder.with_state_sync_config(state_sync_config);
481 }
482
483 if let Some(chain) = self.chain_override {
484 fullnode_config_builder = fullnode_config_builder.with_chain_override(chain);
485 }
486
487 if let Some(spvc) = &self.fullnode_supported_protocol_versions_config {
488 let supported_versions = match spvc {
489 ProtocolVersionsConfig::Default => SupportedProtocolVersions::SYSTEM_DEFAULT,
490 ProtocolVersionsConfig::Global(v) => *v,
491 ProtocolVersionsConfig::PerValidator(func) => func(0, None),
492 };
493 fullnode_config_builder =
494 fullnode_config_builder.with_supported_protocol_versions(supported_versions);
495 }
496
497 if self.fullnode_count > 0 {
498 (0..self.fullnode_count).for_each(|idx| {
499 let mut builder = fullnode_config_builder.clone();
500 if idx == 0 {
501 if let Some(rpc_addr) = self.fullnode_rpc_addr {
504 builder = builder.with_rpc_addr(rpc_addr);
505 }
506 if let Some(rpc_port) = self.fullnode_rpc_port {
507 builder = builder.with_rpc_port(rpc_port);
508 }
509 if let Some(rpc_config) = &self.fullnode_rpc_config {
510 builder = builder.with_rpc_config(rpc_config.clone());
511 }
512 }
513 let config = builder.build(&mut OsRng, &network_config);
514 info!(
515 "SwarmBuilder configuring full node with name {}",
516 config.protocol_public_key()
517 );
518 nodes.insert(config.protocol_public_key(), Node::new(config));
519 });
520 }
521 Swarm {
522 dir,
523 network_config,
524 nodes,
525 fullnode_config_builder,
526 }
527 }
528}
529
530#[derive(Debug)]
532pub struct Swarm {
533 dir: SwarmDirectory,
534 network_config: NetworkConfig,
535 nodes: HashMap<AuthorityName, Node>,
536 fullnode_config_builder: FullnodeConfigBuilder,
538}
539
540impl Drop for Swarm {
541 fn drop(&mut self) {
542 self.nodes_iter_mut().for_each(|node| node.stop());
543 }
544}
545
546impl Swarm {
547 fn nodes_iter_mut(&mut self) -> impl Iterator<Item = &mut Node> {
548 self.nodes.values_mut()
549 }
550
551 pub fn builder() -> SwarmBuilder {
553 SwarmBuilder::new()
554 }
555
556 pub async fn launch(&mut self) -> Result<()> {
558 try_join_all(self.nodes_iter_mut().map(|node| node.start())).await?;
559 tracing::info!("Successfully launched Swarm");
560 Ok(())
561 }
562
563 pub fn dir(&self) -> &Path {
565 self.dir.as_ref()
566 }
567
568 pub fn config(&self) -> &NetworkConfig {
570 &self.network_config
571 }
572
573 pub fn config_mut(&mut self) -> &mut NetworkConfig {
576 &mut self.network_config
577 }
578
579 pub fn all_nodes(&self) -> impl Iterator<Item = &Node> {
580 self.nodes.values()
581 }
582
583 pub fn node(&self, name: &AuthorityName) -> Option<&Node> {
584 self.nodes.get(name)
585 }
586
587 pub fn node_mut(&mut self, name: &AuthorityName) -> Option<&mut Node> {
588 self.nodes.get_mut(name)
589 }
590
591 pub fn validator_nodes(&self) -> impl Iterator<Item = &Node> {
595 self.nodes
596 .values()
597 .filter(|node| node.config().consensus_config.is_some())
598 }
599
600 pub fn validator_node_handles(&self) -> Vec<SuiNodeHandle> {
601 self.validator_nodes()
602 .map(|node| node.get_node_handle().unwrap())
603 .collect()
604 }
605
606 pub fn active_validators(&self) -> impl Iterator<Item = &Node> {
608 self.validator_nodes().filter(|node| {
609 node.get_node_handle().is_some_and(|handle| {
610 let state = handle.state();
611 state.is_validator(&state.epoch_store_for_testing())
612 })
613 })
614 }
615
616 pub fn fullnodes(&self) -> impl Iterator<Item = &Node> {
618 self.nodes
619 .values()
620 .filter(|node| node.config().consensus_config.is_none())
621 }
622
623 pub async fn spawn_new_node(&mut self, config: NodeConfig) -> SuiNodeHandle {
624 let name = config.protocol_public_key();
625 let node = Node::new(config);
626 node.start().await.unwrap();
627 let handle = node.get_node_handle().unwrap();
628 self.nodes.insert(name, node);
629 handle
630 }
631
632 pub fn get_fullnode_config_builder(&self) -> FullnodeConfigBuilder {
633 self.fullnode_config_builder.clone()
634 }
635}
636
637#[derive(Debug)]
638enum SwarmDirectory {
639 Persistent(PathBuf),
640 Temporary(TempDir),
641}
642
643impl SwarmDirectory {
644 fn new_temporary() -> Self {
645 SwarmDirectory::Temporary(nondeterministic!(TempDir::new().unwrap()))
646 }
647}
648
649impl ops::Deref for SwarmDirectory {
650 type Target = Path;
651
652 fn deref(&self) -> &Self::Target {
653 match self {
654 SwarmDirectory::Persistent(dir) => dir.deref(),
655 SwarmDirectory::Temporary(dir) => dir.path(),
656 }
657 }
658}
659
660impl AsRef<Path> for SwarmDirectory {
661 fn as_ref(&self) -> &Path {
662 match self {
663 SwarmDirectory::Persistent(dir) => dir.as_ref(),
664 SwarmDirectory::Temporary(dir) => dir.as_ref(),
665 }
666 }
667}
668
669#[cfg(test)]
670mod test {
671 use super::Swarm;
672 use std::num::NonZeroUsize;
673
674 #[tokio::test]
675 async fn launch() {
676 telemetry_subscribers::init_for_testing();
677 let mut swarm = Swarm::builder()
678 .committee_size(NonZeroUsize::new(4).unwrap())
679 .with_fullnode_count(1)
680 .build();
681
682 swarm.launch().await.unwrap();
683
684 for validator in swarm.validator_nodes() {
685 validator.health_check(true).await.unwrap();
686 }
687
688 for fullnode in swarm.fullnodes() {
689 fullnode.health_check(false).await.unwrap();
690 }
691
692 println!("hello");
693 }
694}