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;
30
31#[cfg(all(feature = "webrtc-direct", feature = "test-utils"))]
32use crate::ant_protocol::{ChunkMessage, ChunkMessageBody, ChunkPutRequest, ChunkPutResponse};
33#[cfg(all(feature = "webrtc-direct", feature = "test-utils"))]
34use crate::browser::BrowserPublicFile;
35#[cfg(feature = "webrtc-direct")]
36use crate::browser::{browser_payment_network, BrowserBootstrapNode, BrowserPaymentNetwork};
37#[cfg(feature = "webrtc-direct")]
38use crate::config::WebRtcDirectConfig;
39#[cfg(all(feature = "webrtc-direct", feature = "test-utils"))]
40use bytes::Bytes;
41#[cfg(all(feature = "webrtc-direct", feature = "test-utils"))]
42use std::collections::HashMap;
43
44// =============================================================================
45// Devnet Constants
46// =============================================================================
47
48/// Minimum port for random devnet allocation.
49pub const DEVNET_PORT_RANGE_MIN: u16 = 20_000;
50
51/// Maximum port for random devnet allocation.
52pub const DEVNET_PORT_RANGE_MAX: u16 = 60_000;
53
54// =============================================================================
55// Default Timing Constants
56// =============================================================================
57
58/// Default delay between spawning nodes (milliseconds).
59const DEFAULT_SPAWN_DELAY_MS: u64 = 200;
60
61/// Default timeout for network stabilization (seconds).
62const DEFAULT_STABILIZATION_TIMEOUT_SECS: u64 = 120;
63
64/// Default timeout for single node startup (seconds).
65const DEFAULT_NODE_STARTUP_TIMEOUT_SECS: u64 = 30;
66
67/// Stabilization timeout for minimal network (seconds).
68const MINIMAL_STABILIZATION_TIMEOUT_SECS: u64 = 30;
69
70/// Stabilization timeout for small network (seconds).
71const SMALL_STABILIZATION_TIMEOUT_SECS: u64 = 60;
72
73/// Polling interval when waiting for individual nodes to become ready (milliseconds).
74const NODE_READY_POLL_INTERVAL_MS: u64 = 100;
75
76/// Polling interval when waiting for network stabilization (seconds).
77const STABILIZATION_POLL_INTERVAL_SECS: u64 = 1;
78
79/// Maximum minimum connections required per node during stabilization.
80const STABILIZATION_MIN_CONNECTIONS_CAP: usize = 3;
81
82/// Health monitor check interval (seconds).
83const HEALTH_CHECK_INTERVAL_SECS: u64 = 5;
84
85// =============================================================================
86// AntProtocol Devnet Configuration
87// =============================================================================
88
89/// Payment cache capacity for devnet nodes.
90const DEVNET_PAYMENT_CACHE_CAPACITY: usize = 1000;
91
92/// Devnet rewards address (20 bytes, all 0x01).
93const DEVNET_REWARDS_ADDRESS: [u8; 20] = [0x01; 20];
94
95/// Initial records for quoting metrics (devnet value).
96const DEVNET_INITIAL_RECORDS: usize = 1000;
97
98async fn handle_chunk_message(
99    protocol: Arc<AntProtocol>,
100    p2p: Arc<P2PNode>,
101    source: PeerId,
102    data: Vec<u8>,
103    node_index: usize,
104    received_at: Instant,
105) {
106    let handled = protocol
107        .try_handle_request_with_context(
108            &data,
109            Some(ChunkRequestContext::new(
110                source.to_string(),
111                received_at.into(),
112                Duration::ZERO,
113            )),
114        )
115        .await;
116    let telemetry = handled.get_telemetry;
117    match handled.response {
118        Ok(Some(response)) => {
119            let send_started = Instant::now();
120            let send_result = p2p
121                .send_message(&source, CHUNK_PROTOCOL_ID, response.to_vec(), &[])
122                .await;
123            if let Some(telemetry) = telemetry {
124                telemetry.finish_send(send_started.elapsed(), send_result.is_ok());
125            }
126            if let Err(e) = send_result {
127                warn!("Node {node_index} failed to send response to {source}: {e}");
128            }
129        }
130        Ok(None) => {
131            if let Some(telemetry) = telemetry {
132                telemetry.finish_without_send("no_response");
133            }
134        }
135        Err(e) => {
136            if let Some(telemetry) = telemetry {
137                telemetry.finish_without_send("encode_error");
138            }
139            warn!("Node {node_index} protocol handler error: {e}");
140        }
141    }
142}
143
144// =============================================================================
145// Default Node Counts
146// =============================================================================
147
148/// Default number of nodes in a full devnet.
149pub const DEFAULT_NODE_COUNT: usize = 25;
150
151/// Default number of bootstrap nodes.
152pub const DEFAULT_BOOTSTRAP_COUNT: usize = 3;
153
154/// Number of nodes in a minimal devnet.
155pub const MINIMAL_NODE_COUNT: usize = 5;
156
157/// Number of bootstrap nodes in a minimal network.
158pub const MINIMAL_BOOTSTRAP_COUNT: usize = 2;
159
160/// Number of nodes in a small devnet.
161pub const SMALL_NODE_COUNT: usize = 10;
162
163/// Error type for devnet operations.
164#[derive(Debug, thiserror::Error)]
165pub enum DevnetError {
166    /// Configuration error
167    #[error("Configuration error: {0}")]
168    Config(String),
169
170    /// Node startup error
171    #[error("Node startup error: {0}")]
172    Startup(String),
173
174    /// Network stabilization error
175    #[error("Network stabilization error: {0}")]
176    Stabilization(String),
177
178    /// IO error
179    #[error("IO error: {0}")]
180    Io(#[from] std::io::Error),
181
182    /// Core error
183    #[error("Core error: {0}")]
184    Core(String),
185}
186
187/// Result type for devnet operations.
188pub type Result<T> = std::result::Result<T, DevnetError>;
189
190/// Configuration for the devnet.
191///
192/// Each configuration is automatically isolated with unique ports and
193/// data directories to prevent collisions when running multiple devnets.
194#[derive(Debug, Clone)]
195pub struct DevnetConfig {
196    /// Number of nodes to spawn (default: 25).
197    pub node_count: usize,
198
199    /// Base port for node allocation (0 = auto).
200    pub base_port: u16,
201
202    /// Number of bootstrap nodes (first N nodes, default: 3).
203    pub bootstrap_count: usize,
204
205    /// Root directory for devnet data.
206    pub data_dir: PathBuf,
207
208    /// Delay between node spawns (default: 200ms).
209    pub spawn_delay: Duration,
210
211    /// Timeout for network stabilization (default: 120s).
212    pub stabilization_timeout: Duration,
213
214    /// Timeout for single node startup (default: 30s).
215    pub node_startup_timeout: Duration,
216
217    /// Enable verbose logging for devnet nodes.
218    pub enable_node_logging: bool,
219
220    /// Whether to remove the data directory on shutdown.
221    pub cleanup_data_dir: bool,
222
223    /// Optional EVM network for payment verification.
224    /// When `Some`, nodes will use this network (e.g. Anvil testnet) for
225    /// on-chain verification. Defaults to Arbitrum One when `None`.
226    pub evm_network: Option<EvmNetwork>,
227
228    /// Optional IPv4 to advertise to peers/clients (LAN devnet). When `Some`,
229    /// nodes bind 0.0.0.0 and advertise this IP instead of 127.0.0.1.
230    pub advertise_ip: Option<Ipv4Addr>,
231
232    /// Run one direct-browser WebRTC Direct listener per devnet node.
233    pub webrtc_direct: bool,
234
235    /// First UDP port in the WebRTC Direct node range (0 = allocate).
236    pub webrtc_direct_base_port: u16,
237}
238
239impl Default for DevnetConfig {
240    fn default() -> Self {
241        let mut rng = rand::thread_rng();
242
243        #[allow(clippy::cast_possible_truncation)] // DEFAULT_NODE_COUNT is 25, always fits u16
244        let max_base_port = DEVNET_PORT_RANGE_MAX.saturating_sub(DEFAULT_NODE_COUNT as u16);
245        let base_port = rng.gen_range(DEVNET_PORT_RANGE_MIN..max_base_port);
246
247        Self {
248            node_count: DEFAULT_NODE_COUNT,
249            base_port,
250            bootstrap_count: DEFAULT_BOOTSTRAP_COUNT,
251            data_dir: default_root_dir(),
252            spawn_delay: Duration::from_millis(DEFAULT_SPAWN_DELAY_MS),
253            stabilization_timeout: Duration::from_secs(DEFAULT_STABILIZATION_TIMEOUT_SECS),
254            node_startup_timeout: Duration::from_secs(DEFAULT_NODE_STARTUP_TIMEOUT_SECS),
255            enable_node_logging: false,
256            cleanup_data_dir: true,
257            evm_network: None,
258            advertise_ip: None,
259            webrtc_direct: false,
260            webrtc_direct_base_port: 0,
261        }
262    }
263}
264
265impl DevnetConfig {
266    /// Minimal devnet preset (5 nodes).
267    #[must_use]
268    pub fn minimal() -> Self {
269        Self {
270            node_count: MINIMAL_NODE_COUNT,
271            bootstrap_count: MINIMAL_BOOTSTRAP_COUNT,
272            stabilization_timeout: Duration::from_secs(MINIMAL_STABILIZATION_TIMEOUT_SECS),
273            ..Self::default()
274        }
275    }
276
277    /// Small devnet preset (10 nodes).
278    #[must_use]
279    pub fn small() -> Self {
280        Self {
281            node_count: SMALL_NODE_COUNT,
282            bootstrap_count: MINIMAL_BOOTSTRAP_COUNT,
283            stabilization_timeout: Duration::from_secs(SMALL_STABILIZATION_TIMEOUT_SECS),
284            ..Self::default()
285        }
286    }
287}
288
289// The manifest types are shared with ant-client (CLI reads them, devnet
290// writes them), so they live in ant-protocol. Re-exported here for
291// backwards compatibility.
292pub use ant_protocol::devnet_manifest::{DevnetEvmInfo, DevnetManifest};
293
294/// Network state for devnet startup lifecycle.
295#[derive(Debug, Clone)]
296pub enum NetworkState {
297    /// Not started.
298    Uninitialized,
299    /// Bootstrapping nodes are starting.
300    BootstrappingPhase,
301    /// Regular nodes are starting.
302    NodeSpawningPhase,
303    /// Waiting for stabilization.
304    Stabilizing,
305    /// Network is ready.
306    Ready,
307    /// Shutting down.
308    ShuttingDown,
309    /// Stopped.
310    Stopped,
311}
312
313/// Node state for devnet nodes.
314#[derive(Debug, Clone)]
315pub enum NodeState {
316    /// Not started yet.
317    Pending,
318    /// Starting up.
319    Starting,
320    /// Running.
321    Running,
322    /// Connected to peers.
323    Connected,
324    /// Stopped.
325    Stopped,
326    /// Failed to start.
327    Failed(String),
328}
329
330/// A single devnet node instance.
331#[allow(dead_code)]
332pub struct DevnetNode {
333    index: usize,
334    label: String,
335    peer_id: PeerId,
336    port: u16,
337    data_dir: PathBuf,
338    p2p_node: Option<Arc<P2PNode>>,
339    ant_protocol: Option<Arc<AntProtocol>>,
340    is_bootstrap: bool,
341    state: Arc<RwLock<NodeState>>,
342    bootstrap_addrs: Vec<MultiAddr>,
343    protocol_task: Option<JoinHandle<()>>,
344    #[cfg(feature = "webrtc-direct")]
345    webrtc_direct_task: Option<JoinHandle<()>>,
346    #[cfg(feature = "webrtc-direct")]
347    webrtc_diagnostics: Option<crate::web_rtc::WebRtcServerDiagnostics>,
348    #[cfg(feature = "webrtc-direct")]
349    browser_endpoint: Option<crate::browser::BrowserEndpoint>,
350}
351
352impl DevnetNode {
353    /// Get the node's peer count.
354    pub async fn peer_count(&self) -> usize {
355        if let Some(ref node) = self.p2p_node {
356            node.peer_count().await
357        } else {
358            0
359        }
360    }
361}
362
363/// A local devnet composed of multiple nodes.
364pub struct Devnet {
365    config: DevnetConfig,
366    nodes: Vec<DevnetNode>,
367    shutdown: CancellationToken,
368    state: Arc<RwLock<NetworkState>>,
369    health_monitor: Option<JoinHandle<()>>,
370    #[cfg(feature = "webrtc-direct")]
371    browser_endpoint_catalog: Arc<crate::web_rtc::BrowserEndpointCatalog>,
372}
373
374impl Devnet {
375    /// Create a new devnet with the given configuration.
376    ///
377    /// # Errors
378    ///
379    /// Returns `DevnetError::Config` if the configuration is invalid (e.g. bootstrap
380    /// count exceeds node count or port range overflow).
381    /// Returns `DevnetError::Io` if the data directory cannot be created.
382    #[allow(clippy::too_many_lines)]
383    pub async fn new(mut config: DevnetConfig) -> Result<Self> {
384        if config.bootstrap_count >= config.node_count {
385            return Err(DevnetError::Config(
386                "Bootstrap count must be less than node count".to_string(),
387            ));
388        }
389
390        if config.bootstrap_count == 0 {
391            return Err(DevnetError::Config(
392                "At least one bootstrap node is required".to_string(),
393            ));
394        }
395
396        let node_count = config.node_count;
397        let node_count_u16 = u16::try_from(node_count).map_err(|_| {
398            DevnetError::Config(format!("Node count {node_count} exceeds u16::MAX"))
399        })?;
400
401        if config.base_port == 0 {
402            let mut rng = rand::thread_rng();
403            let max_base_port = DEVNET_PORT_RANGE_MAX.saturating_sub(node_count_u16);
404            config.base_port = rng.gen_range(DEVNET_PORT_RANGE_MIN..max_base_port);
405        }
406
407        let base_port = config.base_port;
408        let max_port = base_port
409            .checked_add(node_count_u16)
410            .ok_or_else(|| {
411                DevnetError::Config(format!(
412                    "Port range overflow: base_port {base_port} + node_count {node_count} exceeds u16::MAX"
413                ))
414            })?;
415        if max_port > DEVNET_PORT_RANGE_MAX {
416            return Err(DevnetError::Config(format!(
417                "Port range overflow: max port {max_port} exceeds DEVNET_PORT_RANGE_MAX {DEVNET_PORT_RANGE_MAX}"
418            )));
419        }
420
421        #[cfg(not(feature = "webrtc-direct"))]
422        if config.webrtc_direct {
423            return Err(DevnetError::Config(
424                "WebRtcDirect devnet support requires the 'webrtc-direct' feature".to_string(),
425            ));
426        }
427
428        #[cfg(feature = "webrtc-direct")]
429        if config.webrtc_direct {
430            if config.webrtc_direct_base_port == 0 {
431                let adjacent = max_port;
432                let adjacent_end = adjacent.checked_add(node_count_u16);
433                config.webrtc_direct_base_port = if adjacent_end
434                    .is_some_and(|end| end <= DEVNET_PORT_RANGE_MAX)
435                {
436                    adjacent
437                } else if let Some(before) = base_port
438                    .checked_sub(node_count_u16)
439                    .filter(|before| *before >= DEVNET_PORT_RANGE_MIN)
440                {
441                    before
442                } else {
443                    let mut rng = rand::thread_rng();
444                    let max_base = DEVNET_PORT_RANGE_MAX.saturating_sub(node_count_u16);
445                    (0..128)
446                        .map(|_| rng.gen_range(DEVNET_PORT_RANGE_MIN..max_base))
447                        .find(|candidate| {
448                            let end = candidate.saturating_add(node_count_u16);
449                            end <= base_port || *candidate >= max_port
450                        })
451                        .ok_or_else(|| {
452                            DevnetError::Config(
453                                "Could not allocate a disjoint WebRtcDirect port range".to_string(),
454                            )
455                        })?
456                };
457            }
458
459            let webrtc_direct_end = config
460                .webrtc_direct_base_port
461                .checked_add(node_count_u16)
462                .ok_or_else(|| {
463                    DevnetError::Config("WebRtcDirect port range overflow".to_string())
464                })?;
465            if config.webrtc_direct_base_port < DEVNET_PORT_RANGE_MIN
466                || webrtc_direct_end > DEVNET_PORT_RANGE_MAX
467            {
468                return Err(DevnetError::Config(format!(
469                    "WebRtcDirect ports must remain in the local test range {DEVNET_PORT_RANGE_MIN}..{DEVNET_PORT_RANGE_MAX}"
470                )));
471            }
472            if base_port < webrtc_direct_end && config.webrtc_direct_base_port < max_port {
473                return Err(DevnetError::Config(
474                    "Native and WebRtcDirect devnet port ranges overlap".to_string(),
475                ));
476            }
477        }
478
479        tokio::fs::create_dir_all(&config.data_dir).await?;
480
481        Ok(Self {
482            config,
483            nodes: Vec::new(),
484            shutdown: CancellationToken::new(),
485            state: Arc::new(RwLock::new(NetworkState::Uninitialized)),
486            health_monitor: None,
487            #[cfg(feature = "webrtc-direct")]
488            browser_endpoint_catalog: Arc::new(crate::web_rtc::BrowserEndpointCatalog::default()),
489        })
490    }
491
492    /// Start the devnet.
493    ///
494    /// # Errors
495    ///
496    /// Returns `DevnetError::Startup` if any node fails to start, or
497    /// `DevnetError::Stabilization` if the network does not stabilize within the timeout.
498    pub async fn start(&mut self) -> Result<()> {
499        info!(
500            "Starting devnet with {} nodes ({} bootstrap)",
501            self.config.node_count, self.config.bootstrap_count
502        );
503
504        *self.state.write().await = NetworkState::BootstrappingPhase;
505        self.start_bootstrap_nodes().await?;
506
507        *self.state.write().await = NetworkState::NodeSpawningPhase;
508        self.start_regular_nodes().await?;
509
510        *self.state.write().await = NetworkState::Stabilizing;
511        self.wait_for_stabilization().await?;
512
513        self.start_health_monitor();
514
515        *self.state.write().await = NetworkState::Ready;
516        info!("Devnet is ready");
517        Ok(())
518    }
519
520    /// Shutdown the devnet.
521    ///
522    /// # Errors
523    ///
524    /// Returns `DevnetError::Io` if the data directory cleanup fails.
525    pub async fn shutdown(&mut self) -> Result<()> {
526        info!("Shutting down devnet");
527        *self.state.write().await = NetworkState::ShuttingDown;
528
529        self.shutdown.cancel();
530
531        if let Some(handle) = self.health_monitor.take() {
532            handle.abort();
533        }
534
535        let mut shutdown_futures = Vec::with_capacity(self.nodes.len());
536        for node in self.nodes.iter_mut().rev() {
537            debug!("Stopping node {}", node.index);
538            if let Some(handle) = node.protocol_task.take() {
539                handle.abort();
540            }
541            #[cfg(feature = "webrtc-direct")]
542            if let Some(handle) = node.webrtc_direct_task.take() {
543                if let Err(error) = handle.await {
544                    warn!(
545                        "Error stopping node {} WebRtcDirect listener: {error}",
546                        node.index
547                    );
548                }
549            }
550
551            let node_index = node.index;
552            let node_state = Arc::clone(&node.state);
553            let p2p_node = node.p2p_node.take();
554
555            shutdown_futures.push(async move {
556                if let Some(p2p) = p2p_node {
557                    if let Err(e) = p2p.shutdown().await {
558                        warn!("Error shutting down node {node_index}: {e}");
559                    }
560                }
561                *node_state.write().await = NodeState::Stopped;
562            });
563        }
564        futures::future::join_all(shutdown_futures).await;
565
566        if self.config.cleanup_data_dir {
567            if let Err(e) = tokio::fs::remove_dir_all(&self.config.data_dir).await {
568                warn!("Failed to cleanup devnet data directory: {e}");
569            }
570        }
571
572        *self.state.write().await = NetworkState::Stopped;
573        info!("Devnet shutdown complete");
574        Ok(())
575    }
576
577    /// Get devnet configuration.
578    #[must_use]
579    pub fn config(&self) -> &DevnetConfig {
580        &self.config
581    }
582
583    /// Get bootstrap addresses.
584    #[must_use]
585    pub fn bootstrap_addrs(&self) -> Vec<MultiAddr> {
586        self.nodes
587            .iter()
588            .take(self.config.bootstrap_count)
589            .map(|n| {
590                MultiAddr::quic(SocketAddr::from((
591                    self.config.advertise_ip.unwrap_or(Ipv4Addr::LOCALHOST),
592                    n.port,
593                )))
594            })
595            .collect()
596    }
597
598    /// Snapshot every browser listener, including counters retained after shutdown.
599    #[cfg(feature = "webrtc-direct")]
600    #[must_use]
601    pub fn browser_listener_diagnostics(&self) -> Vec<crate::web_rtc::WebRtcServerSnapshot> {
602        self.nodes
603            .iter()
604            .filter_map(|node| {
605                node.webrtc_diagnostics
606                    .as_ref()
607                    .map(crate::web_rtc::WebRtcServerDiagnostics::snapshot)
608            })
609            .collect()
610    }
611
612    /// Test-only handles for exercising browser admission during stalled storage.
613    #[cfg(all(feature = "webrtc-direct", feature = "test-utils"))]
614    #[must_use]
615    pub fn test_browser_node(
616        &self,
617        index: usize,
618    ) -> Option<(Arc<AntProtocol>, crate::web_rtc::WebRtcServerDiagnostics)> {
619        let node = self.nodes.get(index)?;
620        Some((
621            Arc::clone(node.ant_protocol.as_ref()?),
622            node.webrtc_diagnostics.clone()?,
623        ))
624    }
625
626    /// Get every direct browser endpoint in this devnet.
627    #[cfg(feature = "webrtc-direct")]
628    #[must_use]
629    pub fn browser_endpoints(&self) -> Vec<BrowserBootstrapNode> {
630        self.nodes
631            .iter()
632            .filter_map(|node| {
633                node.browser_endpoint
634                    .clone()
635                    .map(|endpoint| BrowserBootstrapNode { endpoint })
636            })
637            .collect()
638    }
639
640    /// Publish a complete self-encrypted file to the browser-enabled devnet.
641    ///
642    /// The file is split using the same `self_encryption` crate as `ant-client`.
643    /// Every encrypted data chunk and the public `MessagePack` `DataMap` are then
644    /// submitted through each node's ordinary chunk PUT handler. Address
645    /// verification, DHT responsibility, payment-cache admission, and LMDB
646    /// integrity checks therefore remain active.
647    ///
648    /// # Errors
649    ///
650    /// Returns an error when WebRTC Direct is disabled, self-encryption fails,
651    /// a generated chunk is too large, no node admits a required record, or
652    /// protocol serialization fails.
653    #[cfg(all(feature = "webrtc-direct", feature = "test-utils"))]
654    pub async fn publish_public_file(
655        &self,
656        name: String,
657        content_type: String,
658        content: &[u8],
659    ) -> Result<BrowserPublicFile> {
660        if !self.config.webrtc_direct {
661            return Err(DevnetError::Config(
662                "Cannot publish a browser file when WebRtcDirect is disabled".to_string(),
663            ));
664        }
665        if content.len() < self_encryption::MIN_ENCRYPTABLE_BYTES {
666            return Err(DevnetError::Config(format!(
667                "Public file is {} bytes; self-encryption requires at least {} bytes",
668                content.len(),
669                self_encryption::MIN_ENCRYPTABLE_BYTES
670            )));
671        }
672
673        let (published_data_map, encrypted_chunks) =
674            self_encryption::encrypt(Bytes::copy_from_slice(content)).map_err(|error| {
675                DevnetError::Core(format!("Failed to self-encrypt browser file: {error}"))
676            })?;
677        let mut records = HashMap::<[u8; 32], Bytes>::new();
678        for chunk in encrypted_chunks {
679            if chunk.content.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
680                return Err(DevnetError::Core(format!(
681                    "Self-encryption produced a {}-byte chunk; node maximum is {}",
682                    chunk.content.len(),
683                    crate::ant_protocol::MAX_CHUNK_SIZE
684                )));
685            }
686            let address = crate::client::compute_address(&chunk.content);
687            records.entry(address).or_insert(chunk.content);
688        }
689
690        let mut get_local_chunk = |address: self_encryption::XorName| {
691            records.get(&address.0).cloned().ok_or_else(|| {
692                self_encryption::Error::Generic(format!(
693                    "Self-encryption output omitted chunk {}",
694                    hex::encode(address.0)
695                ))
696            })
697        };
698        let root_data_map =
699            self_encryption::get_root_data_map(published_data_map.clone(), &mut get_local_chunk)
700                .map_err(|error| {
701                    DevnetError::Core(format!("Failed to resolve browser file DataMap: {error}"))
702                })?;
703        let serialized_data_map = rmp_serde::to_vec(&published_data_map).map_err(|error| {
704            DevnetError::Core(format!("Failed to serialize browser file DataMap: {error}"))
705        })?;
706        let data_map_size = serialized_data_map.len();
707        let data_map_address = crate::client::compute_address(&serialized_data_map);
708        records.insert(data_map_address, Bytes::from(serialized_data_map));
709
710        let record_count = records.len();
711        let mut replicas = usize::MAX;
712        for (address, bytes) in &records {
713            replicas = replicas.min(self.publish_browser_record(*address, bytes).await?);
714        }
715
716        let chunks = root_data_map
717            .infos()
718            .iter()
719            .map(|info| crate::browser::BrowserChunkInfo {
720                index: info.index,
721                dst_hash: hex::encode(info.dst_hash.0),
722                src_hash: hex::encode(info.src_hash.0),
723                src_size: info.src_size,
724            })
725            .collect();
726        let published = BrowserPublicFile {
727            name,
728            address: hex::encode(data_map_address),
729            size: content.len(),
730            content_type,
731            blake3: hex::encode(crate::client::compute_address(content)),
732            data_map_size,
733            chunks,
734            replicas,
735        };
736        info!(
737            "Published browser devnet file '{}' at {} as {record_count} record(s), each on at least {} node(s)",
738            published.name, published.address, published.replicas
739        );
740        Ok(published)
741    }
742
743    /// Public EVM chain and contracts advertised to direct browser clients.
744    ///
745    /// # Errors
746    ///
747    /// Returns `DevnetError::Config` if a custom RPC cannot report its chain ID.
748    #[cfg(feature = "webrtc-direct")]
749    pub async fn browser_payment_network(&self) -> Result<BrowserPaymentNetwork> {
750        let network = self
751            .config
752            .evm_network
753            .as_ref()
754            .unwrap_or(&EvmNetwork::ArbitrumOne);
755        browser_payment_network(network)
756            .await
757            .map_err(|error| DevnetError::Config(error.to_string()))
758    }
759
760    #[cfg(all(feature = "webrtc-direct", feature = "test-utils"))]
761    async fn publish_browser_record(&self, address: [u8; 32], content: &Bytes) -> Result<usize> {
762        let mut replicas = 0usize;
763        let mut failures = Vec::new();
764
765        for node in &self.nodes {
766            let Some(protocol) = node.ant_protocol.as_ref() else {
767                failures.push(format!("node {} has no protocol handler", node.index));
768                continue;
769            };
770            protocol
771                .payment_verifier_arc()
772                .cache_insert_browser_devnet_seed(address);
773
774            let request = ChunkMessage {
775                request_id: u64::try_from(node.index).unwrap_or(u64::MAX),
776                body: ChunkMessageBody::PutRequest(ChunkPutRequest::new(address, content.clone())),
777            };
778            let request_bytes = request.encode().map_err(|error| {
779                DevnetError::Core(format!("Failed to encode public-file PUT: {error}"))
780            })?;
781            let response_bytes = protocol
782                .try_handle_request(&request_bytes)
783                .await
784                .map_err(|error| {
785                    DevnetError::Core(format!(
786                        "Node {} public-file PUT failed: {error}",
787                        node.index
788                    ))
789                })?
790                .ok_or_else(|| {
791                    DevnetError::Core(format!(
792                        "Node {} returned no public-file PUT response",
793                        node.index
794                    ))
795                })?;
796            let response = ChunkMessage::decode(&response_bytes).map_err(|error| {
797                DevnetError::Core(format!(
798                    "Failed to decode node {} public-file response: {error}",
799                    node.index
800                ))
801            })?;
802            match response.body {
803                ChunkMessageBody::PutResponse(
804                    ChunkPutResponse::Success { .. } | ChunkPutResponse::AlreadyExists { .. },
805                ) => {
806                    replicas += 1;
807                }
808                ChunkMessageBody::PutResponse(other) => {
809                    failures.push(format!("node {}: {other:?}", node.index));
810                }
811                other => failures.push(format!(
812                    "node {} returned unexpected response {other:?}",
813                    node.index
814                )),
815            }
816        }
817
818        if replicas == 0 {
819            return Err(DevnetError::Startup(format!(
820                "No devnet node admitted browser record {}: {}",
821                hex::encode(address),
822                failures.join("; ")
823            )));
824        }
825        if !failures.is_empty() {
826            debug!(
827                "Browser record was admitted by {replicas} nodes; {} non-responsible/failed nodes: {}",
828                failures.len(),
829                failures.join("; ")
830            );
831        }
832        Ok(replicas)
833    }
834
835    async fn start_bootstrap_nodes(&mut self) -> Result<()> {
836        info!("Starting {} bootstrap nodes", self.config.bootstrap_count);
837
838        for i in 0..self.config.bootstrap_count {
839            let node = self.create_node(i, true, vec![]).await?;
840            self.start_node(node).await?;
841            tokio::time::sleep(self.config.spawn_delay).await;
842        }
843
844        self.wait_for_nodes_ready(0..self.config.bootstrap_count)
845            .await?;
846
847        info!("All bootstrap nodes are ready");
848        Ok(())
849    }
850
851    async fn start_regular_nodes(&mut self) -> Result<()> {
852        let regular_count = self.config.node_count - self.config.bootstrap_count;
853        info!("Starting {} regular nodes", regular_count);
854
855        let bootstrap_addrs: Vec<MultiAddr> = self
856            .nodes
857            .get(0..self.config.bootstrap_count)
858            .ok_or_else(|| {
859                DevnetError::Config(format!(
860                    "Bootstrap count {} exceeds nodes length {}",
861                    self.config.bootstrap_count,
862                    self.nodes.len()
863                ))
864            })?
865            .iter()
866            .map(|n| {
867                MultiAddr::quic(SocketAddr::from((
868                    self.config.advertise_ip.unwrap_or(Ipv4Addr::LOCALHOST),
869                    n.port,
870                )))
871            })
872            .collect();
873
874        for i in self.config.bootstrap_count..self.config.node_count {
875            let node = self.create_node(i, false, bootstrap_addrs.clone()).await?;
876            self.start_node(node).await?;
877            tokio::time::sleep(self.config.spawn_delay).await;
878        }
879
880        info!("All regular nodes started");
881        Ok(())
882    }
883
884    async fn create_node(
885        &self,
886        index: usize,
887        is_bootstrap: bool,
888        bootstrap_addrs: Vec<MultiAddr>,
889    ) -> Result<DevnetNode> {
890        let index_u16 = u16::try_from(index)
891            .map_err(|_| DevnetError::Config(format!("Node index {index} exceeds u16::MAX")))?;
892        let port = self.config.base_port + index_u16;
893
894        // Generate identity first so we can use peer_id as the directory name
895        let identity = NodeIdentity::generate()
896            .map_err(|e| DevnetError::Core(format!("Failed to generate node identity: {e}")))?;
897        let peer_id = *identity.peer_id();
898        let label = format!("devnet_node_{index}");
899        let data_dir = self
900            .config
901            .data_dir
902            .join(NODES_SUBDIR)
903            .join(peer_id.to_hex());
904
905        tokio::fs::create_dir_all(&data_dir).await?;
906
907        identity
908            .save_to_file(&data_dir.join(NODE_IDENTITY_FILENAME))
909            .await
910            .map_err(|e| DevnetError::Core(format!("Failed to save node identity: {e}")))?;
911
912        let ant_protocol = Self::create_ant_protocol(&data_dir, &identity, &self.config).await?;
913
914        Ok(DevnetNode {
915            index,
916            label,
917            peer_id,
918            port,
919            data_dir,
920            p2p_node: None,
921            ant_protocol: Some(Arc::new(ant_protocol)),
922            is_bootstrap,
923            state: Arc::new(RwLock::new(NodeState::Pending)),
924            bootstrap_addrs,
925            protocol_task: None,
926            #[cfg(feature = "webrtc-direct")]
927            webrtc_direct_task: None,
928            #[cfg(feature = "webrtc-direct")]
929            webrtc_diagnostics: None,
930            #[cfg(feature = "webrtc-direct")]
931            browser_endpoint: None,
932        })
933    }
934
935    async fn create_ant_protocol(
936        data_dir: &std::path::Path,
937        identity: &NodeIdentity,
938        config: &DevnetConfig,
939    ) -> Result<AntProtocol> {
940        let storage_config = ChunkStoreConfig {
941            root_dir: data_dir.to_path_buf(),
942            verify_on_read: true,
943            ..ChunkStoreConfig::default()
944        };
945        let storage = ChunkStore::new(storage_config)
946            .await
947            .map_err(|e| DevnetError::Core(format!("Failed to create LMDB storage: {e}")))?;
948
949        let evm_config = EvmVerifierConfig {
950            network: config
951                .evm_network
952                .clone()
953                .unwrap_or(EvmNetwork::ArbitrumOne),
954        };
955
956        let rewards_address = RewardsAddress::new(DEVNET_REWARDS_ADDRESS);
957        let replication_config = ReplicationConfig::default();
958        let payment_config = PaymentVerifierConfig {
959            evm: evm_config,
960            cache_capacity: DEVNET_PAYMENT_CACHE_CAPACITY,
961            close_group_size: replication_config.close_group_size,
962            local_rewards_address: rewards_address,
963            price_floor: PriceFloorConfig::default(),
964        };
965        let payment_verifier = PaymentVerifier::new(payment_config);
966        let metrics_tracker = QuotingMetricsTracker::new(DEVNET_INITIAL_RECORDS);
967        let mut quote_generator = QuoteGenerator::new(rewards_address, metrics_tracker);
968
969        // Wire ML-DSA-65 signing from the devnet node's identity
970        crate::payment::wire_ml_dsa_signer(&mut quote_generator, identity)
971            .map_err(|e| DevnetError::Startup(format!("Failed to wire ML-DSA-65 signer: {e}")))?;
972
973        let storage = Arc::new(storage);
974        let payment_verifier = Arc::new(payment_verifier);
975
976        // Same pointer wiring as a production node, so a devnet exercises the
977        // real path rather than a node that silently refuses every pointer.
978        let pointer_store = crate::pointer::PointerStore::new(storage.root_dir())
979            .await
980            .map_err(|e| DevnetError::Startup(format!("Failed to open pointer store: {e}")))?;
981        let pointers = crate::pointer::PointerService::new(pointer_store)
982            .with_chunk_store(Arc::clone(&storage))
983            .with_payments(Arc::clone(&payment_verifier));
984
985        Ok(
986            AntProtocol::new(storage, payment_verifier, Arc::new(quote_generator))
987                .with_pointer_service(pointers),
988        )
989    }
990
991    #[allow(clippy::too_many_lines)]
992    async fn start_node(&mut self, mut node: DevnetNode) -> Result<()> {
993        debug!("Starting node {} on port {}", node.index, node.port);
994        *node.state.write().await = NodeState::Starting;
995
996        let mut core_config = CoreNodeConfig::builder()
997            .port(node.port)
998            .local(self.config.advertise_ip.is_none())
999            .max_message_size(crate::ant_protocol::MAX_WIRE_MESSAGE_SIZE)
1000            .build()
1001            .map_err(|e| DevnetError::Core(format!("Failed to create core config: {e}")))?;
1002
1003        // Load the node identity for app-level message signing.
1004        let identity = NodeIdentity::load_from_file(
1005            &node.data_dir.join(crate::config::NODE_IDENTITY_FILENAME),
1006        )
1007        .await
1008        .map_err(|e| DevnetError::Core(format!("Failed to load node identity: {e}")))?;
1009
1010        core_config.node_identity = Some(Arc::new(identity));
1011        core_config
1012            .bootstrap_peers
1013            .clone_from(&node.bootstrap_addrs);
1014        core_config.diversity_config = Some(IPDiversityConfig::permissive());
1015
1016        let index = node.index;
1017        let p2p_node = P2PNode::new(core_config)
1018            .await
1019            .map_err(|e| DevnetError::Startup(format!("Failed to create node {index}: {e}")))?;
1020
1021        p2p_node
1022            .start()
1023            .await
1024            .map_err(|e| DevnetError::Startup(format!("Failed to start node {index}: {e}")))?;
1025
1026        node.p2p_node = Some(Arc::new(p2p_node));
1027        *node.state.write().await = NodeState::Running;
1028
1029        #[cfg(feature = "webrtc-direct")]
1030        if self.config.webrtc_direct {
1031            let index_u16 = u16::try_from(node.index).map_err(|_| {
1032                DevnetError::Config(format!("Node index {} exceeds u16::MAX", node.index))
1033            })?;
1034            let port = self
1035                .config
1036                .webrtc_direct_base_port
1037                .checked_add(index_u16)
1038                .ok_or_else(|| {
1039                    DevnetError::Config(format!(
1040                        "WebRtcDirect port overflow for node {}",
1041                        node.index
1042                    ))
1043                })?;
1044            let advertised_ip = self.config.advertise_ip.unwrap_or(Ipv4Addr::LOCALHOST);
1045            let bind_ip = self
1046                .config
1047                .advertise_ip
1048                .map_or(Ipv4Addr::LOCALHOST, |_| Ipv4Addr::UNSPECIFIED);
1049            let webrtc_direct_config = WebRtcDirectConfig {
1050                enabled: true,
1051                bind: SocketAddr::from((bind_ip, port)),
1052                advertised_addr: Some(SocketAddr::from((advertised_ip, port))),
1053                ..WebRtcDirectConfig::default()
1054            };
1055
1056            let p2p = node.p2p_node.clone().ok_or_else(|| {
1057                DevnetError::Startup(format!(
1058                    "Node {} lost its P2P handle before WebRtcDirect startup",
1059                    node.index
1060                ))
1061            })?;
1062            let server = crate::web_rtc::spawn(
1063                &webrtc_direct_config,
1064                &node.data_dir,
1065                p2p,
1066                node.ant_protocol.clone(),
1067                self.config
1068                    .evm_network
1069                    .as_ref()
1070                    .unwrap_or(&EvmNetwork::ArbitrumOne),
1071                self.shutdown.clone(),
1072                Some(Arc::clone(&self.browser_endpoint_catalog)),
1073            )
1074            .await
1075            .map_err(|error| {
1076                DevnetError::Startup(format!(
1077                    "Failed to start node {} WebRtcDirect listener: {error}",
1078                    node.index
1079                ))
1080            })?;
1081            node.browser_endpoint = server.endpoint;
1082            node.webrtc_diagnostics = Some(server.diagnostics);
1083            node.webrtc_direct_task = Some(server.task);
1084        }
1085
1086        if let (Some(ref p2p), Some(ref protocol)) = (&node.p2p_node, &node.ant_protocol) {
1087            // Wire P2P into AntProtocol for payment-proof closeness checks.
1088            protocol.attach_p2p_node(Arc::clone(p2p));
1089
1090            let mut events = p2p.subscribe_events();
1091            let p2p_clone = Arc::clone(p2p);
1092            let protocol_clone = Arc::clone(protocol);
1093            let node_index = node.index;
1094            node.protocol_task = Some(tokio::spawn(async move {
1095                while let Ok(event) = events.recv().await {
1096                    if let P2PEvent::Message {
1097                        topic,
1098                        source: Some(source),
1099                        data,
1100                        ..
1101                    } = event
1102                    {
1103                        if topic == CHUNK_PROTOCOL_ID {
1104                            debug!(
1105                                "Node {node_index} received chunk protocol message from {source}"
1106                            );
1107                            let protocol = Arc::clone(&protocol_clone);
1108                            let p2p = Arc::clone(&p2p_clone);
1109                            let received_at = Instant::now();
1110                            tokio::spawn(handle_chunk_message(
1111                                protocol,
1112                                p2p,
1113                                source,
1114                                data,
1115                                node_index,
1116                                received_at,
1117                            ));
1118                        }
1119                    }
1120                }
1121            }));
1122        }
1123
1124        debug!("Node {} started successfully", node.index);
1125        self.nodes.push(node);
1126        Ok(())
1127    }
1128
1129    async fn wait_for_nodes_ready(&self, range: std::ops::Range<usize>) -> Result<()> {
1130        let deadline = Instant::now() + self.config.node_startup_timeout;
1131
1132        for i in range {
1133            while Instant::now() < deadline {
1134                let node = self.nodes.get(i).ok_or_else(|| {
1135                    DevnetError::Config(format!(
1136                        "Node index {i} out of bounds (len: {})",
1137                        self.nodes.len()
1138                    ))
1139                })?;
1140                let state = node.state.read().await.clone();
1141                match state {
1142                    NodeState::Running | NodeState::Connected => break,
1143                    NodeState::Failed(ref e) => {
1144                        return Err(DevnetError::Startup(format!("Node {i} failed: {e}")));
1145                    }
1146                    _ => {
1147                        tokio::time::sleep(Duration::from_millis(NODE_READY_POLL_INTERVAL_MS))
1148                            .await;
1149                    }
1150                }
1151            }
1152        }
1153        Ok(())
1154    }
1155
1156    async fn wait_for_stabilization(&self) -> Result<()> {
1157        let deadline = Instant::now() + self.config.stabilization_timeout;
1158        let min_connections = self
1159            .config
1160            .bootstrap_count
1161            .min(STABILIZATION_MIN_CONNECTIONS_CAP);
1162
1163        info!(
1164            "Waiting for devnet stabilization (min {} connections per node)",
1165            min_connections
1166        );
1167
1168        while Instant::now() < deadline {
1169            let mut all_connected = true;
1170            let mut total_connections = 0;
1171
1172            for node in &self.nodes {
1173                let peer_count = node.peer_count().await;
1174                total_connections += peer_count;
1175
1176                if peer_count < min_connections {
1177                    all_connected = false;
1178                }
1179            }
1180
1181            if all_connected {
1182                info!("Devnet stabilized: {} total connections", total_connections);
1183                return Ok(());
1184            }
1185
1186            debug!(
1187                "Waiting for stabilization: {} total connections",
1188                total_connections
1189            );
1190            tokio::time::sleep(Duration::from_secs(STABILIZATION_POLL_INTERVAL_SECS)).await;
1191        }
1192
1193        Err(DevnetError::Stabilization(
1194            "Devnet failed to stabilize within timeout".to_string(),
1195        ))
1196    }
1197
1198    fn start_health_monitor(&mut self) {
1199        let nodes: Vec<Arc<P2PNode>> = self
1200            .nodes
1201            .iter()
1202            .filter_map(|n| n.p2p_node.clone())
1203            .collect();
1204        let shutdown = self.shutdown.clone();
1205
1206        self.health_monitor = Some(tokio::spawn(async move {
1207            let check_interval = Duration::from_secs(HEALTH_CHECK_INTERVAL_SECS);
1208
1209            loop {
1210                tokio::select! {
1211                    () = shutdown.cancelled() => break,
1212                    () = tokio::time::sleep(check_interval) => {
1213                        for (i, node) in nodes.iter().enumerate() {
1214                            if !node.is_running() {
1215                                warn!("Node {} appears unhealthy", i);
1216                            }
1217                        }
1218                    }
1219                }
1220            }
1221        }));
1222    }
1223}
1224
1225impl Drop for Devnet {
1226    fn drop(&mut self) {
1227        self.shutdown.cancel();
1228        if let Some(handle) = self.health_monitor.take() {
1229            handle.abort();
1230        }
1231    }
1232}
1233
1234#[cfg(test)]
1235mod tests {
1236    use super::*;
1237
1238    /// Backward-compatibility contract: a default config advertises no LAN IP,
1239    /// so nodes bind loopback (`.local(advertise_ip.is_none())` → `.local(true)`)
1240    /// and stamp `127.0.0.1` into the manifest bootstrap addresses — exactly as
1241    /// before the `--host` flag existed.
1242    #[test]
1243    fn default_config_has_no_advertise_ip() {
1244        assert!(DevnetConfig::default().advertise_ip.is_none());
1245    }
1246}