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, 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;
30use tokio_util::task::TaskTracker;
31
32#[cfg(all(feature = "webrtc-direct", feature = "test-utils"))]
33use crate::ant_protocol::{ChunkMessage, ChunkMessageBody, ChunkPutRequest, ChunkPutResponse};
34#[cfg(all(feature = "webrtc-direct", feature = "test-utils"))]
35use crate::browser::BrowserPublicFile;
36#[cfg(feature = "webrtc-direct")]
37use crate::browser::{browser_payment_network, BrowserBootstrapNode, BrowserPaymentNetwork};
38#[cfg(feature = "webrtc-direct")]
39use crate::config::WebRtcDirectConfig;
40#[cfg(all(feature = "webrtc-direct", feature = "test-utils"))]
41use bytes::Bytes;
42#[cfg(all(feature = "webrtc-direct", feature = "test-utils"))]
43use std::collections::HashMap;
44
45mod run_dir;
46
47use run_dir::RunDir;
48pub use run_dir::{LOCK_FILE, MARKER_FILE};
49
50// =============================================================================
51// Devnet Constants
52// =============================================================================
53
54/// Minimum port for random devnet allocation.
55pub const DEVNET_PORT_RANGE_MIN: u16 = 20_000;
56
57/// Maximum port for random devnet allocation.
58pub const DEVNET_PORT_RANGE_MAX: u16 = 60_000;
59
60// =============================================================================
61// Default Timing Constants
62// =============================================================================
63
64/// Directory under the ant data root that devnet runs create their own data
65/// directories in by default (see [`DevnetConfig::data_dir`]).
66pub const DEVNETS_SUBDIR: &str = "devnets";
67
68/// Default delay between spawning nodes (milliseconds).
69const DEFAULT_SPAWN_DELAY_MS: u64 = 200;
70
71/// Default timeout for network stabilization (seconds).
72const DEFAULT_STABILIZATION_TIMEOUT_SECS: u64 = 120;
73
74/// Default timeout for single node startup (seconds).
75const DEFAULT_NODE_STARTUP_TIMEOUT_SECS: u64 = 30;
76
77/// Stabilization timeout for minimal network (seconds).
78const MINIMAL_STABILIZATION_TIMEOUT_SECS: u64 = 30;
79
80/// Stabilization timeout for small network (seconds).
81const SMALL_STABILIZATION_TIMEOUT_SECS: u64 = 60;
82
83/// Polling interval when waiting for individual nodes to become ready (milliseconds).
84const NODE_READY_POLL_INTERVAL_MS: u64 = 100;
85
86/// Polling interval when waiting for network stabilization (seconds).
87const STABILIZATION_POLL_INTERVAL_SECS: u64 = 1;
88
89/// Maximum minimum connections required per node during stabilization.
90const STABILIZATION_MIN_CONNECTIONS_CAP: usize = 3;
91
92/// Health monitor check interval (seconds).
93const HEALTH_CHECK_INTERVAL_SECS: u64 = 5;
94
95/// How long shutdown gives a node's request handlers, and then the storage
96/// writes they started, to finish (seconds), as a node does. A node still
97/// writing after that keeps the run directory.
98const DRAIN_GRACE_SECS: u64 = 5;
99
100// =============================================================================
101// AntProtocol Devnet Configuration
102// =============================================================================
103
104/// Payment cache capacity for devnet nodes.
105const DEVNET_PAYMENT_CACHE_CAPACITY: usize = 1000;
106
107/// Devnet rewards address (20 bytes, all 0x01).
108const DEVNET_REWARDS_ADDRESS: [u8; 20] = [0x01; 20];
109
110/// Initial records for quoting metrics (devnet value).
111const DEVNET_INITIAL_RECORDS: usize = 1000;
112
113async fn handle_chunk_message(
114    protocol: Arc<AntProtocol>,
115    p2p: Arc<P2PNode>,
116    source: PeerId,
117    data: Vec<u8>,
118    node_index: usize,
119    received_at: Instant,
120) {
121    let handled = protocol
122        .try_handle_request_with_context(
123            &data,
124            Some(
125                ChunkRequestContext::new(source.to_string(), received_at.into(), Duration::ZERO)
126                    .with_requester(source),
127            ),
128        )
129        .await;
130    let telemetry = handled.get_telemetry;
131    match handled.response {
132        Ok(Some(response)) => {
133            let send_started = Instant::now();
134            let send_result = p2p
135                .send_message(&source, CHUNK_PROTOCOL_ID, response.to_vec(), &[])
136                .await;
137            if let Some(telemetry) = telemetry {
138                telemetry.finish_send(send_started.elapsed(), send_result.is_ok());
139            }
140            if let Err(e) = send_result {
141                warn!("Node {node_index} failed to send response to {source}: {e}");
142            }
143        }
144        Ok(None) => {
145            if let Some(telemetry) = telemetry {
146                telemetry.finish_without_send("no_response");
147            }
148        }
149        Err(e) => {
150            if let Some(telemetry) = telemetry {
151                telemetry.finish_without_send("encode_error");
152            }
153            warn!("Node {node_index} protocol handler error: {e}");
154        }
155    }
156}
157
158// =============================================================================
159// Default Node Counts
160// =============================================================================
161
162/// Default number of nodes in a full devnet.
163pub const DEFAULT_NODE_COUNT: usize = 25;
164
165/// Default number of bootstrap nodes.
166pub const DEFAULT_BOOTSTRAP_COUNT: usize = 3;
167
168/// Number of nodes in a minimal devnet.
169pub const MINIMAL_NODE_COUNT: usize = 5;
170
171/// Number of bootstrap nodes in a minimal network.
172pub const MINIMAL_BOOTSTRAP_COUNT: usize = 2;
173
174/// Number of nodes in a small devnet.
175pub const SMALL_NODE_COUNT: usize = 10;
176
177/// Error type for devnet operations.
178#[derive(Debug, thiserror::Error)]
179pub enum DevnetError {
180    /// Configuration error
181    #[error("Configuration error: {0}")]
182    Config(String),
183
184    /// Node startup error
185    #[error("Node startup error: {0}")]
186    Startup(String),
187
188    /// Network stabilization error
189    #[error("Network stabilization error: {0}")]
190    Stabilization(String),
191
192    /// IO error
193    #[error("IO error: {0}")]
194    Io(#[from] std::io::Error),
195
196    /// Core error
197    #[error("Core error: {0}")]
198    Core(String),
199}
200
201/// Result type for devnet operations.
202pub type Result<T> = std::result::Result<T, DevnetError>;
203
204/// Configuration for the devnet.
205///
206/// Each configuration is automatically isolated with unique ports and
207/// data directories to prevent collisions when running multiple devnets.
208#[derive(Debug, Clone)]
209pub struct DevnetConfig {
210    /// Number of nodes to spawn (default: 25).
211    pub node_count: usize,
212
213    /// Base port for node allocation (0 = auto).
214    pub base_port: u16,
215
216    /// Number of bootstrap nodes (first N nodes, default: 3).
217    pub bootstrap_count: usize,
218
219    /// Directory each run creates its own data directory in (default:
220    /// `{ant data root}/devnets`).
221    ///
222    /// [`Devnet::new`] creates a fresh `{pid}-{random}` directory inside it,
223    /// and from then on [`Devnet::config`]'s `data_dir` is that run
224    /// directory. A devnet deletes only a directory it created and marked as
225    /// its own ([`MARKER_FILE`]), never this one or anything else in it: the
226    /// ant data root also holds real nodes' data and the client's payment
227    /// caches and upload history (ant-node#261). Run directories that earlier
228    /// runs left here, killed before they could remove them, are removed when
229    /// the next run starts, unless they were kept.
230    ///
231    /// On Unix it must be a directory only the user and root can change, as
232    /// must every directory above it, or [`Devnet::new`] fails: another user
233    /// who could would be able to redirect what the nodes write.
234    pub data_dir: PathBuf,
235
236    /// Delay between node spawns (default: 200ms).
237    pub spawn_delay: Duration,
238
239    /// Timeout for network stabilization (default: 120s).
240    pub stabilization_timeout: Duration,
241
242    /// Timeout for single node startup (default: 30s).
243    pub node_startup_timeout: Duration,
244
245    /// Enable verbose logging for devnet nodes.
246    pub enable_node_logging: bool,
247
248    /// Whether to remove the run's data directory on shutdown. When `false`,
249    /// its marker also tells later runs to leave it alone.
250    pub cleanup_data_dir: bool,
251
252    /// Optional EVM network for payment verification.
253    /// When `Some`, nodes will use this network (e.g. Anvil testnet) for
254    /// on-chain verification. Defaults to Arbitrum One when `None`.
255    pub evm_network: Option<EvmNetwork>,
256
257    /// Optional IPv4 to advertise to peers/clients (LAN devnet). When `Some`,
258    /// nodes bind 0.0.0.0 and advertise this IP instead of 127.0.0.1.
259    pub advertise_ip: Option<Ipv4Addr>,
260
261    /// Run one direct-browser WebRTC Direct listener per devnet node.
262    pub webrtc_direct: bool,
263
264    /// First UDP port in the WebRTC Direct node range (0 = allocate).
265    pub webrtc_direct_base_port: u16,
266}
267
268impl Default for DevnetConfig {
269    fn default() -> Self {
270        let mut rng = rand::thread_rng();
271
272        #[allow(clippy::cast_possible_truncation)] // DEFAULT_NODE_COUNT is 25, always fits u16
273        let max_base_port = DEVNET_PORT_RANGE_MAX.saturating_sub(DEFAULT_NODE_COUNT as u16);
274        let base_port = rng.gen_range(DEVNET_PORT_RANGE_MIN..max_base_port);
275
276        Self {
277            node_count: DEFAULT_NODE_COUNT,
278            base_port,
279            bootstrap_count: DEFAULT_BOOTSTRAP_COUNT,
280            data_dir: default_root_dir().join(DEVNETS_SUBDIR),
281            spawn_delay: Duration::from_millis(DEFAULT_SPAWN_DELAY_MS),
282            stabilization_timeout: Duration::from_secs(DEFAULT_STABILIZATION_TIMEOUT_SECS),
283            node_startup_timeout: Duration::from_secs(DEFAULT_NODE_STARTUP_TIMEOUT_SECS),
284            enable_node_logging: false,
285            cleanup_data_dir: true,
286            evm_network: None,
287            advertise_ip: None,
288            webrtc_direct: false,
289            webrtc_direct_base_port: 0,
290        }
291    }
292}
293
294impl DevnetConfig {
295    /// Minimal devnet preset (5 nodes).
296    #[must_use]
297    pub fn minimal() -> Self {
298        Self {
299            node_count: MINIMAL_NODE_COUNT,
300            bootstrap_count: MINIMAL_BOOTSTRAP_COUNT,
301            stabilization_timeout: Duration::from_secs(MINIMAL_STABILIZATION_TIMEOUT_SECS),
302            ..Self::default()
303        }
304    }
305
306    /// Small devnet preset (10 nodes).
307    #[must_use]
308    pub fn small() -> Self {
309        Self {
310            node_count: SMALL_NODE_COUNT,
311            bootstrap_count: MINIMAL_BOOTSTRAP_COUNT,
312            stabilization_timeout: Duration::from_secs(SMALL_STABILIZATION_TIMEOUT_SECS),
313            ..Self::default()
314        }
315    }
316}
317
318// The manifest types are shared with ant-client (CLI reads them, devnet
319// writes them), so they live in ant-protocol. Re-exported here for
320// backwards compatibility.
321pub use ant_protocol::devnet_manifest::{DevnetEvmInfo, DevnetManifest};
322
323/// Network state for devnet startup lifecycle.
324#[derive(Debug, Clone)]
325pub enum NetworkState {
326    /// Not started.
327    Uninitialized,
328    /// Bootstrapping nodes are starting.
329    BootstrappingPhase,
330    /// Regular nodes are starting.
331    NodeSpawningPhase,
332    /// Waiting for stabilization.
333    Stabilizing,
334    /// Network is ready.
335    Ready,
336    /// Shutting down.
337    ShuttingDown,
338    /// Stopped.
339    Stopped,
340}
341
342/// Node state for devnet nodes.
343#[derive(Debug, Clone)]
344pub enum NodeState {
345    /// Not started yet.
346    Pending,
347    /// Starting up.
348    Starting,
349    /// Running.
350    Running,
351    /// Connected to peers.
352    Connected,
353    /// Stopped.
354    Stopped,
355    /// Failed to start.
356    Failed(String),
357}
358
359/// A single devnet node instance.
360#[allow(dead_code)]
361pub struct DevnetNode {
362    index: usize,
363    label: String,
364    peer_id: PeerId,
365    port: u16,
366    data_dir: PathBuf,
367    p2p_node: Option<Arc<P2PNode>>,
368    ant_protocol: Option<Arc<AntProtocol>>,
369    is_bootstrap: bool,
370    state: Arc<RwLock<NodeState>>,
371    bootstrap_addrs: Vec<MultiAddr>,
372    protocol_task: Option<JoinHandle<()>>,
373    /// The request handlers `protocol_task` has started, which shutdown
374    /// waits for.
375    handlers: TaskTracker,
376    #[cfg(feature = "webrtc-direct")]
377    webrtc_direct_task: Option<JoinHandle<()>>,
378    #[cfg(feature = "webrtc-direct")]
379    webrtc_diagnostics: Option<crate::web_rtc::WebRtcServerDiagnostics>,
380    #[cfg(feature = "webrtc-direct")]
381    browser_endpoint: Option<crate::browser::BrowserEndpoint>,
382}
383
384impl DevnetNode {
385    /// Get the node's peer count.
386    pub async fn peer_count(&self) -> usize {
387        if let Some(ref node) = self.p2p_node {
388            node.peer_count().await
389        } else {
390            0
391        }
392    }
393}
394
395/// A local devnet composed of multiple nodes.
396///
397/// Call [`shutdown`](Self::shutdown) before dropping it. Dropped without one,
398/// the nodes it started are not stopped, and its run directory is left,
399/// locked until the process exits so that no other run deletes it while they
400/// may still be writing there.
401pub struct Devnet {
402    config: DevnetConfig,
403    nodes: Vec<DevnetNode>,
404    shutdown: CancellationToken,
405    state: Arc<RwLock<NetworkState>>,
406    health_monitor: Option<JoinHandle<()>>,
407    /// This run's data directory, until [`shutdown`](Self::shutdown) removes
408    /// or releases it. Dropped without a shutdown, the devnet keeps it locked
409    /// until the process exits.
410    run_dir: Option<RunDir>,
411    /// [`DRAIN_GRACE_SECS`], shorter in tests.
412    drain_grace: Duration,
413    #[cfg(feature = "webrtc-direct")]
414    browser_endpoint_catalog: Arc<crate::web_rtc::BrowserEndpointCatalog>,
415}
416
417impl Devnet {
418    /// Create a new devnet with the given configuration.
419    ///
420    /// Creates this run's own data directory inside `config.data_dir`, after
421    /// removing any that earlier runs left there and that are over and not
422    /// kept (see [`DevnetConfig::data_dir`]).
423    ///
424    /// # Errors
425    ///
426    /// Returns `DevnetError::Config` if the configuration is invalid (e.g. bootstrap
427    /// count exceeds node count or port range overflow).
428    /// Returns `DevnetError::Io` if the data directory cannot be created.
429    #[allow(clippy::too_many_lines)]
430    pub async fn new(mut config: DevnetConfig) -> Result<Self> {
431        if config.bootstrap_count >= config.node_count {
432            return Err(DevnetError::Config(
433                "Bootstrap count must be less than node count".to_string(),
434            ));
435        }
436
437        if config.bootstrap_count == 0 {
438            return Err(DevnetError::Config(
439                "At least one bootstrap node is required".to_string(),
440            ));
441        }
442
443        let node_count = config.node_count;
444        let node_count_u16 = u16::try_from(node_count).map_err(|_| {
445            DevnetError::Config(format!("Node count {node_count} exceeds u16::MAX"))
446        })?;
447
448        if config.base_port == 0 {
449            let mut rng = rand::thread_rng();
450            let max_base_port = DEVNET_PORT_RANGE_MAX.saturating_sub(node_count_u16);
451            config.base_port = rng.gen_range(DEVNET_PORT_RANGE_MIN..max_base_port);
452        }
453
454        let base_port = config.base_port;
455        let max_port = base_port
456            .checked_add(node_count_u16)
457            .ok_or_else(|| {
458                DevnetError::Config(format!(
459                    "Port range overflow: base_port {base_port} + node_count {node_count} exceeds u16::MAX"
460                ))
461            })?;
462        if max_port > DEVNET_PORT_RANGE_MAX {
463            return Err(DevnetError::Config(format!(
464                "Port range overflow: max port {max_port} exceeds DEVNET_PORT_RANGE_MAX {DEVNET_PORT_RANGE_MAX}"
465            )));
466        }
467
468        #[cfg(not(feature = "webrtc-direct"))]
469        if config.webrtc_direct {
470            return Err(DevnetError::Config(
471                "WebRtcDirect devnet support requires the 'webrtc-direct' feature".to_string(),
472            ));
473        }
474
475        #[cfg(feature = "webrtc-direct")]
476        if config.webrtc_direct {
477            if config.webrtc_direct_base_port == 0 {
478                let adjacent = max_port;
479                let adjacent_end = adjacent.checked_add(node_count_u16);
480                config.webrtc_direct_base_port = if adjacent_end
481                    .is_some_and(|end| end <= DEVNET_PORT_RANGE_MAX)
482                {
483                    adjacent
484                } else if let Some(before) = base_port
485                    .checked_sub(node_count_u16)
486                    .filter(|before| *before >= DEVNET_PORT_RANGE_MIN)
487                {
488                    before
489                } else {
490                    let mut rng = rand::thread_rng();
491                    let max_base = DEVNET_PORT_RANGE_MAX.saturating_sub(node_count_u16);
492                    (0..128)
493                        .map(|_| rng.gen_range(DEVNET_PORT_RANGE_MIN..max_base))
494                        .find(|candidate| {
495                            let end = candidate.saturating_add(node_count_u16);
496                            end <= base_port || *candidate >= max_port
497                        })
498                        .ok_or_else(|| {
499                            DevnetError::Config(
500                                "Could not allocate a disjoint WebRtcDirect port range".to_string(),
501                            )
502                        })?
503                };
504            }
505
506            let webrtc_direct_end = config
507                .webrtc_direct_base_port
508                .checked_add(node_count_u16)
509                .ok_or_else(|| {
510                    DevnetError::Config("WebRtcDirect port range overflow".to_string())
511                })?;
512            if config.webrtc_direct_base_port < DEVNET_PORT_RANGE_MIN
513                || webrtc_direct_end > DEVNET_PORT_RANGE_MAX
514            {
515                return Err(DevnetError::Config(format!(
516                    "WebRtcDirect ports must remain in the local test range {DEVNET_PORT_RANGE_MIN}..{DEVNET_PORT_RANGE_MAX}"
517                )));
518            }
519            if base_port < webrtc_direct_end && config.webrtc_direct_base_port < max_port {
520                return Err(DevnetError::Config(
521                    "Native and WebRtcDirect devnet port ranges overlap".to_string(),
522                ));
523            }
524        }
525
526        let parent = config.data_dir.clone();
527        let keep = !config.cleanup_data_dir;
528        let run_dir = tokio::task::spawn_blocking(move || RunDir::create(&parent, keep))
529            .await
530            .map_err(std::io::Error::other)??;
531        config.data_dir = run_dir.path().to_path_buf();
532        info!("Devnet data directory: {}", config.data_dir.display());
533
534        Ok(Self {
535            config,
536            nodes: Vec::new(),
537            shutdown: CancellationToken::new(),
538            state: Arc::new(RwLock::new(NetworkState::Uninitialized)),
539            health_monitor: None,
540            run_dir: Some(run_dir),
541            drain_grace: Duration::from_secs(DRAIN_GRACE_SECS),
542            #[cfg(feature = "webrtc-direct")]
543            browser_endpoint_catalog: Arc::new(crate::web_rtc::BrowserEndpointCatalog::default()),
544        })
545    }
546
547    /// Start the devnet.
548    ///
549    /// # Errors
550    ///
551    /// Returns `DevnetError::Startup` if any node fails to start, or
552    /// `DevnetError::Stabilization` if the network does not stabilize within the timeout.
553    pub async fn start(&mut self) -> Result<()> {
554        info!(
555            "Starting devnet with {} nodes ({} bootstrap)",
556            self.config.node_count, self.config.bootstrap_count
557        );
558
559        *self.state.write().await = NetworkState::BootstrappingPhase;
560        self.start_bootstrap_nodes().await?;
561
562        *self.state.write().await = NetworkState::NodeSpawningPhase;
563        self.start_regular_nodes().await?;
564
565        *self.state.write().await = NetworkState::Stabilizing;
566        self.wait_for_stabilization().await?;
567
568        self.start_health_monitor();
569
570        *self.state.write().await = NetworkState::Ready;
571        info!("Devnet is ready");
572        Ok(())
573    }
574
575    /// Shutdown the devnet.
576    ///
577    /// Stops every node, then removes the run's data directory, but only if
578    /// they have all stopped writing to it. A node that has not, because a
579    /// request is still being handled after a few seconds or its P2P node
580    /// failed to shut down, leaves the directory, locked until the process
581    /// exits; the next run removes it then.
582    ///
583    /// # Errors
584    ///
585    /// Returns `DevnetError::Io` if the data directory cleanup fails.
586    pub async fn shutdown(&mut self) -> Result<()> {
587        info!("Shutting down devnet");
588        *self.state.write().await = NetworkState::ShuttingDown;
589
590        self.shutdown.cancel();
591
592        if let Some(handle) = self.health_monitor.take() {
593            handle.abort();
594        }
595
596        let grace = self.drain_grace;
597        let mut stops = Vec::with_capacity(self.nodes.len());
598        for node in self.nodes.iter_mut().rev() {
599            debug!("Stopping node {}", node.index);
600            let node_index = node.index;
601            let node_state = Arc::clone(&node.state);
602            let protocol_task = node.protocol_task.take();
603            #[cfg(feature = "webrtc-direct")]
604            let webrtc_direct_task = node.webrtc_direct_task.take();
605            let handlers = node.handlers.clone();
606            let storage = node
607                .ant_protocol
608                .as_ref()
609                .map(|protocol| protocol.storage());
610            let p2p_node = node.p2p_node.take();
611
612            stops.push(async move {
613                let mut stopped = true;
614                // The token cancelled above closes the browser listener,
615                // which drains its own requests before it returns.
616                #[cfg(feature = "webrtc-direct")]
617                if let Some(handle) = webrtc_direct_task {
618                    if let Err(error) = handle.await {
619                        warn!("Error stopping node {node_index} WebRtcDirect listener: {error}");
620                        stopped = false;
621                    }
622                }
623                // As a node does: the routing loop first, aborted and awaited
624                // so that it starts no more handlers, then the handlers it
625                // started, given a moment to finish.
626                if let Some(handle) = protocol_task {
627                    handle.abort();
628                    let _ = handle.await;
629                }
630                handlers.close();
631                if tokio::time::timeout(grace, handlers.wait()).await.is_err() {
632                    warn!(
633                        "Node {node_index}: {} request handler(s) still running after {grace:?}",
634                        handlers.len()
635                    );
636                    stopped = false;
637                }
638                // A storage write outlives the future that started it.
639                if let Some(storage) = storage {
640                    if tokio::time::timeout(grace, storage.wait_idle())
641                        .await
642                        .is_err()
643                    {
644                        warn!("Node {node_index}: storage writes still running after {grace:?}");
645                        stopped = false;
646                    }
647                }
648                if let Some(p2p) = p2p_node {
649                    if let Err(e) = p2p.shutdown().await {
650                        warn!("Error shutting down node {node_index}: {e}");
651                        stopped = false;
652                    }
653                }
654                *node_state.write().await = NodeState::Stopped;
655                stopped
656            });
657        }
658        let all_stopped = futures::future::join_all(stops)
659            .await
660            .into_iter()
661            .all(|stopped| stopped);
662
663        match self.run_dir.take() {
664            Some(run_dir) if !all_stopped => {
665                warn!(
666                    "Leaving devnet data directory {}: not every node has stopped writing to it. \
667                     It stays locked until this process exits, and the next run removes it.",
668                    self.config.data_dir.display()
669                );
670                run_dir.keep_locked_until_exit();
671            }
672            Some(run_dir) if self.config.cleanup_data_dir => {
673                match tokio::task::spawn_blocking(move || run_dir.remove()).await {
674                    Ok(Ok(())) => {}
675                    Ok(Err(e)) => warn!(
676                        "Failed to remove devnet data directory {}: {e}",
677                        self.config.data_dir.display()
678                    ),
679                    Err(e) => warn!("Failed to remove devnet data directory: {e}"),
680                }
681            }
682            // Without cleanup, dropping the run directory releases its lock
683            // and leaves it, marked to be kept.
684            Some(_) | None => {}
685        }
686
687        *self.state.write().await = NetworkState::Stopped;
688        info!("Devnet shutdown complete");
689        Ok(())
690    }
691
692    /// A token that stops this devnet's [`start`](Self::start) when cancelled.
693    ///
694    /// A start in progress returns an error at its next safe point: between
695    /// node spawns, or while it waits for nodes to come up or the network to
696    /// stabilize. Every node it started is registered by then, so a following
697    /// [`shutdown`](Self::shutdown) stops them all before it removes the data
698    /// directory. Dropping a `start` future part-way instead can leave a node
699    /// running unregistered, still writing into that directory. It is the same
700    /// token `shutdown` cancels.
701    #[must_use]
702    pub fn cancellation_token(&self) -> CancellationToken {
703        self.shutdown.clone()
704    }
705
706    /// Wait `delay`, or fail at once if the devnet has been cancelled.
707    async fn pause(&self, delay: Duration) -> Result<()> {
708        tokio::select! {
709            biased;
710            () = self.shutdown.cancelled() => Err(start_cancelled()),
711            () = tokio::time::sleep(delay) => Ok(()),
712        }
713    }
714
715    /// Get devnet configuration.
716    #[must_use]
717    pub fn config(&self) -> &DevnetConfig {
718        &self.config
719    }
720
721    /// Get bootstrap addresses.
722    #[must_use]
723    pub fn bootstrap_addrs(&self) -> Vec<MultiAddr> {
724        self.nodes
725            .iter()
726            .take(self.config.bootstrap_count)
727            .map(|n| {
728                MultiAddr::quic(SocketAddr::from((
729                    self.config.advertise_ip.unwrap_or(Ipv4Addr::LOCALHOST),
730                    n.port,
731                )))
732            })
733            .collect()
734    }
735
736    /// Snapshot every browser listener, including counters retained after shutdown.
737    #[cfg(feature = "webrtc-direct")]
738    #[must_use]
739    pub fn browser_listener_diagnostics(&self) -> Vec<crate::web_rtc::WebRtcServerSnapshot> {
740        self.nodes
741            .iter()
742            .filter_map(|node| {
743                node.webrtc_diagnostics
744                    .as_ref()
745                    .map(crate::web_rtc::WebRtcServerDiagnostics::snapshot)
746            })
747            .collect()
748    }
749
750    /// Test-only handles for exercising browser admission during stalled storage.
751    #[cfg(all(feature = "webrtc-direct", feature = "test-utils"))]
752    #[must_use]
753    pub fn test_browser_node(
754        &self,
755        index: usize,
756    ) -> Option<(Arc<AntProtocol>, crate::web_rtc::WebRtcServerDiagnostics)> {
757        let node = self.nodes.get(index)?;
758        Some((
759            Arc::clone(node.ant_protocol.as_ref()?),
760            node.webrtc_diagnostics.clone()?,
761        ))
762    }
763
764    /// Get every direct browser endpoint in this devnet.
765    #[cfg(feature = "webrtc-direct")]
766    #[must_use]
767    pub fn browser_endpoints(&self) -> Vec<BrowserBootstrapNode> {
768        self.nodes
769            .iter()
770            .filter_map(|node| {
771                node.browser_endpoint
772                    .clone()
773                    .map(|endpoint| BrowserBootstrapNode { endpoint })
774            })
775            .collect()
776    }
777
778    /// Publish a complete self-encrypted file to the browser-enabled devnet.
779    ///
780    /// The file is split using the same `self_encryption` crate as `ant-client`.
781    /// Every encrypted data chunk and the public `MessagePack` `DataMap` are then
782    /// submitted through each node's ordinary chunk PUT handler. Address
783    /// verification, DHT responsibility, payment-cache admission, and chunk
784    /// integrity checks therefore remain active.
785    ///
786    /// # Errors
787    ///
788    /// Returns an error when WebRTC Direct is disabled, self-encryption fails,
789    /// a generated chunk is too large, no node admits a required record, or
790    /// protocol serialization fails.
791    #[cfg(all(feature = "webrtc-direct", feature = "test-utils"))]
792    pub async fn publish_public_file(
793        &self,
794        name: String,
795        content_type: String,
796        content: &[u8],
797    ) -> Result<BrowserPublicFile> {
798        if !self.config.webrtc_direct {
799            return Err(DevnetError::Config(
800                "Cannot publish a browser file when WebRtcDirect is disabled".to_string(),
801            ));
802        }
803        if content.len() < self_encryption::MIN_ENCRYPTABLE_BYTES {
804            return Err(DevnetError::Config(format!(
805                "Public file is {} bytes; self-encryption requires at least {} bytes",
806                content.len(),
807                self_encryption::MIN_ENCRYPTABLE_BYTES
808            )));
809        }
810
811        let (published_data_map, encrypted_chunks) =
812            self_encryption::encrypt(Bytes::copy_from_slice(content)).map_err(|error| {
813                DevnetError::Core(format!("Failed to self-encrypt browser file: {error}"))
814            })?;
815        let mut records = HashMap::<[u8; 32], Bytes>::new();
816        for chunk in encrypted_chunks {
817            if chunk.content.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
818                return Err(DevnetError::Core(format!(
819                    "Self-encryption produced a {}-byte chunk; node maximum is {}",
820                    chunk.content.len(),
821                    crate::ant_protocol::MAX_CHUNK_SIZE
822                )));
823            }
824            let address = crate::client::compute_address(&chunk.content);
825            records.entry(address).or_insert(chunk.content);
826        }
827
828        let mut get_local_chunk = |address: self_encryption::XorName| {
829            records.get(&address.0).cloned().ok_or_else(|| {
830                self_encryption::Error::Generic(format!(
831                    "Self-encryption output omitted chunk {}",
832                    hex::encode(address.0)
833                ))
834            })
835        };
836        let root_data_map =
837            self_encryption::get_root_data_map(published_data_map.clone(), &mut get_local_chunk)
838                .map_err(|error| {
839                    DevnetError::Core(format!("Failed to resolve browser file DataMap: {error}"))
840                })?;
841        let serialized_data_map = rmp_serde::to_vec(&published_data_map).map_err(|error| {
842            DevnetError::Core(format!("Failed to serialize browser file DataMap: {error}"))
843        })?;
844        let data_map_size = serialized_data_map.len();
845        let data_map_address = crate::client::compute_address(&serialized_data_map);
846        records.insert(data_map_address, Bytes::from(serialized_data_map));
847
848        let record_count = records.len();
849        let mut replicas = usize::MAX;
850        for (address, bytes) in &records {
851            replicas = replicas.min(self.publish_browser_record(*address, bytes).await?);
852        }
853
854        let chunks = root_data_map
855            .infos()
856            .iter()
857            .map(|info| crate::browser::BrowserChunkInfo {
858                index: info.index,
859                dst_hash: hex::encode(info.dst_hash.0),
860                src_hash: hex::encode(info.src_hash.0),
861                src_size: info.src_size,
862            })
863            .collect();
864        let published = BrowserPublicFile {
865            name,
866            address: hex::encode(data_map_address),
867            size: content.len(),
868            content_type,
869            blake3: hex::encode(crate::client::compute_address(content)),
870            data_map_size,
871            chunks,
872            replicas,
873        };
874        info!(
875            "Published browser devnet file '{}' at {} as {record_count} record(s), each on at least {} node(s)",
876            published.name, published.address, published.replicas
877        );
878        Ok(published)
879    }
880
881    /// Public EVM chain and contracts advertised to direct browser clients.
882    ///
883    /// # Errors
884    ///
885    /// Returns `DevnetError::Config` if a custom RPC cannot report its chain ID.
886    #[cfg(feature = "webrtc-direct")]
887    pub async fn browser_payment_network(&self) -> Result<BrowserPaymentNetwork> {
888        let network = self
889            .config
890            .evm_network
891            .as_ref()
892            .unwrap_or(&EvmNetwork::ArbitrumOne);
893        browser_payment_network(network)
894            .await
895            .map_err(|error| DevnetError::Config(error.to_string()))
896    }
897
898    #[cfg(all(feature = "webrtc-direct", feature = "test-utils"))]
899    async fn publish_browser_record(&self, address: [u8; 32], content: &Bytes) -> Result<usize> {
900        let mut replicas = 0usize;
901        let mut failures = Vec::new();
902
903        for node in &self.nodes {
904            let Some(protocol) = node.ant_protocol.as_ref() else {
905                failures.push(format!("node {} has no protocol handler", node.index));
906                continue;
907            };
908            protocol
909                .payment_verifier_arc()
910                .cache_insert_browser_devnet_seed(address);
911
912            let request = ChunkMessage {
913                request_id: u64::try_from(node.index).unwrap_or(u64::MAX),
914                body: ChunkMessageBody::PutRequest(ChunkPutRequest::new(address, content.clone())),
915            };
916            let request_bytes = request.encode().map_err(|error| {
917                DevnetError::Core(format!("Failed to encode public-file PUT: {error}"))
918            })?;
919            let response_bytes = protocol
920                .try_handle_request(&request_bytes)
921                .await
922                .map_err(|error| {
923                    DevnetError::Core(format!(
924                        "Node {} public-file PUT failed: {error}",
925                        node.index
926                    ))
927                })?
928                .ok_or_else(|| {
929                    DevnetError::Core(format!(
930                        "Node {} returned no public-file PUT response",
931                        node.index
932                    ))
933                })?;
934            let response = ChunkMessage::decode(&response_bytes).map_err(|error| {
935                DevnetError::Core(format!(
936                    "Failed to decode node {} public-file response: {error}",
937                    node.index
938                ))
939            })?;
940            match response.body {
941                ChunkMessageBody::PutResponse(
942                    ChunkPutResponse::Success { .. } | ChunkPutResponse::AlreadyExists { .. },
943                ) => {
944                    replicas += 1;
945                }
946                ChunkMessageBody::PutResponse(other) => {
947                    failures.push(format!("node {}: {other:?}", node.index));
948                }
949                other => failures.push(format!(
950                    "node {} returned unexpected response {other:?}",
951                    node.index
952                )),
953            }
954        }
955
956        if replicas == 0 {
957            return Err(DevnetError::Startup(format!(
958                "No devnet node admitted browser record {}: {}",
959                hex::encode(address),
960                failures.join("; ")
961            )));
962        }
963        if !failures.is_empty() {
964            debug!(
965                "Browser record was admitted by {replicas} nodes; {} non-responsible/failed nodes: {}",
966                failures.len(),
967                failures.join("; ")
968            );
969        }
970        Ok(replicas)
971    }
972
973    async fn start_bootstrap_nodes(&mut self) -> Result<()> {
974        info!("Starting {} bootstrap nodes", self.config.bootstrap_count);
975
976        for i in 0..self.config.bootstrap_count {
977            let node = self.create_node(i, true, vec![]).await?;
978            self.start_node(node).await?;
979            self.pause(self.config.spawn_delay).await?;
980        }
981
982        self.wait_for_nodes_ready(0..self.config.bootstrap_count)
983            .await?;
984
985        info!("All bootstrap nodes are ready");
986        Ok(())
987    }
988
989    async fn start_regular_nodes(&mut self) -> Result<()> {
990        let regular_count = self.config.node_count - self.config.bootstrap_count;
991        info!("Starting {} regular nodes", regular_count);
992
993        let bootstrap_addrs: Vec<MultiAddr> = self
994            .nodes
995            .get(0..self.config.bootstrap_count)
996            .ok_or_else(|| {
997                DevnetError::Config(format!(
998                    "Bootstrap count {} exceeds nodes length {}",
999                    self.config.bootstrap_count,
1000                    self.nodes.len()
1001                ))
1002            })?
1003            .iter()
1004            .map(|n| {
1005                MultiAddr::quic(SocketAddr::from((
1006                    self.config.advertise_ip.unwrap_or(Ipv4Addr::LOCALHOST),
1007                    n.port,
1008                )))
1009            })
1010            .collect();
1011
1012        for i in self.config.bootstrap_count..self.config.node_count {
1013            let node = self.create_node(i, false, bootstrap_addrs.clone()).await?;
1014            self.start_node(node).await?;
1015            self.pause(self.config.spawn_delay).await?;
1016        }
1017
1018        info!("All regular nodes started");
1019        Ok(())
1020    }
1021
1022    async fn create_node(
1023        &self,
1024        index: usize,
1025        is_bootstrap: bool,
1026        bootstrap_addrs: Vec<MultiAddr>,
1027    ) -> Result<DevnetNode> {
1028        let index_u16 = u16::try_from(index)
1029            .map_err(|_| DevnetError::Config(format!("Node index {index} exceeds u16::MAX")))?;
1030        let port = self.config.base_port + index_u16;
1031
1032        // Generate identity first so we can use peer_id as the directory name
1033        let identity = NodeIdentity::generate()
1034            .map_err(|e| DevnetError::Core(format!("Failed to generate node identity: {e}")))?;
1035        let peer_id = *identity.peer_id();
1036        let label = format!("devnet_node_{index}");
1037        let data_dir = self
1038            .config
1039            .data_dir
1040            .join(NODES_SUBDIR)
1041            .join(peer_id.to_hex());
1042
1043        tokio::fs::create_dir_all(&data_dir).await?;
1044
1045        identity
1046            .save_to_file(&data_dir.join(NODE_IDENTITY_FILENAME))
1047            .await
1048            .map_err(|e| DevnetError::Core(format!("Failed to save node identity: {e}")))?;
1049
1050        let ant_protocol = Self::create_ant_protocol(&data_dir, &identity, &self.config).await?;
1051
1052        Ok(DevnetNode {
1053            index,
1054            label,
1055            peer_id,
1056            port,
1057            data_dir,
1058            p2p_node: None,
1059            ant_protocol: Some(Arc::new(ant_protocol)),
1060            is_bootstrap,
1061            state: Arc::new(RwLock::new(NodeState::Pending)),
1062            bootstrap_addrs,
1063            protocol_task: None,
1064            handlers: TaskTracker::new(),
1065            #[cfg(feature = "webrtc-direct")]
1066            webrtc_direct_task: None,
1067            #[cfg(feature = "webrtc-direct")]
1068            webrtc_diagnostics: None,
1069            #[cfg(feature = "webrtc-direct")]
1070            browser_endpoint: None,
1071        })
1072    }
1073
1074    async fn create_ant_protocol(
1075        data_dir: &std::path::Path,
1076        identity: &NodeIdentity,
1077        config: &DevnetConfig,
1078    ) -> Result<AntProtocol> {
1079        let storage_config = ChunkStoreConfig {
1080            root_dir: data_dir.to_path_buf(),
1081            verify_on_read: true,
1082            ..ChunkStoreConfig::default()
1083        };
1084        let storage = ChunkStore::new(storage_config)
1085            .await
1086            .map_err(|e| DevnetError::Core(format!("Failed to create the chunk store: {e}")))?;
1087
1088        let evm_config = EvmVerifierConfig {
1089            network: config
1090                .evm_network
1091                .clone()
1092                .unwrap_or(EvmNetwork::ArbitrumOne),
1093        };
1094
1095        let rewards_address = RewardsAddress::new(DEVNET_REWARDS_ADDRESS);
1096        let replication_config = ReplicationConfig::default();
1097        let payment_config = PaymentVerifierConfig {
1098            evm: evm_config,
1099            cache_capacity: DEVNET_PAYMENT_CACHE_CAPACITY,
1100            close_group_size: replication_config.close_group_size,
1101            local_rewards_address: rewards_address,
1102            price_floor: PriceFloorConfig::default(),
1103        };
1104        let payment_verifier = PaymentVerifier::new(payment_config);
1105        let metrics_tracker = QuotingMetricsTracker::new(DEVNET_INITIAL_RECORDS);
1106        let mut quote_generator = QuoteGenerator::new(rewards_address, metrics_tracker);
1107
1108        // Wire ML-DSA-65 signing from the devnet node's identity
1109        crate::payment::wire_ml_dsa_signer(&mut quote_generator, identity)
1110            .map_err(|e| DevnetError::Startup(format!("Failed to wire ML-DSA-65 signer: {e}")))?;
1111
1112        let storage = Arc::new(storage);
1113        let payment_verifier = Arc::new(payment_verifier);
1114
1115        // Same pointer wiring as a production node, so a devnet exercises the
1116        // real path rather than a node that silently refuses every pointer.
1117        let pointer_store = crate::pointer::PointerStore::new(storage.root_dir())
1118            .await
1119            .map_err(|e| DevnetError::Startup(format!("Failed to open pointer store: {e}")))?;
1120        let pointers = crate::pointer::PointerService::new(pointer_store)
1121            .with_chunk_store(Arc::clone(&storage))
1122            .with_payments(Arc::clone(&payment_verifier));
1123
1124        Ok(
1125            AntProtocol::new(storage, payment_verifier, Arc::new(quote_generator))
1126                .with_pointer_service(pointers),
1127        )
1128    }
1129
1130    #[allow(clippy::too_many_lines)]
1131    async fn start_node(&mut self, mut node: DevnetNode) -> Result<()> {
1132        debug!("Starting node {} on port {}", node.index, node.port);
1133        *node.state.write().await = NodeState::Starting;
1134
1135        let mut core_config = CoreNodeConfig::builder()
1136            .port(node.port)
1137            .local(self.config.advertise_ip.is_none())
1138            .max_message_size(crate::ant_protocol::MAX_WIRE_MESSAGE_SIZE)
1139            .build()
1140            .map_err(|e| DevnetError::Core(format!("Failed to create core config: {e}")))?;
1141
1142        // Load the node identity for app-level message signing.
1143        let identity = NodeIdentity::load_from_file(
1144            &node.data_dir.join(crate::config::NODE_IDENTITY_FILENAME),
1145        )
1146        .await
1147        .map_err(|e| DevnetError::Core(format!("Failed to load node identity: {e}")))?;
1148
1149        core_config.node_identity = Some(Arc::new(identity));
1150        core_config
1151            .bootstrap_peers
1152            .clone_from(&node.bootstrap_addrs);
1153        core_config.diversity_config = Some(IPDiversityConfig::permissive());
1154        // Devnet nodes serve chunks, so they announce get-or-closer
1155        // (ADR-0020) as a production node does.
1156        core_config.custom_user_agent = Some(crate::node::user_agent(true));
1157
1158        let index = node.index;
1159        let p2p_node = P2PNode::new(core_config)
1160            .await
1161            .map_err(|e| DevnetError::Startup(format!("Failed to create node {index}: {e}")))?;
1162
1163        p2p_node
1164            .start()
1165            .await
1166            .map_err(|e| DevnetError::Startup(format!("Failed to start node {index}: {e}")))?;
1167
1168        node.p2p_node = Some(Arc::new(p2p_node));
1169        *node.state.write().await = NodeState::Running;
1170        // Registered as soon as it runs, so that should the rest of its
1171        // startup fail, shutdown still stops it before removing its data.
1172        self.nodes.push(node);
1173        let node = self
1174            .nodes
1175            .last_mut()
1176            .ok_or_else(|| DevnetError::Startup(format!("Node {index} was not registered")))?;
1177
1178        #[cfg(feature = "webrtc-direct")]
1179        if self.config.webrtc_direct {
1180            let index_u16 = u16::try_from(node.index).map_err(|_| {
1181                DevnetError::Config(format!("Node index {} exceeds u16::MAX", node.index))
1182            })?;
1183            let port = self
1184                .config
1185                .webrtc_direct_base_port
1186                .checked_add(index_u16)
1187                .ok_or_else(|| {
1188                    DevnetError::Config(format!(
1189                        "WebRtcDirect port overflow for node {}",
1190                        node.index
1191                    ))
1192                })?;
1193            let advertised_ip = self.config.advertise_ip.unwrap_or(Ipv4Addr::LOCALHOST);
1194            let bind_ip = self
1195                .config
1196                .advertise_ip
1197                .map_or(Ipv4Addr::LOCALHOST, |_| Ipv4Addr::UNSPECIFIED);
1198            let webrtc_direct_config = WebRtcDirectConfig {
1199                enabled: true,
1200                bind: SocketAddr::from((bind_ip, port)),
1201                advertised_addr: Some(SocketAddr::from((advertised_ip, port))),
1202                ..WebRtcDirectConfig::default()
1203            };
1204
1205            let p2p = node.p2p_node.clone().ok_or_else(|| {
1206                DevnetError::Startup(format!(
1207                    "Node {} lost its P2P handle before WebRtcDirect startup",
1208                    node.index
1209                ))
1210            })?;
1211            let server = crate::web_rtc::spawn(
1212                &webrtc_direct_config,
1213                &node.data_dir,
1214                p2p,
1215                node.ant_protocol.clone(),
1216                self.config
1217                    .evm_network
1218                    .as_ref()
1219                    .unwrap_or(&EvmNetwork::ArbitrumOne),
1220                self.shutdown.clone(),
1221                Some(Arc::clone(&self.browser_endpoint_catalog)),
1222            )
1223            .await
1224            .map_err(|error| {
1225                DevnetError::Startup(format!(
1226                    "Failed to start node {} WebRtcDirect listener: {error}",
1227                    node.index
1228                ))
1229            })?;
1230            node.browser_endpoint = server.endpoint;
1231            node.webrtc_diagnostics = Some(server.diagnostics);
1232            node.webrtc_direct_task = Some(server.task);
1233        }
1234
1235        if let (Some(ref p2p), Some(ref protocol)) = (&node.p2p_node, &node.ant_protocol) {
1236            // Wire P2P into AntProtocol for payment-proof closeness checks.
1237            protocol.attach_p2p_node(Arc::clone(p2p));
1238
1239            let mut events = p2p.subscribe_events();
1240            let p2p_clone = Arc::clone(p2p);
1241            let protocol_clone = Arc::clone(protocol);
1242            let handlers = node.handlers.clone();
1243            let node_index = node.index;
1244            node.protocol_task = Some(tokio::spawn(async move {
1245                while let Ok(event) = events.recv().await {
1246                    if let P2PEvent::Message {
1247                        topic,
1248                        source: Some(source),
1249                        data,
1250                        ..
1251                    } = event
1252                    {
1253                        if topic == CHUNK_PROTOCOL_ID {
1254                            debug!(
1255                                "Node {node_index} received chunk protocol message from {source}"
1256                            );
1257                            let protocol = Arc::clone(&protocol_clone);
1258                            let p2p = Arc::clone(&p2p_clone);
1259                            let received_at = Instant::now();
1260                            handlers.spawn(handle_chunk_message(
1261                                protocol,
1262                                p2p,
1263                                source,
1264                                data,
1265                                node_index,
1266                                received_at,
1267                            ));
1268                        }
1269                    }
1270                }
1271            }));
1272        }
1273
1274        debug!("Node {} started successfully", node.index);
1275        Ok(())
1276    }
1277
1278    async fn wait_for_nodes_ready(&self, range: std::ops::Range<usize>) -> Result<()> {
1279        let deadline = Instant::now() + self.config.node_startup_timeout;
1280
1281        for i in range {
1282            while Instant::now() < deadline {
1283                let node = self.nodes.get(i).ok_or_else(|| {
1284                    DevnetError::Config(format!(
1285                        "Node index {i} out of bounds (len: {})",
1286                        self.nodes.len()
1287                    ))
1288                })?;
1289                let state = node.state.read().await.clone();
1290                match state {
1291                    NodeState::Running | NodeState::Connected => break,
1292                    NodeState::Failed(ref e) => {
1293                        return Err(DevnetError::Startup(format!("Node {i} failed: {e}")));
1294                    }
1295                    _ => {
1296                        self.pause(Duration::from_millis(NODE_READY_POLL_INTERVAL_MS))
1297                            .await?;
1298                    }
1299                }
1300            }
1301        }
1302        Ok(())
1303    }
1304
1305    async fn wait_for_stabilization(&self) -> Result<()> {
1306        let deadline = Instant::now() + self.config.stabilization_timeout;
1307        let min_connections = self
1308            .config
1309            .bootstrap_count
1310            .min(STABILIZATION_MIN_CONNECTIONS_CAP);
1311
1312        info!(
1313            "Waiting for devnet stabilization (min {} connections per node)",
1314            min_connections
1315        );
1316
1317        while Instant::now() < deadline {
1318            let mut all_connected = true;
1319            let mut total_connections = 0;
1320
1321            for node in &self.nodes {
1322                let peer_count = node.peer_count().await;
1323                total_connections += peer_count;
1324
1325                if peer_count < min_connections {
1326                    all_connected = false;
1327                }
1328            }
1329
1330            if all_connected {
1331                info!("Devnet stabilized: {} total connections", total_connections);
1332                return Ok(());
1333            }
1334
1335            debug!(
1336                "Waiting for stabilization: {} total connections",
1337                total_connections
1338            );
1339            self.pause(Duration::from_secs(STABILIZATION_POLL_INTERVAL_SECS))
1340                .await?;
1341        }
1342
1343        Err(DevnetError::Stabilization(
1344            "Devnet failed to stabilize within timeout".to_string(),
1345        ))
1346    }
1347
1348    fn start_health_monitor(&mut self) {
1349        let nodes: Vec<Arc<P2PNode>> = self
1350            .nodes
1351            .iter()
1352            .filter_map(|n| n.p2p_node.clone())
1353            .collect();
1354        let shutdown = self.shutdown.clone();
1355
1356        self.health_monitor = Some(tokio::spawn(async move {
1357            let check_interval = Duration::from_secs(HEALTH_CHECK_INTERVAL_SECS);
1358
1359            loop {
1360                tokio::select! {
1361                    () = shutdown.cancelled() => break,
1362                    () = tokio::time::sleep(check_interval) => {
1363                        for (i, node) in nodes.iter().enumerate() {
1364                            if !node.is_running() {
1365                                warn!("Node {} appears unhealthy", i);
1366                            }
1367                        }
1368                    }
1369                }
1370            }
1371        }));
1372    }
1373}
1374
1375/// The error a cancelled [`Devnet::start`] returns.
1376fn start_cancelled() -> DevnetError {
1377    DevnetError::Startup("devnet start cancelled".to_string())
1378}
1379
1380impl Drop for Devnet {
1381    fn drop(&mut self) {
1382        self.shutdown.cancel();
1383        if let Some(handle) = self.health_monitor.take() {
1384            handle.abort();
1385        }
1386        // Not shut down, so nodes it started may still be running: their
1387        // tasks hold them, and outlive this. Keep the run directory locked
1388        // until the process exits, so that no sweep deletes it under them. A
1389        // later run removes it then, as it would after a SIGKILL.
1390        if let Some(run_dir) = self.run_dir.take() {
1391            run_dir.keep_locked_until_exit();
1392        }
1393    }
1394}
1395
1396#[cfg(test)]
1397mod tests {
1398    use super::*;
1399
1400    /// Backward-compatibility contract: a default config advertises no LAN IP,
1401    /// so nodes bind loopback (`.local(advertise_ip.is_none())` → `.local(true)`)
1402    /// and stamp `127.0.0.1` into the manifest bootstrap addresses — exactly as
1403    /// before the `--host` flag existed.
1404    #[test]
1405    fn default_config_has_no_advertise_ip() {
1406        assert!(DevnetConfig::default().advertise_ip.is_none());
1407    }
1408
1409    #[test]
1410    fn runs_go_in_the_devnets_dir_of_the_data_root_by_default() {
1411        let devnets = default_root_dir().join(DEVNETS_SUBDIR);
1412        for config in [
1413            DevnetConfig::default(),
1414            DevnetConfig::minimal(),
1415            DevnetConfig::small(),
1416        ] {
1417            assert_eq!(config.data_dir, devnets);
1418            assert!(config.cleanup_data_dir);
1419        }
1420    }
1421
1422    #[tokio::test]
1423    async fn each_devnet_gets_and_removes_only_its_own_run_dir(
1424    ) -> std::result::Result<(), Box<dyn std::error::Error>> {
1425        let temp = tempfile::tempdir()?;
1426        let parent = temp.path().join("devnets");
1427        let mut config = DevnetConfig::minimal();
1428        config.data_dir.clone_from(&parent);
1429        let mut first = Devnet::new(config.clone()).await?;
1430        let mut second = Devnet::new(config).await?;
1431        let first_dir = first.config().data_dir.clone();
1432        let second_dir = second.config().data_dir.clone();
1433
1434        assert_ne!(first_dir, second_dir);
1435        for dir in [&first_dir, &second_dir] {
1436            assert_eq!(
1437                dir.parent().map(std::fs::canonicalize).transpose()?,
1438                Some(std::fs::canonicalize(&parent)?),
1439                "{}",
1440                dir.display()
1441            );
1442            assert!(dir.join(MARKER_FILE).is_file(), "{}", dir.display());
1443        }
1444
1445        first.shutdown().await?;
1446        assert!(!first_dir.exists());
1447        assert!(second_dir.join(MARKER_FILE).is_file());
1448        second.shutdown().await?;
1449        assert!(!second_dir.exists());
1450        assert!(parent.is_dir(), "the parent is not the devnet's to delete");
1451        Ok(())
1452    }
1453
1454    #[tokio::test]
1455    async fn without_cleanup_the_run_dir_is_kept(
1456    ) -> std::result::Result<(), Box<dyn std::error::Error>> {
1457        let temp = tempfile::tempdir()?;
1458        let mut config = DevnetConfig::minimal();
1459        config.data_dir = temp.path().to_path_buf();
1460        config.cleanup_data_dir = false;
1461        let mut devnet = Devnet::new(config.clone()).await?;
1462        let kept = devnet.config().data_dir.clone();
1463        devnet.shutdown().await?;
1464        drop(devnet);
1465
1466        // A later run's sweep leaves it too.
1467        config.cleanup_data_dir = true;
1468        let mut later = Devnet::new(config).await?;
1469        assert!(kept.join(MARKER_FILE).is_file());
1470        later.shutdown().await?;
1471        assert!(kept.join(MARKER_FILE).is_file());
1472        Ok(())
1473    }
1474
1475    /// A devnet of two nodes, quick to start, running in `parent`.
1476    fn two_nodes(parent: &std::path::Path) -> DevnetConfig {
1477        let mut config = DevnetConfig::minimal();
1478        config.node_count = 2;
1479        config.bootstrap_count = 1;
1480        config.base_port = 0;
1481        config.spawn_delay = Duration::from_millis(20);
1482        config.data_dir = parent.join("devnets");
1483        config
1484    }
1485
1486    /// Hermes round 3 on #263: a started devnet dropped without a shutdown
1487    /// leaves nodes running, still writing into its run directory, so the
1488    /// next devnet's sweep must leave it.
1489    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1490    async fn a_started_devnet_dropped_without_shutdown_is_not_swept(
1491    ) -> std::result::Result<(), Box<dyn std::error::Error>> {
1492        let temp = tempfile::tempdir()?;
1493        let config = two_nodes(temp.path());
1494        let mut dropped = Devnet::new(config.clone()).await?;
1495        dropped.start().await?;
1496        let dropped_dir = dropped.config().data_dir.clone();
1497        drop(dropped);
1498
1499        let mut next = Devnet::new(config).await?;
1500
1501        assert!(
1502            dropped_dir.join(MARKER_FILE).is_file(),
1503            "the next devnet swept {}",
1504            dropped_dir.display()
1505        );
1506        next.shutdown().await?;
1507        Ok(())
1508    }
1509
1510    /// Hermes round 4 on #263: a PUT still being written when the devnet
1511    /// shuts down keeps the run directory, locked, rather than having it
1512    /// removed under the write.
1513    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1514    #[allow(clippy::await_holding_lock)]
1515    async fn a_put_still_being_written_at_shutdown_keeps_the_run_dir(
1516    ) -> std::result::Result<(), Box<dyn std::error::Error>> {
1517        use crate::ant_protocol::{ChunkMessage, ChunkMessageBody, ChunkPutRequest};
1518
1519        let temp = tempfile::tempdir()?;
1520        let mut devnet = Devnet::new(two_nodes(temp.path())).await?;
1521        devnet.start().await?;
1522        devnet.drain_grace = Duration::from_millis(500);
1523        let run_dir = devnet.config().data_dir.clone();
1524        let sender = devnet
1525            .nodes
1526            .first()
1527            .and_then(|node| node.p2p_node.clone())
1528            .ok_or("no sender")?;
1529        let receiver = devnet.nodes.get(1).ok_or("no receiver")?;
1530        let peer = receiver.peer_id;
1531        let protocol = receiver.ant_protocol.clone().ok_or("no protocol")?;
1532        let storage = protocol.storage();
1533        let content = b"a chunk still being written at shutdown";
1534        let address = ChunkStore::compute_address(content);
1535        protocol.payment_verifier().cache_insert(address);
1536        let request = ChunkMessage {
1537            request_id: 1,
1538            body: ChunkMessageBody::PutRequest(ChunkPutRequest::new(
1539                address,
1540                bytes::Bytes::from_static(content),
1541            )),
1542        }
1543        .encode()?;
1544
1545        // Held, the write waits on its way into the store.
1546        let gate = storage.test_put_gate();
1547        let held = gate.write();
1548        sender
1549            .send_message(&peer, CHUNK_PROTOCOL_ID, request, &[])
1550            .await?;
1551        let deadline = Instant::now() + Duration::from_secs(30);
1552        while storage.tasks_in_flight() == 0 {
1553            assert!(Instant::now() < deadline, "the PUT never reached the store");
1554            tokio::time::sleep(Duration::from_millis(10)).await;
1555        }
1556
1557        devnet.shutdown().await?;
1558
1559        assert!(
1560            run_dir.join(MARKER_FILE).is_file(),
1561            "{} was removed under a write",
1562            run_dir.display()
1563        );
1564        drop(held);
1565        storage.wait_idle().await;
1566        assert!(run_dir.join(MARKER_FILE).is_file());
1567        // Kept locked, so the next run leaves it too.
1568        let mut next = Devnet::new(two_nodes(temp.path())).await?;
1569        assert!(run_dir.join(MARKER_FILE).is_file());
1570        next.shutdown().await?;
1571        Ok(())
1572    }
1573
1574    /// Hermes round 4 on #263: a node whose startup fails once its P2P node
1575    /// is running, here because its WebRTC Direct port is taken, is
1576    /// registered all the same, so shutdown stops it.
1577    #[cfg(feature = "webrtc-direct")]
1578    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1579    async fn a_node_whose_startup_fails_part_way_is_stopped_by_shutdown(
1580    ) -> std::result::Result<(), Box<dyn std::error::Error>> {
1581        let temp = tempfile::tempdir()?;
1582        let mut config = two_nodes(temp.path());
1583        config.webrtc_direct = true;
1584        let mut devnet = Devnet::new(config).await?;
1585        let taken = std::net::UdpSocket::bind((
1586            Ipv4Addr::LOCALHOST,
1587            devnet.config().webrtc_direct_base_port,
1588        ))?;
1589
1590        let started = devnet.start().await;
1591
1592        assert!(
1593            matches!(started, Err(DevnetError::Startup(_))),
1594            "{started:?}"
1595        );
1596        let p2p = devnet
1597            .nodes
1598            .first()
1599            .and_then(|node| node.p2p_node.clone())
1600            .ok_or("the node that failed part-way was not registered")?;
1601        assert!(p2p.is_running());
1602        devnet.shutdown().await?;
1603        assert!(!p2p.is_running(), "shutdown left the node running");
1604        assert!(!devnet.config().data_dir.exists());
1605        drop(taken);
1606        Ok(())
1607    }
1608
1609    #[tokio::test]
1610    async fn a_cancelled_devnet_stops_pausing_at_once(
1611    ) -> std::result::Result<(), Box<dyn std::error::Error>> {
1612        let temp = tempfile::tempdir()?;
1613        let mut config = DevnetConfig::minimal();
1614        config.data_dir = temp.path().join("devnet");
1615        config.cleanup_data_dir = false;
1616        let devnet = Devnet::new(config).await?;
1617
1618        assert!(devnet.pause(Duration::ZERO).await.is_ok());
1619        devnet.cancellation_token().cancel();
1620        let started = Instant::now();
1621        let paused = devnet.pause(Duration::from_mins(1)).await;
1622        assert!(matches!(paused, Err(DevnetError::Startup(_))), "{paused:?}");
1623        assert!(started.elapsed() < Duration::from_secs(5));
1624        Ok(())
1625    }
1626}