1use crate::ant_protocol::CHUNK_PROTOCOL_ID;
7use crate::config::{default_root_dir, NODES_SUBDIR, NODE_IDENTITY_FILENAME};
8use crate::logging::{debug, info, warn};
9use crate::payment::{
10 EvmVerifierConfig, PaymentVerifier, PaymentVerifierConfig, PriceFloorConfig, QuoteGenerator,
11 QuotingMetricsTracker,
12};
13use crate::replication::config::ReplicationConfig;
14use crate::storage::{AntProtocol, LmdbStorage, LmdbStorageConfig};
15use evmlib::Network as EvmNetwork;
16use evmlib::RewardsAddress;
17use rand::Rng;
18use saorsa_core::identity::NodeIdentity;
19use saorsa_core::{
20 IPDiversityConfig, MultiAddr, NodeConfig as CoreNodeConfig, P2PEvent, P2PNode, PeerId,
21};
22use std::net::{Ipv4Addr, SocketAddr};
23use std::path::PathBuf;
24use std::sync::Arc;
25use std::time::Duration;
26use tokio::sync::RwLock;
27use tokio::task::JoinHandle;
28use tokio::time::Instant;
29use tokio_util::sync::CancellationToken;
30
31pub const DEVNET_PORT_RANGE_MIN: u16 = 20_000;
37
38pub const DEVNET_PORT_RANGE_MAX: u16 = 60_000;
40
41const DEFAULT_SPAWN_DELAY_MS: u64 = 200;
47
48const DEFAULT_STABILIZATION_TIMEOUT_SECS: u64 = 120;
50
51const DEFAULT_NODE_STARTUP_TIMEOUT_SECS: u64 = 30;
53
54const MINIMAL_STABILIZATION_TIMEOUT_SECS: u64 = 30;
56
57const SMALL_STABILIZATION_TIMEOUT_SECS: u64 = 60;
59
60const NODE_READY_POLL_INTERVAL_MS: u64 = 100;
62
63const STABILIZATION_POLL_INTERVAL_SECS: u64 = 1;
65
66const STABILIZATION_MIN_CONNECTIONS_CAP: usize = 3;
68
69const HEALTH_CHECK_INTERVAL_SECS: u64 = 5;
71
72const DEVNET_PAYMENT_CACHE_CAPACITY: usize = 1000;
78
79const DEVNET_REWARDS_ADDRESS: [u8; 20] = [0x01; 20];
81
82const DEVNET_INITIAL_RECORDS: usize = 1000;
84
85pub const DEFAULT_NODE_COUNT: usize = 25;
91
92pub const DEFAULT_BOOTSTRAP_COUNT: usize = 3;
94
95pub const MINIMAL_NODE_COUNT: usize = 5;
97
98pub const MINIMAL_BOOTSTRAP_COUNT: usize = 2;
100
101pub const SMALL_NODE_COUNT: usize = 10;
103
104#[derive(Debug, thiserror::Error)]
106pub enum DevnetError {
107 #[error("Configuration error: {0}")]
109 Config(String),
110
111 #[error("Node startup error: {0}")]
113 Startup(String),
114
115 #[error("Network stabilization error: {0}")]
117 Stabilization(String),
118
119 #[error("IO error: {0}")]
121 Io(#[from] std::io::Error),
122
123 #[error("Core error: {0}")]
125 Core(String),
126}
127
128pub type Result<T> = std::result::Result<T, DevnetError>;
130
131#[derive(Debug, Clone)]
136pub struct DevnetConfig {
137 pub node_count: usize,
139
140 pub base_port: u16,
142
143 pub bootstrap_count: usize,
145
146 pub data_dir: PathBuf,
148
149 pub spawn_delay: Duration,
151
152 pub stabilization_timeout: Duration,
154
155 pub node_startup_timeout: Duration,
157
158 pub enable_node_logging: bool,
160
161 pub cleanup_data_dir: bool,
163
164 pub evm_network: Option<EvmNetwork>,
168
169 pub advertise_ip: Option<Ipv4Addr>,
172}
173
174impl Default for DevnetConfig {
175 fn default() -> Self {
176 let mut rng = rand::thread_rng();
177
178 #[allow(clippy::cast_possible_truncation)] let max_base_port = DEVNET_PORT_RANGE_MAX.saturating_sub(DEFAULT_NODE_COUNT as u16);
180 let base_port = rng.gen_range(DEVNET_PORT_RANGE_MIN..max_base_port);
181
182 Self {
183 node_count: DEFAULT_NODE_COUNT,
184 base_port,
185 bootstrap_count: DEFAULT_BOOTSTRAP_COUNT,
186 data_dir: default_root_dir(),
187 spawn_delay: Duration::from_millis(DEFAULT_SPAWN_DELAY_MS),
188 stabilization_timeout: Duration::from_secs(DEFAULT_STABILIZATION_TIMEOUT_SECS),
189 node_startup_timeout: Duration::from_secs(DEFAULT_NODE_STARTUP_TIMEOUT_SECS),
190 enable_node_logging: false,
191 cleanup_data_dir: true,
192 evm_network: None,
193 advertise_ip: None,
194 }
195 }
196}
197
198impl DevnetConfig {
199 #[must_use]
201 pub fn minimal() -> Self {
202 Self {
203 node_count: MINIMAL_NODE_COUNT,
204 bootstrap_count: MINIMAL_BOOTSTRAP_COUNT,
205 stabilization_timeout: Duration::from_secs(MINIMAL_STABILIZATION_TIMEOUT_SECS),
206 ..Self::default()
207 }
208 }
209
210 #[must_use]
212 pub fn small() -> Self {
213 Self {
214 node_count: SMALL_NODE_COUNT,
215 bootstrap_count: MINIMAL_BOOTSTRAP_COUNT,
216 stabilization_timeout: Duration::from_secs(SMALL_STABILIZATION_TIMEOUT_SECS),
217 ..Self::default()
218 }
219 }
220}
221
222pub use ant_protocol::devnet_manifest::{DevnetEvmInfo, DevnetManifest};
226
227#[derive(Debug, Clone)]
229pub enum NetworkState {
230 Uninitialized,
232 BootstrappingPhase,
234 NodeSpawningPhase,
236 Stabilizing,
238 Ready,
240 ShuttingDown,
242 Stopped,
244}
245
246#[derive(Debug, Clone)]
248pub enum NodeState {
249 Pending,
251 Starting,
253 Running,
255 Connected,
257 Stopped,
259 Failed(String),
261}
262
263#[allow(dead_code)]
265pub struct DevnetNode {
266 index: usize,
267 label: String,
268 peer_id: PeerId,
269 port: u16,
270 data_dir: PathBuf,
271 p2p_node: Option<Arc<P2PNode>>,
272 ant_protocol: Option<Arc<AntProtocol>>,
273 is_bootstrap: bool,
274 state: Arc<RwLock<NodeState>>,
275 bootstrap_addrs: Vec<MultiAddr>,
276 protocol_task: Option<JoinHandle<()>>,
277}
278
279impl DevnetNode {
280 pub async fn peer_count(&self) -> usize {
282 if let Some(ref node) = self.p2p_node {
283 node.peer_count().await
284 } else {
285 0
286 }
287 }
288}
289
290pub struct Devnet {
292 config: DevnetConfig,
293 nodes: Vec<DevnetNode>,
294 shutdown: CancellationToken,
295 state: Arc<RwLock<NetworkState>>,
296 health_monitor: Option<JoinHandle<()>>,
297}
298
299impl Devnet {
300 pub async fn new(mut config: DevnetConfig) -> Result<Self> {
308 if config.bootstrap_count >= config.node_count {
309 return Err(DevnetError::Config(
310 "Bootstrap count must be less than node count".to_string(),
311 ));
312 }
313
314 if config.bootstrap_count == 0 {
315 return Err(DevnetError::Config(
316 "At least one bootstrap node is required".to_string(),
317 ));
318 }
319
320 let node_count = config.node_count;
321 let node_count_u16 = u16::try_from(node_count).map_err(|_| {
322 DevnetError::Config(format!("Node count {node_count} exceeds u16::MAX"))
323 })?;
324
325 if config.base_port == 0 {
326 let mut rng = rand::thread_rng();
327 let max_base_port = DEVNET_PORT_RANGE_MAX.saturating_sub(node_count_u16);
328 config.base_port = rng.gen_range(DEVNET_PORT_RANGE_MIN..max_base_port);
329 }
330
331 let base_port = config.base_port;
332 let max_port = base_port
333 .checked_add(node_count_u16)
334 .ok_or_else(|| {
335 DevnetError::Config(format!(
336 "Port range overflow: base_port {base_port} + node_count {node_count} exceeds u16::MAX"
337 ))
338 })?;
339 if max_port > DEVNET_PORT_RANGE_MAX {
340 return Err(DevnetError::Config(format!(
341 "Port range overflow: max port {max_port} exceeds DEVNET_PORT_RANGE_MAX {DEVNET_PORT_RANGE_MAX}"
342 )));
343 }
344
345 tokio::fs::create_dir_all(&config.data_dir).await?;
346
347 Ok(Self {
348 config,
349 nodes: Vec::new(),
350 shutdown: CancellationToken::new(),
351 state: Arc::new(RwLock::new(NetworkState::Uninitialized)),
352 health_monitor: None,
353 })
354 }
355
356 pub async fn start(&mut self) -> Result<()> {
363 info!(
364 "Starting devnet with {} nodes ({} bootstrap)",
365 self.config.node_count, self.config.bootstrap_count
366 );
367
368 *self.state.write().await = NetworkState::BootstrappingPhase;
369 self.start_bootstrap_nodes().await?;
370
371 *self.state.write().await = NetworkState::NodeSpawningPhase;
372 self.start_regular_nodes().await?;
373
374 *self.state.write().await = NetworkState::Stabilizing;
375 self.wait_for_stabilization().await?;
376
377 self.start_health_monitor();
378
379 *self.state.write().await = NetworkState::Ready;
380 info!("Devnet is ready");
381 Ok(())
382 }
383
384 pub async fn shutdown(&mut self) -> Result<()> {
390 info!("Shutting down devnet");
391 *self.state.write().await = NetworkState::ShuttingDown;
392
393 self.shutdown.cancel();
394
395 if let Some(handle) = self.health_monitor.take() {
396 handle.abort();
397 }
398
399 let mut shutdown_futures = Vec::with_capacity(self.nodes.len());
400 for node in self.nodes.iter_mut().rev() {
401 debug!("Stopping node {}", node.index);
402 if let Some(handle) = node.protocol_task.take() {
403 handle.abort();
404 }
405
406 let node_index = node.index;
407 let node_state = Arc::clone(&node.state);
408 let p2p_node = node.p2p_node.take();
409
410 shutdown_futures.push(async move {
411 if let Some(p2p) = p2p_node {
412 if let Err(e) = p2p.shutdown().await {
413 warn!("Error shutting down node {node_index}: {e}");
414 }
415 }
416 *node_state.write().await = NodeState::Stopped;
417 });
418 }
419 futures::future::join_all(shutdown_futures).await;
420
421 if self.config.cleanup_data_dir {
422 if let Err(e) = tokio::fs::remove_dir_all(&self.config.data_dir).await {
423 warn!("Failed to cleanup devnet data directory: {e}");
424 }
425 }
426
427 *self.state.write().await = NetworkState::Stopped;
428 info!("Devnet shutdown complete");
429 Ok(())
430 }
431
432 #[must_use]
434 pub fn config(&self) -> &DevnetConfig {
435 &self.config
436 }
437
438 #[must_use]
440 pub fn bootstrap_addrs(&self) -> Vec<MultiAddr> {
441 self.nodes
442 .iter()
443 .take(self.config.bootstrap_count)
444 .map(|n| {
445 MultiAddr::quic(SocketAddr::from((
446 self.config.advertise_ip.unwrap_or(Ipv4Addr::LOCALHOST),
447 n.port,
448 )))
449 })
450 .collect()
451 }
452
453 async fn start_bootstrap_nodes(&mut self) -> Result<()> {
454 info!("Starting {} bootstrap nodes", self.config.bootstrap_count);
455
456 for i in 0..self.config.bootstrap_count {
457 let node = self.create_node(i, true, vec![]).await?;
458 self.start_node(node).await?;
459 tokio::time::sleep(self.config.spawn_delay).await;
460 }
461
462 self.wait_for_nodes_ready(0..self.config.bootstrap_count)
463 .await?;
464
465 info!("All bootstrap nodes are ready");
466 Ok(())
467 }
468
469 async fn start_regular_nodes(&mut self) -> Result<()> {
470 let regular_count = self.config.node_count - self.config.bootstrap_count;
471 info!("Starting {} regular nodes", regular_count);
472
473 let bootstrap_addrs: Vec<MultiAddr> = self
474 .nodes
475 .get(0..self.config.bootstrap_count)
476 .ok_or_else(|| {
477 DevnetError::Config(format!(
478 "Bootstrap count {} exceeds nodes length {}",
479 self.config.bootstrap_count,
480 self.nodes.len()
481 ))
482 })?
483 .iter()
484 .map(|n| {
485 MultiAddr::quic(SocketAddr::from((
486 self.config.advertise_ip.unwrap_or(Ipv4Addr::LOCALHOST),
487 n.port,
488 )))
489 })
490 .collect();
491
492 for i in self.config.bootstrap_count..self.config.node_count {
493 let node = self.create_node(i, false, bootstrap_addrs.clone()).await?;
494 self.start_node(node).await?;
495 tokio::time::sleep(self.config.spawn_delay).await;
496 }
497
498 info!("All regular nodes started");
499 Ok(())
500 }
501
502 async fn create_node(
503 &self,
504 index: usize,
505 is_bootstrap: bool,
506 bootstrap_addrs: Vec<MultiAddr>,
507 ) -> Result<DevnetNode> {
508 let index_u16 = u16::try_from(index)
509 .map_err(|_| DevnetError::Config(format!("Node index {index} exceeds u16::MAX")))?;
510 let port = self.config.base_port + index_u16;
511
512 let identity = NodeIdentity::generate()
514 .map_err(|e| DevnetError::Core(format!("Failed to generate node identity: {e}")))?;
515 let peer_id = *identity.peer_id();
516 let label = format!("devnet_node_{index}");
517 let data_dir = self
518 .config
519 .data_dir
520 .join(NODES_SUBDIR)
521 .join(peer_id.to_hex());
522
523 tokio::fs::create_dir_all(&data_dir).await?;
524
525 identity
526 .save_to_file(&data_dir.join(NODE_IDENTITY_FILENAME))
527 .await
528 .map_err(|e| DevnetError::Core(format!("Failed to save node identity: {e}")))?;
529
530 let ant_protocol = Self::create_ant_protocol(&data_dir, &identity, &self.config).await?;
531
532 Ok(DevnetNode {
533 index,
534 label,
535 peer_id,
536 port,
537 data_dir,
538 p2p_node: None,
539 ant_protocol: Some(Arc::new(ant_protocol)),
540 is_bootstrap,
541 state: Arc::new(RwLock::new(NodeState::Pending)),
542 bootstrap_addrs,
543 protocol_task: None,
544 })
545 }
546
547 async fn create_ant_protocol(
548 data_dir: &std::path::Path,
549 identity: &NodeIdentity,
550 config: &DevnetConfig,
551 ) -> Result<AntProtocol> {
552 let storage_config = LmdbStorageConfig {
553 root_dir: data_dir.to_path_buf(),
554 verify_on_read: true,
555 ..LmdbStorageConfig::default()
556 };
557 let storage = LmdbStorage::new(storage_config)
558 .await
559 .map_err(|e| DevnetError::Core(format!("Failed to create LMDB storage: {e}")))?;
560
561 let evm_config = EvmVerifierConfig {
562 network: config
563 .evm_network
564 .clone()
565 .unwrap_or(EvmNetwork::ArbitrumOne),
566 };
567
568 let rewards_address = RewardsAddress::new(DEVNET_REWARDS_ADDRESS);
569 let replication_config = ReplicationConfig::default();
570 let payment_config = PaymentVerifierConfig {
571 evm: evm_config,
572 cache_capacity: DEVNET_PAYMENT_CACHE_CAPACITY,
573 close_group_size: replication_config.close_group_size,
574 local_rewards_address: rewards_address,
575 price_floor: PriceFloorConfig::default(),
576 };
577 let payment_verifier = PaymentVerifier::new(payment_config);
578 let metrics_tracker = QuotingMetricsTracker::new(DEVNET_INITIAL_RECORDS);
579 let mut quote_generator = QuoteGenerator::new(rewards_address, metrics_tracker);
580
581 crate::payment::wire_ml_dsa_signer(&mut quote_generator, identity)
583 .map_err(|e| DevnetError::Startup(format!("Failed to wire ML-DSA-65 signer: {e}")))?;
584
585 let storage = Arc::new(storage);
586 let payment_verifier = Arc::new(payment_verifier);
587
588 Ok(AntProtocol::new(
589 storage,
590 payment_verifier,
591 Arc::new(quote_generator),
592 ))
593 }
594
595 async fn start_node(&mut self, mut node: DevnetNode) -> Result<()> {
596 debug!("Starting node {} on port {}", node.index, node.port);
597 *node.state.write().await = NodeState::Starting;
598
599 let mut core_config = CoreNodeConfig::builder()
600 .port(node.port)
601 .local(self.config.advertise_ip.is_none())
602 .max_message_size(crate::ant_protocol::MAX_WIRE_MESSAGE_SIZE)
603 .build()
604 .map_err(|e| DevnetError::Core(format!("Failed to create core config: {e}")))?;
605
606 let identity = NodeIdentity::load_from_file(
608 &node.data_dir.join(crate::config::NODE_IDENTITY_FILENAME),
609 )
610 .await
611 .map_err(|e| DevnetError::Core(format!("Failed to load node identity: {e}")))?;
612
613 core_config.node_identity = Some(Arc::new(identity));
614 core_config
615 .bootstrap_peers
616 .clone_from(&node.bootstrap_addrs);
617 core_config.diversity_config = Some(IPDiversityConfig::permissive());
618
619 let index = node.index;
620 let p2p_node = P2PNode::new(core_config)
621 .await
622 .map_err(|e| DevnetError::Startup(format!("Failed to create node {index}: {e}")))?;
623
624 p2p_node
625 .start()
626 .await
627 .map_err(|e| DevnetError::Startup(format!("Failed to start node {index}: {e}")))?;
628
629 node.p2p_node = Some(Arc::new(p2p_node));
630 *node.state.write().await = NodeState::Running;
631
632 if let (Some(ref p2p), Some(ref protocol)) = (&node.p2p_node, &node.ant_protocol) {
633 protocol.attach_p2p_node(Arc::clone(p2p));
635
636 let mut events = p2p.subscribe_events();
637 let p2p_clone = Arc::clone(p2p);
638 let protocol_clone = Arc::clone(protocol);
639 let node_index = node.index;
640 node.protocol_task = Some(tokio::spawn(async move {
641 while let Ok(event) = events.recv().await {
642 if let P2PEvent::Message {
643 topic,
644 source: Some(source),
645 data,
646 ..
647 } = event
648 {
649 if topic == CHUNK_PROTOCOL_ID {
650 debug!(
651 "Node {node_index} received chunk protocol message from {source}"
652 );
653 let protocol = Arc::clone(&protocol_clone);
654 let p2p = Arc::clone(&p2p_clone);
655 tokio::spawn(async move {
656 match protocol.try_handle_request(&data).await {
657 Ok(Some(response)) => {
658 if let Err(e) = p2p
659 .send_message(
660 &source,
661 CHUNK_PROTOCOL_ID,
662 response.to_vec(),
663 &[],
664 )
665 .await
666 {
667 warn!(
668 "Node {node_index} failed to send response to {source}: {e}"
669 );
670 }
671 }
672 Ok(None) => {}
673 Err(e) => {
674 warn!("Node {node_index} protocol handler error: {e}");
675 }
676 }
677 });
678 }
679 }
680 }
681 }));
682 }
683
684 debug!("Node {} started successfully", node.index);
685 self.nodes.push(node);
686 Ok(())
687 }
688
689 async fn wait_for_nodes_ready(&self, range: std::ops::Range<usize>) -> Result<()> {
690 let deadline = Instant::now() + self.config.node_startup_timeout;
691
692 for i in range {
693 while Instant::now() < deadline {
694 let node = self.nodes.get(i).ok_or_else(|| {
695 DevnetError::Config(format!(
696 "Node index {i} out of bounds (len: {})",
697 self.nodes.len()
698 ))
699 })?;
700 let state = node.state.read().await.clone();
701 match state {
702 NodeState::Running | NodeState::Connected => break,
703 NodeState::Failed(ref e) => {
704 return Err(DevnetError::Startup(format!("Node {i} failed: {e}")));
705 }
706 _ => {
707 tokio::time::sleep(Duration::from_millis(NODE_READY_POLL_INTERVAL_MS))
708 .await;
709 }
710 }
711 }
712 }
713 Ok(())
714 }
715
716 async fn wait_for_stabilization(&self) -> Result<()> {
717 let deadline = Instant::now() + self.config.stabilization_timeout;
718 let min_connections = self
719 .config
720 .bootstrap_count
721 .min(STABILIZATION_MIN_CONNECTIONS_CAP);
722
723 info!(
724 "Waiting for devnet stabilization (min {} connections per node)",
725 min_connections
726 );
727
728 while Instant::now() < deadline {
729 let mut all_connected = true;
730 let mut total_connections = 0;
731
732 for node in &self.nodes {
733 let peer_count = node.peer_count().await;
734 total_connections += peer_count;
735
736 if peer_count < min_connections {
737 all_connected = false;
738 }
739 }
740
741 if all_connected {
742 info!("Devnet stabilized: {} total connections", total_connections);
743 return Ok(());
744 }
745
746 debug!(
747 "Waiting for stabilization: {} total connections",
748 total_connections
749 );
750 tokio::time::sleep(Duration::from_secs(STABILIZATION_POLL_INTERVAL_SECS)).await;
751 }
752
753 Err(DevnetError::Stabilization(
754 "Devnet failed to stabilize within timeout".to_string(),
755 ))
756 }
757
758 fn start_health_monitor(&mut self) {
759 let nodes: Vec<Arc<P2PNode>> = self
760 .nodes
761 .iter()
762 .filter_map(|n| n.p2p_node.clone())
763 .collect();
764 let shutdown = self.shutdown.clone();
765
766 self.health_monitor = Some(tokio::spawn(async move {
767 let check_interval = Duration::from_secs(HEALTH_CHECK_INTERVAL_SECS);
768
769 loop {
770 tokio::select! {
771 () = shutdown.cancelled() => break,
772 () = tokio::time::sleep(check_interval) => {
773 for (i, node) in nodes.iter().enumerate() {
774 if !node.is_running() {
775 warn!("Node {} appears unhealthy", i);
776 }
777 }
778 }
779 }
780 }
781 }));
782 }
783}
784
785impl Drop for Devnet {
786 fn drop(&mut self) {
787 self.shutdown.cancel();
788 if let Some(handle) = self.health_monitor.take() {
789 handle.abort();
790 }
791 }
792}
793
794#[cfg(test)]
795mod tests {
796 use super::*;
797
798 #[test]
803 fn default_config_has_no_advertise_ip() {
804 assert!(DevnetConfig::default().advertise_ip.is_none());
805 }
806}