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, ChunkRequestContext, ChunkStore, ChunkStoreConfig};
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
85async fn handle_chunk_message(
86 protocol: Arc<AntProtocol>,
87 p2p: Arc<P2PNode>,
88 source: PeerId,
89 data: Vec<u8>,
90 node_index: usize,
91 received_at: Instant,
92) {
93 let handled = protocol
94 .try_handle_request_with_context(
95 &data,
96 Some(ChunkRequestContext::new(
97 source.to_string(),
98 received_at.into(),
99 Duration::ZERO,
100 )),
101 )
102 .await;
103 let telemetry = handled.get_telemetry;
104 match handled.response {
105 Ok(Some(response)) => {
106 let send_started = Instant::now();
107 let send_result = p2p
108 .send_message(&source, CHUNK_PROTOCOL_ID, response.to_vec(), &[])
109 .await;
110 if let Some(telemetry) = telemetry {
111 telemetry.finish_send(send_started.elapsed(), send_result.is_ok());
112 }
113 if let Err(e) = send_result {
114 warn!("Node {node_index} failed to send response to {source}: {e}");
115 }
116 }
117 Ok(None) => {
118 if let Some(telemetry) = telemetry {
119 telemetry.finish_without_send("no_response");
120 }
121 }
122 Err(e) => {
123 if let Some(telemetry) = telemetry {
124 telemetry.finish_without_send("encode_error");
125 }
126 warn!("Node {node_index} protocol handler error: {e}");
127 }
128 }
129}
130
131pub const DEFAULT_NODE_COUNT: usize = 25;
137
138pub const DEFAULT_BOOTSTRAP_COUNT: usize = 3;
140
141pub const MINIMAL_NODE_COUNT: usize = 5;
143
144pub const MINIMAL_BOOTSTRAP_COUNT: usize = 2;
146
147pub const SMALL_NODE_COUNT: usize = 10;
149
150#[derive(Debug, thiserror::Error)]
152pub enum DevnetError {
153 #[error("Configuration error: {0}")]
155 Config(String),
156
157 #[error("Node startup error: {0}")]
159 Startup(String),
160
161 #[error("Network stabilization error: {0}")]
163 Stabilization(String),
164
165 #[error("IO error: {0}")]
167 Io(#[from] std::io::Error),
168
169 #[error("Core error: {0}")]
171 Core(String),
172}
173
174pub type Result<T> = std::result::Result<T, DevnetError>;
176
177#[derive(Debug, Clone)]
182pub struct DevnetConfig {
183 pub node_count: usize,
185
186 pub base_port: u16,
188
189 pub bootstrap_count: usize,
191
192 pub data_dir: PathBuf,
194
195 pub spawn_delay: Duration,
197
198 pub stabilization_timeout: Duration,
200
201 pub node_startup_timeout: Duration,
203
204 pub enable_node_logging: bool,
206
207 pub cleanup_data_dir: bool,
209
210 pub evm_network: Option<EvmNetwork>,
214
215 pub advertise_ip: Option<Ipv4Addr>,
218}
219
220impl Default for DevnetConfig {
221 fn default() -> Self {
222 let mut rng = rand::thread_rng();
223
224 #[allow(clippy::cast_possible_truncation)] let max_base_port = DEVNET_PORT_RANGE_MAX.saturating_sub(DEFAULT_NODE_COUNT as u16);
226 let base_port = rng.gen_range(DEVNET_PORT_RANGE_MIN..max_base_port);
227
228 Self {
229 node_count: DEFAULT_NODE_COUNT,
230 base_port,
231 bootstrap_count: DEFAULT_BOOTSTRAP_COUNT,
232 data_dir: default_root_dir(),
233 spawn_delay: Duration::from_millis(DEFAULT_SPAWN_DELAY_MS),
234 stabilization_timeout: Duration::from_secs(DEFAULT_STABILIZATION_TIMEOUT_SECS),
235 node_startup_timeout: Duration::from_secs(DEFAULT_NODE_STARTUP_TIMEOUT_SECS),
236 enable_node_logging: false,
237 cleanup_data_dir: true,
238 evm_network: None,
239 advertise_ip: None,
240 }
241 }
242}
243
244impl DevnetConfig {
245 #[must_use]
247 pub fn minimal() -> Self {
248 Self {
249 node_count: MINIMAL_NODE_COUNT,
250 bootstrap_count: MINIMAL_BOOTSTRAP_COUNT,
251 stabilization_timeout: Duration::from_secs(MINIMAL_STABILIZATION_TIMEOUT_SECS),
252 ..Self::default()
253 }
254 }
255
256 #[must_use]
258 pub fn small() -> Self {
259 Self {
260 node_count: SMALL_NODE_COUNT,
261 bootstrap_count: MINIMAL_BOOTSTRAP_COUNT,
262 stabilization_timeout: Duration::from_secs(SMALL_STABILIZATION_TIMEOUT_SECS),
263 ..Self::default()
264 }
265 }
266}
267
268pub use ant_protocol::devnet_manifest::{DevnetEvmInfo, DevnetManifest};
272
273#[derive(Debug, Clone)]
275pub enum NetworkState {
276 Uninitialized,
278 BootstrappingPhase,
280 NodeSpawningPhase,
282 Stabilizing,
284 Ready,
286 ShuttingDown,
288 Stopped,
290}
291
292#[derive(Debug, Clone)]
294pub enum NodeState {
295 Pending,
297 Starting,
299 Running,
301 Connected,
303 Stopped,
305 Failed(String),
307}
308
309#[allow(dead_code)]
311pub struct DevnetNode {
312 index: usize,
313 label: String,
314 peer_id: PeerId,
315 port: u16,
316 data_dir: PathBuf,
317 p2p_node: Option<Arc<P2PNode>>,
318 ant_protocol: Option<Arc<AntProtocol>>,
319 is_bootstrap: bool,
320 state: Arc<RwLock<NodeState>>,
321 bootstrap_addrs: Vec<MultiAddr>,
322 protocol_task: Option<JoinHandle<()>>,
323}
324
325impl DevnetNode {
326 pub async fn peer_count(&self) -> usize {
328 if let Some(ref node) = self.p2p_node {
329 node.peer_count().await
330 } else {
331 0
332 }
333 }
334}
335
336pub struct Devnet {
338 config: DevnetConfig,
339 nodes: Vec<DevnetNode>,
340 shutdown: CancellationToken,
341 state: Arc<RwLock<NetworkState>>,
342 health_monitor: Option<JoinHandle<()>>,
343}
344
345impl Devnet {
346 pub async fn new(mut config: DevnetConfig) -> Result<Self> {
354 if config.bootstrap_count >= config.node_count {
355 return Err(DevnetError::Config(
356 "Bootstrap count must be less than node count".to_string(),
357 ));
358 }
359
360 if config.bootstrap_count == 0 {
361 return Err(DevnetError::Config(
362 "At least one bootstrap node is required".to_string(),
363 ));
364 }
365
366 let node_count = config.node_count;
367 let node_count_u16 = u16::try_from(node_count).map_err(|_| {
368 DevnetError::Config(format!("Node count {node_count} exceeds u16::MAX"))
369 })?;
370
371 if config.base_port == 0 {
372 let mut rng = rand::thread_rng();
373 let max_base_port = DEVNET_PORT_RANGE_MAX.saturating_sub(node_count_u16);
374 config.base_port = rng.gen_range(DEVNET_PORT_RANGE_MIN..max_base_port);
375 }
376
377 let base_port = config.base_port;
378 let max_port = base_port
379 .checked_add(node_count_u16)
380 .ok_or_else(|| {
381 DevnetError::Config(format!(
382 "Port range overflow: base_port {base_port} + node_count {node_count} exceeds u16::MAX"
383 ))
384 })?;
385 if max_port > DEVNET_PORT_RANGE_MAX {
386 return Err(DevnetError::Config(format!(
387 "Port range overflow: max port {max_port} exceeds DEVNET_PORT_RANGE_MAX {DEVNET_PORT_RANGE_MAX}"
388 )));
389 }
390
391 tokio::fs::create_dir_all(&config.data_dir).await?;
392
393 Ok(Self {
394 config,
395 nodes: Vec::new(),
396 shutdown: CancellationToken::new(),
397 state: Arc::new(RwLock::new(NetworkState::Uninitialized)),
398 health_monitor: None,
399 })
400 }
401
402 pub async fn start(&mut self) -> Result<()> {
409 info!(
410 "Starting devnet with {} nodes ({} bootstrap)",
411 self.config.node_count, self.config.bootstrap_count
412 );
413
414 *self.state.write().await = NetworkState::BootstrappingPhase;
415 self.start_bootstrap_nodes().await?;
416
417 *self.state.write().await = NetworkState::NodeSpawningPhase;
418 self.start_regular_nodes().await?;
419
420 *self.state.write().await = NetworkState::Stabilizing;
421 self.wait_for_stabilization().await?;
422
423 self.start_health_monitor();
424
425 *self.state.write().await = NetworkState::Ready;
426 info!("Devnet is ready");
427 Ok(())
428 }
429
430 pub async fn shutdown(&mut self) -> Result<()> {
436 info!("Shutting down devnet");
437 *self.state.write().await = NetworkState::ShuttingDown;
438
439 self.shutdown.cancel();
440
441 if let Some(handle) = self.health_monitor.take() {
442 handle.abort();
443 }
444
445 let mut shutdown_futures = Vec::with_capacity(self.nodes.len());
446 for node in self.nodes.iter_mut().rev() {
447 debug!("Stopping node {}", node.index);
448 if let Some(handle) = node.protocol_task.take() {
449 handle.abort();
450 }
451
452 let node_index = node.index;
453 let node_state = Arc::clone(&node.state);
454 let p2p_node = node.p2p_node.take();
455
456 shutdown_futures.push(async move {
457 if let Some(p2p) = p2p_node {
458 if let Err(e) = p2p.shutdown().await {
459 warn!("Error shutting down node {node_index}: {e}");
460 }
461 }
462 *node_state.write().await = NodeState::Stopped;
463 });
464 }
465 futures::future::join_all(shutdown_futures).await;
466
467 if self.config.cleanup_data_dir {
468 if let Err(e) = tokio::fs::remove_dir_all(&self.config.data_dir).await {
469 warn!("Failed to cleanup devnet data directory: {e}");
470 }
471 }
472
473 *self.state.write().await = NetworkState::Stopped;
474 info!("Devnet shutdown complete");
475 Ok(())
476 }
477
478 #[must_use]
480 pub fn config(&self) -> &DevnetConfig {
481 &self.config
482 }
483
484 #[must_use]
486 pub fn bootstrap_addrs(&self) -> Vec<MultiAddr> {
487 self.nodes
488 .iter()
489 .take(self.config.bootstrap_count)
490 .map(|n| {
491 MultiAddr::quic(SocketAddr::from((
492 self.config.advertise_ip.unwrap_or(Ipv4Addr::LOCALHOST),
493 n.port,
494 )))
495 })
496 .collect()
497 }
498
499 async fn start_bootstrap_nodes(&mut self) -> Result<()> {
500 info!("Starting {} bootstrap nodes", self.config.bootstrap_count);
501
502 for i in 0..self.config.bootstrap_count {
503 let node = self.create_node(i, true, vec![]).await?;
504 self.start_node(node).await?;
505 tokio::time::sleep(self.config.spawn_delay).await;
506 }
507
508 self.wait_for_nodes_ready(0..self.config.bootstrap_count)
509 .await?;
510
511 info!("All bootstrap nodes are ready");
512 Ok(())
513 }
514
515 async fn start_regular_nodes(&mut self) -> Result<()> {
516 let regular_count = self.config.node_count - self.config.bootstrap_count;
517 info!("Starting {} regular nodes", regular_count);
518
519 let bootstrap_addrs: Vec<MultiAddr> = self
520 .nodes
521 .get(0..self.config.bootstrap_count)
522 .ok_or_else(|| {
523 DevnetError::Config(format!(
524 "Bootstrap count {} exceeds nodes length {}",
525 self.config.bootstrap_count,
526 self.nodes.len()
527 ))
528 })?
529 .iter()
530 .map(|n| {
531 MultiAddr::quic(SocketAddr::from((
532 self.config.advertise_ip.unwrap_or(Ipv4Addr::LOCALHOST),
533 n.port,
534 )))
535 })
536 .collect();
537
538 for i in self.config.bootstrap_count..self.config.node_count {
539 let node = self.create_node(i, false, bootstrap_addrs.clone()).await?;
540 self.start_node(node).await?;
541 tokio::time::sleep(self.config.spawn_delay).await;
542 }
543
544 info!("All regular nodes started");
545 Ok(())
546 }
547
548 async fn create_node(
549 &self,
550 index: usize,
551 is_bootstrap: bool,
552 bootstrap_addrs: Vec<MultiAddr>,
553 ) -> Result<DevnetNode> {
554 let index_u16 = u16::try_from(index)
555 .map_err(|_| DevnetError::Config(format!("Node index {index} exceeds u16::MAX")))?;
556 let port = self.config.base_port + index_u16;
557
558 let identity = NodeIdentity::generate()
560 .map_err(|e| DevnetError::Core(format!("Failed to generate node identity: {e}")))?;
561 let peer_id = *identity.peer_id();
562 let label = format!("devnet_node_{index}");
563 let data_dir = self
564 .config
565 .data_dir
566 .join(NODES_SUBDIR)
567 .join(peer_id.to_hex());
568
569 tokio::fs::create_dir_all(&data_dir).await?;
570
571 identity
572 .save_to_file(&data_dir.join(NODE_IDENTITY_FILENAME))
573 .await
574 .map_err(|e| DevnetError::Core(format!("Failed to save node identity: {e}")))?;
575
576 let ant_protocol = Self::create_ant_protocol(&data_dir, &identity, &self.config).await?;
577
578 Ok(DevnetNode {
579 index,
580 label,
581 peer_id,
582 port,
583 data_dir,
584 p2p_node: None,
585 ant_protocol: Some(Arc::new(ant_protocol)),
586 is_bootstrap,
587 state: Arc::new(RwLock::new(NodeState::Pending)),
588 bootstrap_addrs,
589 protocol_task: None,
590 })
591 }
592
593 async fn create_ant_protocol(
594 data_dir: &std::path::Path,
595 identity: &NodeIdentity,
596 config: &DevnetConfig,
597 ) -> Result<AntProtocol> {
598 let storage_config = ChunkStoreConfig {
599 root_dir: data_dir.to_path_buf(),
600 verify_on_read: true,
601 ..ChunkStoreConfig::default()
602 };
603 let storage = ChunkStore::new(storage_config)
604 .await
605 .map_err(|e| DevnetError::Core(format!("Failed to create LMDB storage: {e}")))?;
606
607 let evm_config = EvmVerifierConfig {
608 network: config
609 .evm_network
610 .clone()
611 .unwrap_or(EvmNetwork::ArbitrumOne),
612 };
613
614 let rewards_address = RewardsAddress::new(DEVNET_REWARDS_ADDRESS);
615 let replication_config = ReplicationConfig::default();
616 let payment_config = PaymentVerifierConfig {
617 evm: evm_config,
618 cache_capacity: DEVNET_PAYMENT_CACHE_CAPACITY,
619 close_group_size: replication_config.close_group_size,
620 local_rewards_address: rewards_address,
621 price_floor: PriceFloorConfig::default(),
622 };
623 let payment_verifier = PaymentVerifier::new(payment_config);
624 let metrics_tracker = QuotingMetricsTracker::new(DEVNET_INITIAL_RECORDS);
625 let mut quote_generator = QuoteGenerator::new(rewards_address, metrics_tracker);
626
627 crate::payment::wire_ml_dsa_signer(&mut quote_generator, identity)
629 .map_err(|e| DevnetError::Startup(format!("Failed to wire ML-DSA-65 signer: {e}")))?;
630
631 let storage = Arc::new(storage);
632 let payment_verifier = Arc::new(payment_verifier);
633
634 Ok(AntProtocol::new(
635 storage,
636 payment_verifier,
637 Arc::new(quote_generator),
638 ))
639 }
640
641 async fn start_node(&mut self, mut node: DevnetNode) -> Result<()> {
642 debug!("Starting node {} on port {}", node.index, node.port);
643 *node.state.write().await = NodeState::Starting;
644
645 let mut core_config = CoreNodeConfig::builder()
646 .port(node.port)
647 .local(self.config.advertise_ip.is_none())
648 .max_message_size(crate::ant_protocol::MAX_WIRE_MESSAGE_SIZE)
649 .build()
650 .map_err(|e| DevnetError::Core(format!("Failed to create core config: {e}")))?;
651
652 let identity = NodeIdentity::load_from_file(
654 &node.data_dir.join(crate::config::NODE_IDENTITY_FILENAME),
655 )
656 .await
657 .map_err(|e| DevnetError::Core(format!("Failed to load node identity: {e}")))?;
658
659 core_config.node_identity = Some(Arc::new(identity));
660 core_config
661 .bootstrap_peers
662 .clone_from(&node.bootstrap_addrs);
663 core_config.diversity_config = Some(IPDiversityConfig::permissive());
664
665 let index = node.index;
666 let p2p_node = P2PNode::new(core_config)
667 .await
668 .map_err(|e| DevnetError::Startup(format!("Failed to create node {index}: {e}")))?;
669
670 p2p_node
671 .start()
672 .await
673 .map_err(|e| DevnetError::Startup(format!("Failed to start node {index}: {e}")))?;
674
675 node.p2p_node = Some(Arc::new(p2p_node));
676 *node.state.write().await = NodeState::Running;
677
678 if let (Some(ref p2p), Some(ref protocol)) = (&node.p2p_node, &node.ant_protocol) {
679 protocol.attach_p2p_node(Arc::clone(p2p));
681
682 let mut events = p2p.subscribe_events();
683 let p2p_clone = Arc::clone(p2p);
684 let protocol_clone = Arc::clone(protocol);
685 let node_index = node.index;
686 node.protocol_task = Some(tokio::spawn(async move {
687 while let Ok(event) = events.recv().await {
688 if let P2PEvent::Message {
689 topic,
690 source: Some(source),
691 data,
692 ..
693 } = event
694 {
695 if topic == CHUNK_PROTOCOL_ID {
696 debug!(
697 "Node {node_index} received chunk protocol message from {source}"
698 );
699 let protocol = Arc::clone(&protocol_clone);
700 let p2p = Arc::clone(&p2p_clone);
701 let received_at = Instant::now();
702 tokio::spawn(handle_chunk_message(
703 protocol,
704 p2p,
705 source,
706 data,
707 node_index,
708 received_at,
709 ));
710 }
711 }
712 }
713 }));
714 }
715
716 debug!("Node {} started successfully", node.index);
717 self.nodes.push(node);
718 Ok(())
719 }
720
721 async fn wait_for_nodes_ready(&self, range: std::ops::Range<usize>) -> Result<()> {
722 let deadline = Instant::now() + self.config.node_startup_timeout;
723
724 for i in range {
725 while Instant::now() < deadline {
726 let node = self.nodes.get(i).ok_or_else(|| {
727 DevnetError::Config(format!(
728 "Node index {i} out of bounds (len: {})",
729 self.nodes.len()
730 ))
731 })?;
732 let state = node.state.read().await.clone();
733 match state {
734 NodeState::Running | NodeState::Connected => break,
735 NodeState::Failed(ref e) => {
736 return Err(DevnetError::Startup(format!("Node {i} failed: {e}")));
737 }
738 _ => {
739 tokio::time::sleep(Duration::from_millis(NODE_READY_POLL_INTERVAL_MS))
740 .await;
741 }
742 }
743 }
744 }
745 Ok(())
746 }
747
748 async fn wait_for_stabilization(&self) -> Result<()> {
749 let deadline = Instant::now() + self.config.stabilization_timeout;
750 let min_connections = self
751 .config
752 .bootstrap_count
753 .min(STABILIZATION_MIN_CONNECTIONS_CAP);
754
755 info!(
756 "Waiting for devnet stabilization (min {} connections per node)",
757 min_connections
758 );
759
760 while Instant::now() < deadline {
761 let mut all_connected = true;
762 let mut total_connections = 0;
763
764 for node in &self.nodes {
765 let peer_count = node.peer_count().await;
766 total_connections += peer_count;
767
768 if peer_count < min_connections {
769 all_connected = false;
770 }
771 }
772
773 if all_connected {
774 info!("Devnet stabilized: {} total connections", total_connections);
775 return Ok(());
776 }
777
778 debug!(
779 "Waiting for stabilization: {} total connections",
780 total_connections
781 );
782 tokio::time::sleep(Duration::from_secs(STABILIZATION_POLL_INTERVAL_SECS)).await;
783 }
784
785 Err(DevnetError::Stabilization(
786 "Devnet failed to stabilize within timeout".to_string(),
787 ))
788 }
789
790 fn start_health_monitor(&mut self) {
791 let nodes: Vec<Arc<P2PNode>> = self
792 .nodes
793 .iter()
794 .filter_map(|n| n.p2p_node.clone())
795 .collect();
796 let shutdown = self.shutdown.clone();
797
798 self.health_monitor = Some(tokio::spawn(async move {
799 let check_interval = Duration::from_secs(HEALTH_CHECK_INTERVAL_SECS);
800
801 loop {
802 tokio::select! {
803 () = shutdown.cancelled() => break,
804 () = tokio::time::sleep(check_interval) => {
805 for (i, node) in nodes.iter().enumerate() {
806 if !node.is_running() {
807 warn!("Node {} appears unhealthy", i);
808 }
809 }
810 }
811 }
812 }
813 }));
814 }
815}
816
817impl Drop for Devnet {
818 fn drop(&mut self) {
819 self.shutdown.cancel();
820 if let Some(handle) = self.health_monitor.take() {
821 handle.abort();
822 }
823 }
824}
825
826#[cfg(test)]
827mod tests {
828 use super::*;
829
830 #[test]
835 fn default_config_has_no_advertise_ip() {
836 assert!(DevnetConfig::default().advertise_ip.is_none());
837 }
838}