Skip to main content

ant_node/
devnet.rs

1//! Local devnet infrastructure for spawning and managing multiple nodes.
2//!
3//! This module provides a local, in-process devnet suitable for running
4//! multi-node networks on a single machine.
5
6use 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, 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
31// =============================================================================
32// Devnet Constants
33// =============================================================================
34
35/// Minimum port for random devnet allocation.
36pub const DEVNET_PORT_RANGE_MIN: u16 = 20_000;
37
38/// Maximum port for random devnet allocation.
39pub const DEVNET_PORT_RANGE_MAX: u16 = 60_000;
40
41// =============================================================================
42// Default Timing Constants
43// =============================================================================
44
45/// Default delay between spawning nodes (milliseconds).
46const DEFAULT_SPAWN_DELAY_MS: u64 = 200;
47
48/// Default timeout for network stabilization (seconds).
49const DEFAULT_STABILIZATION_TIMEOUT_SECS: u64 = 120;
50
51/// Default timeout for single node startup (seconds).
52const DEFAULT_NODE_STARTUP_TIMEOUT_SECS: u64 = 30;
53
54/// Stabilization timeout for minimal network (seconds).
55const MINIMAL_STABILIZATION_TIMEOUT_SECS: u64 = 30;
56
57/// Stabilization timeout for small network (seconds).
58const SMALL_STABILIZATION_TIMEOUT_SECS: u64 = 60;
59
60/// Polling interval when waiting for individual nodes to become ready (milliseconds).
61const NODE_READY_POLL_INTERVAL_MS: u64 = 100;
62
63/// Polling interval when waiting for network stabilization (seconds).
64const STABILIZATION_POLL_INTERVAL_SECS: u64 = 1;
65
66/// Maximum minimum connections required per node during stabilization.
67const STABILIZATION_MIN_CONNECTIONS_CAP: usize = 3;
68
69/// Health monitor check interval (seconds).
70const HEALTH_CHECK_INTERVAL_SECS: u64 = 5;
71
72// =============================================================================
73// AntProtocol Devnet Configuration
74// =============================================================================
75
76/// Payment cache capacity for devnet nodes.
77const DEVNET_PAYMENT_CACHE_CAPACITY: usize = 1000;
78
79/// Devnet rewards address (20 bytes, all 0x01).
80const DEVNET_REWARDS_ADDRESS: [u8; 20] = [0x01; 20];
81
82/// Initial records for quoting metrics (devnet value).
83const DEVNET_INITIAL_RECORDS: usize = 1000;
84
85// =============================================================================
86// Default Node Counts
87// =============================================================================
88
89/// Default number of nodes in a full devnet.
90pub const DEFAULT_NODE_COUNT: usize = 25;
91
92/// Default number of bootstrap nodes.
93pub const DEFAULT_BOOTSTRAP_COUNT: usize = 3;
94
95/// Number of nodes in a minimal devnet.
96pub const MINIMAL_NODE_COUNT: usize = 5;
97
98/// Number of bootstrap nodes in a minimal network.
99pub const MINIMAL_BOOTSTRAP_COUNT: usize = 2;
100
101/// Number of nodes in a small devnet.
102pub const SMALL_NODE_COUNT: usize = 10;
103
104/// Error type for devnet operations.
105#[derive(Debug, thiserror::Error)]
106pub enum DevnetError {
107    /// Configuration error
108    #[error("Configuration error: {0}")]
109    Config(String),
110
111    /// Node startup error
112    #[error("Node startup error: {0}")]
113    Startup(String),
114
115    /// Network stabilization error
116    #[error("Network stabilization error: {0}")]
117    Stabilization(String),
118
119    /// IO error
120    #[error("IO error: {0}")]
121    Io(#[from] std::io::Error),
122
123    /// Core error
124    #[error("Core error: {0}")]
125    Core(String),
126}
127
128/// Result type for devnet operations.
129pub type Result<T> = std::result::Result<T, DevnetError>;
130
131/// Configuration for the devnet.
132///
133/// Each configuration is automatically isolated with unique ports and
134/// data directories to prevent collisions when running multiple devnets.
135#[derive(Debug, Clone)]
136pub struct DevnetConfig {
137    /// Number of nodes to spawn (default: 25).
138    pub node_count: usize,
139
140    /// Base port for node allocation (0 = auto).
141    pub base_port: u16,
142
143    /// Number of bootstrap nodes (first N nodes, default: 3).
144    pub bootstrap_count: usize,
145
146    /// Root directory for devnet data.
147    pub data_dir: PathBuf,
148
149    /// Delay between node spawns (default: 200ms).
150    pub spawn_delay: Duration,
151
152    /// Timeout for network stabilization (default: 120s).
153    pub stabilization_timeout: Duration,
154
155    /// Timeout for single node startup (default: 30s).
156    pub node_startup_timeout: Duration,
157
158    /// Enable verbose logging for devnet nodes.
159    pub enable_node_logging: bool,
160
161    /// Whether to remove the data directory on shutdown.
162    pub cleanup_data_dir: bool,
163
164    /// Optional EVM network for payment verification.
165    /// When `Some`, nodes will use this network (e.g. Anvil testnet) for
166    /// on-chain verification. Defaults to Arbitrum One when `None`.
167    pub evm_network: Option<EvmNetwork>,
168
169    /// Optional IPv4 to advertise to peers/clients (LAN devnet). When `Some`,
170    /// nodes bind 0.0.0.0 and advertise this IP instead of 127.0.0.1.
171    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)] // DEFAULT_NODE_COUNT is 25, always fits u16
179        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    /// Minimal devnet preset (5 nodes).
200    #[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    /// Small devnet preset (10 nodes).
211    #[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
222// The manifest types are shared with ant-client (CLI reads them, devnet
223// writes them), so they live in ant-protocol. Re-exported here for
224// backwards compatibility.
225pub use ant_protocol::devnet_manifest::{DevnetEvmInfo, DevnetManifest};
226
227/// Network state for devnet startup lifecycle.
228#[derive(Debug, Clone)]
229pub enum NetworkState {
230    /// Not started.
231    Uninitialized,
232    /// Bootstrapping nodes are starting.
233    BootstrappingPhase,
234    /// Regular nodes are starting.
235    NodeSpawningPhase,
236    /// Waiting for stabilization.
237    Stabilizing,
238    /// Network is ready.
239    Ready,
240    /// Shutting down.
241    ShuttingDown,
242    /// Stopped.
243    Stopped,
244}
245
246/// Node state for devnet nodes.
247#[derive(Debug, Clone)]
248pub enum NodeState {
249    /// Not started yet.
250    Pending,
251    /// Starting up.
252    Starting,
253    /// Running.
254    Running,
255    /// Connected to peers.
256    Connected,
257    /// Stopped.
258    Stopped,
259    /// Failed to start.
260    Failed(String),
261}
262
263/// A single devnet node instance.
264#[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    /// Get the node's peer count.
281    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
290/// A local devnet composed of multiple nodes.
291pub 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    /// Create a new devnet with the given configuration.
301    ///
302    /// # Errors
303    ///
304    /// Returns `DevnetError::Config` if the configuration is invalid (e.g. bootstrap
305    /// count exceeds node count or port range overflow).
306    /// Returns `DevnetError::Io` if the data directory cannot be created.
307    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    /// Start the devnet.
357    ///
358    /// # Errors
359    ///
360    /// Returns `DevnetError::Startup` if any node fails to start, or
361    /// `DevnetError::Stabilization` if the network does not stabilize within the timeout.
362    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    /// Shutdown the devnet.
385    ///
386    /// # Errors
387    ///
388    /// Returns `DevnetError::Io` if the data directory cleanup fails.
389    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    /// Get devnet configuration.
433    #[must_use]
434    pub fn config(&self) -> &DevnetConfig {
435        &self.config
436    }
437
438    /// Get bootstrap addresses.
439    #[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        // Generate identity first so we can use peer_id as the directory name
513        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        };
576        let payment_verifier = PaymentVerifier::new(payment_config);
577        let metrics_tracker = QuotingMetricsTracker::new(DEVNET_INITIAL_RECORDS);
578        let mut quote_generator = QuoteGenerator::new(rewards_address, metrics_tracker);
579
580        // Wire ML-DSA-65 signing from the devnet node's identity
581        crate::payment::wire_ml_dsa_signer(&mut quote_generator, identity)
582            .map_err(|e| DevnetError::Startup(format!("Failed to wire ML-DSA-65 signer: {e}")))?;
583
584        let storage = Arc::new(storage);
585        let payment_verifier = Arc::new(payment_verifier);
586
587        Ok(AntProtocol::new(
588            storage,
589            payment_verifier,
590            Arc::new(quote_generator),
591        ))
592    }
593
594    async fn start_node(&mut self, mut node: DevnetNode) -> Result<()> {
595        debug!("Starting node {} on port {}", node.index, node.port);
596        *node.state.write().await = NodeState::Starting;
597
598        let mut core_config = CoreNodeConfig::builder()
599            .port(node.port)
600            .local(self.config.advertise_ip.is_none())
601            .max_message_size(crate::ant_protocol::MAX_WIRE_MESSAGE_SIZE)
602            .build()
603            .map_err(|e| DevnetError::Core(format!("Failed to create core config: {e}")))?;
604
605        // Load the node identity for app-level message signing.
606        let identity = NodeIdentity::load_from_file(
607            &node.data_dir.join(crate::config::NODE_IDENTITY_FILENAME),
608        )
609        .await
610        .map_err(|e| DevnetError::Core(format!("Failed to load node identity: {e}")))?;
611
612        core_config.node_identity = Some(Arc::new(identity));
613        core_config
614            .bootstrap_peers
615            .clone_from(&node.bootstrap_addrs);
616        core_config.diversity_config = Some(IPDiversityConfig::permissive());
617
618        let index = node.index;
619        let p2p_node = P2PNode::new(core_config)
620            .await
621            .map_err(|e| DevnetError::Startup(format!("Failed to create node {index}: {e}")))?;
622
623        p2p_node
624            .start()
625            .await
626            .map_err(|e| DevnetError::Startup(format!("Failed to start node {index}: {e}")))?;
627
628        node.p2p_node = Some(Arc::new(p2p_node));
629        *node.state.write().await = NodeState::Running;
630
631        if let (Some(ref p2p), Some(ref protocol)) = (&node.p2p_node, &node.ant_protocol) {
632            // Wire P2P into AntProtocol for payment-proof closeness checks.
633            protocol.attach_p2p_node(Arc::clone(p2p));
634
635            let mut events = p2p.subscribe_events();
636            let p2p_clone = Arc::clone(p2p);
637            let protocol_clone = Arc::clone(protocol);
638            let node_index = node.index;
639            node.protocol_task = Some(tokio::spawn(async move {
640                while let Ok(event) = events.recv().await {
641                    if let P2PEvent::Message {
642                        topic,
643                        source: Some(source),
644                        data,
645                        ..
646                    } = event
647                    {
648                        if topic == CHUNK_PROTOCOL_ID {
649                            debug!(
650                                "Node {node_index} received chunk protocol message from {source}"
651                            );
652                            let protocol = Arc::clone(&protocol_clone);
653                            let p2p = Arc::clone(&p2p_clone);
654                            tokio::spawn(async move {
655                                match protocol.try_handle_request(&data).await {
656                                    Ok(Some(response)) => {
657                                        if let Err(e) = p2p
658                                            .send_message(
659                                                &source,
660                                                CHUNK_PROTOCOL_ID,
661                                                response.to_vec(),
662                                                &[],
663                                            )
664                                            .await
665                                        {
666                                            warn!(
667                                                "Node {node_index} failed to send response to {source}: {e}"
668                                            );
669                                        }
670                                    }
671                                    Ok(None) => {}
672                                    Err(e) => {
673                                        warn!("Node {node_index} protocol handler error: {e}");
674                                    }
675                                }
676                            });
677                        }
678                    }
679                }
680            }));
681        }
682
683        debug!("Node {} started successfully", node.index);
684        self.nodes.push(node);
685        Ok(())
686    }
687
688    async fn wait_for_nodes_ready(&self, range: std::ops::Range<usize>) -> Result<()> {
689        let deadline = Instant::now() + self.config.node_startup_timeout;
690
691        for i in range {
692            while Instant::now() < deadline {
693                let node = self.nodes.get(i).ok_or_else(|| {
694                    DevnetError::Config(format!(
695                        "Node index {i} out of bounds (len: {})",
696                        self.nodes.len()
697                    ))
698                })?;
699                let state = node.state.read().await.clone();
700                match state {
701                    NodeState::Running | NodeState::Connected => break,
702                    NodeState::Failed(ref e) => {
703                        return Err(DevnetError::Startup(format!("Node {i} failed: {e}")));
704                    }
705                    _ => {
706                        tokio::time::sleep(Duration::from_millis(NODE_READY_POLL_INTERVAL_MS))
707                            .await;
708                    }
709                }
710            }
711        }
712        Ok(())
713    }
714
715    async fn wait_for_stabilization(&self) -> Result<()> {
716        let deadline = Instant::now() + self.config.stabilization_timeout;
717        let min_connections = self
718            .config
719            .bootstrap_count
720            .min(STABILIZATION_MIN_CONNECTIONS_CAP);
721
722        info!(
723            "Waiting for devnet stabilization (min {} connections per node)",
724            min_connections
725        );
726
727        while Instant::now() < deadline {
728            let mut all_connected = true;
729            let mut total_connections = 0;
730
731            for node in &self.nodes {
732                let peer_count = node.peer_count().await;
733                total_connections += peer_count;
734
735                if peer_count < min_connections {
736                    all_connected = false;
737                }
738            }
739
740            if all_connected {
741                info!("Devnet stabilized: {} total connections", total_connections);
742                return Ok(());
743            }
744
745            debug!(
746                "Waiting for stabilization: {} total connections",
747                total_connections
748            );
749            tokio::time::sleep(Duration::from_secs(STABILIZATION_POLL_INTERVAL_SECS)).await;
750        }
751
752        Err(DevnetError::Stabilization(
753            "Devnet failed to stabilize within timeout".to_string(),
754        ))
755    }
756
757    fn start_health_monitor(&mut self) {
758        let nodes: Vec<Arc<P2PNode>> = self
759            .nodes
760            .iter()
761            .filter_map(|n| n.p2p_node.clone())
762            .collect();
763        let shutdown = self.shutdown.clone();
764
765        self.health_monitor = Some(tokio::spawn(async move {
766            let check_interval = Duration::from_secs(HEALTH_CHECK_INTERVAL_SECS);
767
768            loop {
769                tokio::select! {
770                    () = shutdown.cancelled() => break,
771                    () = tokio::time::sleep(check_interval) => {
772                        for (i, node) in nodes.iter().enumerate() {
773                            if !node.is_running() {
774                                warn!("Node {} appears unhealthy", i);
775                            }
776                        }
777                    }
778                }
779            }
780        }));
781    }
782}
783
784impl Drop for Devnet {
785    fn drop(&mut self) {
786        self.shutdown.cancel();
787        if let Some(handle) = self.health_monitor.take() {
788            handle.abort();
789        }
790    }
791}
792
793#[cfg(test)]
794mod tests {
795    use super::*;
796
797    /// Backward-compatibility contract: a default config advertises no LAN IP,
798    /// so nodes bind loopback (`.local(advertise_ip.is_none())` → `.local(true)`)
799    /// and stamp `127.0.0.1` into the manifest bootstrap addresses — exactly as
800    /// before the `--host` flag existed.
801    #[test]
802    fn default_config_has_no_advertise_ip() {
803        assert!(DevnetConfig::default().advertise_ip.is_none());
804    }
805}