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, PriceFloorConfig, QuoteGenerator,
11    QuotingMetricsTracker,
12};
13use crate::replication::config::ReplicationConfig;
14use crate::storage::{AntProtocol, ChunkRequestContext, 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
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
131// =============================================================================
132// Default Node Counts
133// =============================================================================
134
135/// Default number of nodes in a full devnet.
136pub const DEFAULT_NODE_COUNT: usize = 25;
137
138/// Default number of bootstrap nodes.
139pub const DEFAULT_BOOTSTRAP_COUNT: usize = 3;
140
141/// Number of nodes in a minimal devnet.
142pub const MINIMAL_NODE_COUNT: usize = 5;
143
144/// Number of bootstrap nodes in a minimal network.
145pub const MINIMAL_BOOTSTRAP_COUNT: usize = 2;
146
147/// Number of nodes in a small devnet.
148pub const SMALL_NODE_COUNT: usize = 10;
149
150/// Error type for devnet operations.
151#[derive(Debug, thiserror::Error)]
152pub enum DevnetError {
153    /// Configuration error
154    #[error("Configuration error: {0}")]
155    Config(String),
156
157    /// Node startup error
158    #[error("Node startup error: {0}")]
159    Startup(String),
160
161    /// Network stabilization error
162    #[error("Network stabilization error: {0}")]
163    Stabilization(String),
164
165    /// IO error
166    #[error("IO error: {0}")]
167    Io(#[from] std::io::Error),
168
169    /// Core error
170    #[error("Core error: {0}")]
171    Core(String),
172}
173
174/// Result type for devnet operations.
175pub type Result<T> = std::result::Result<T, DevnetError>;
176
177/// Configuration for the devnet.
178///
179/// Each configuration is automatically isolated with unique ports and
180/// data directories to prevent collisions when running multiple devnets.
181#[derive(Debug, Clone)]
182pub struct DevnetConfig {
183    /// Number of nodes to spawn (default: 25).
184    pub node_count: usize,
185
186    /// Base port for node allocation (0 = auto).
187    pub base_port: u16,
188
189    /// Number of bootstrap nodes (first N nodes, default: 3).
190    pub bootstrap_count: usize,
191
192    /// Root directory for devnet data.
193    pub data_dir: PathBuf,
194
195    /// Delay between node spawns (default: 200ms).
196    pub spawn_delay: Duration,
197
198    /// Timeout for network stabilization (default: 120s).
199    pub stabilization_timeout: Duration,
200
201    /// Timeout for single node startup (default: 30s).
202    pub node_startup_timeout: Duration,
203
204    /// Enable verbose logging for devnet nodes.
205    pub enable_node_logging: bool,
206
207    /// Whether to remove the data directory on shutdown.
208    pub cleanup_data_dir: bool,
209
210    /// Optional EVM network for payment verification.
211    /// When `Some`, nodes will use this network (e.g. Anvil testnet) for
212    /// on-chain verification. Defaults to Arbitrum One when `None`.
213    pub evm_network: Option<EvmNetwork>,
214
215    /// Optional IPv4 to advertise to peers/clients (LAN devnet). When `Some`,
216    /// nodes bind 0.0.0.0 and advertise this IP instead of 127.0.0.1.
217    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)] // DEFAULT_NODE_COUNT is 25, always fits u16
225        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    /// Minimal devnet preset (5 nodes).
246    #[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    /// Small devnet preset (10 nodes).
257    #[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
268// The manifest types are shared with ant-client (CLI reads them, devnet
269// writes them), so they live in ant-protocol. Re-exported here for
270// backwards compatibility.
271pub use ant_protocol::devnet_manifest::{DevnetEvmInfo, DevnetManifest};
272
273/// Network state for devnet startup lifecycle.
274#[derive(Debug, Clone)]
275pub enum NetworkState {
276    /// Not started.
277    Uninitialized,
278    /// Bootstrapping nodes are starting.
279    BootstrappingPhase,
280    /// Regular nodes are starting.
281    NodeSpawningPhase,
282    /// Waiting for stabilization.
283    Stabilizing,
284    /// Network is ready.
285    Ready,
286    /// Shutting down.
287    ShuttingDown,
288    /// Stopped.
289    Stopped,
290}
291
292/// Node state for devnet nodes.
293#[derive(Debug, Clone)]
294pub enum NodeState {
295    /// Not started yet.
296    Pending,
297    /// Starting up.
298    Starting,
299    /// Running.
300    Running,
301    /// Connected to peers.
302    Connected,
303    /// Stopped.
304    Stopped,
305    /// Failed to start.
306    Failed(String),
307}
308
309/// A single devnet node instance.
310#[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    /// Get the node's peer count.
327    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
336/// A local devnet composed of multiple nodes.
337pub 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    /// Create a new devnet with the given configuration.
347    ///
348    /// # Errors
349    ///
350    /// Returns `DevnetError::Config` if the configuration is invalid (e.g. bootstrap
351    /// count exceeds node count or port range overflow).
352    /// Returns `DevnetError::Io` if the data directory cannot be created.
353    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    /// Start the devnet.
403    ///
404    /// # Errors
405    ///
406    /// Returns `DevnetError::Startup` if any node fails to start, or
407    /// `DevnetError::Stabilization` if the network does not stabilize within the timeout.
408    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    /// Shutdown the devnet.
431    ///
432    /// # Errors
433    ///
434    /// Returns `DevnetError::Io` if the data directory cleanup fails.
435    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    /// Get devnet configuration.
479    #[must_use]
480    pub fn config(&self) -> &DevnetConfig {
481        &self.config
482    }
483
484    /// Get bootstrap addresses.
485    #[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        // Generate identity first so we can use peer_id as the directory name
559        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 = LmdbStorageConfig {
599            root_dir: data_dir.to_path_buf(),
600            verify_on_read: true,
601            ..LmdbStorageConfig::default()
602        };
603        let storage = LmdbStorage::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        // Wire ML-DSA-65 signing from the devnet node's identity
628        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        // Load the node identity for app-level message signing.
653        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            // Wire P2P into AntProtocol for payment-proof closeness checks.
680            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    /// Backward-compatibility contract: a default config advertises no LAN IP,
831    /// so nodes bind loopback (`.local(advertise_ip.is_none())` → `.local(true)`)
832    /// and stamp `127.0.0.1` into the manifest bootstrap addresses — exactly as
833    /// before the `--host` flag existed.
834    #[test]
835    fn default_config_has_no_advertise_ip() {
836        assert!(DevnetConfig::default().advertise_ip.is_none());
837    }
838}