Skip to main content

ant_node/
node.rs

1//! Node implementation - thin wrapper around saorsa-core's `P2PNode`.
2
3use crate::ant_protocol::{CHUNK_PROTOCOL_ID, GET_OR_CLOSER_AGENT_TOKEN};
4use crate::config::{
5    default_nodes_dir, default_root_dir, NetworkMode, NodeConfig, NODE_IDENTITY_FILENAME,
6};
7use crate::error::{Error, Result};
8use crate::event::{create_event_channel, NodeEvent, NodeEventsChannel, NodeEventsSender};
9use crate::logging::{debug, error, info, warn};
10use crate::payment::metrics::QuotingMetricsTracker;
11use crate::payment::wallet::parse_rewards_address;
12use crate::payment::{
13    EvmVerifierConfig, PaymentVerifier, PaymentVerifierConfig, PriceFloorConfig, QuoteGenerator,
14};
15use crate::replication::config::ReplicationConfig;
16use crate::replication::fresh::FreshWriteEvent;
17use crate::replication::ReplicationEngine;
18use crate::storage::legacy_artifacts;
19use crate::storage::traffic as storage_traffic;
20use crate::storage::MIB;
21use crate::storage::{AntProtocol, ChunkRequestContext, ChunkStore, ChunkStoreConfig};
22use crate::upgrade::{
23    upgrade_cache_dir, AutoApplyUpgrader, BinaryCache, ReleaseCache, UpgradeMonitor, UpgradeResult,
24};
25use rand::Rng;
26use saorsa_core::identity::NodeIdentity;
27use saorsa_core::{
28    IPDiversityConfig as CoreDiversityConfig, MultiAddr, NodeConfig as CoreNodeConfig, P2PEvent,
29    P2PNode,
30};
31use std::path::{Path, PathBuf};
32use std::sync::atomic::{AtomicI32, Ordering};
33use std::sync::Arc;
34use std::time::Instant;
35use tokio::sync::mpsc::UnboundedReceiver;
36use tokio::sync::Semaphore;
37use tokio::task::JoinHandle;
38use tokio_util::sync::CancellationToken;
39use tokio_util::task::TaskTracker;
40
41#[cfg(unix)]
42use tokio::signal::unix::{signal, SignalKind};
43
44/// How long shutdown waits for in-flight request handlers to finish.
45///
46/// Short, because these are single request/response exchanges and the peer will retry.
47/// The point is to stop new storage work starting, not to see every last request through.
48const PROTOCOL_DRAIN_GRACE: std::time::Duration = std::time::Duration::from_secs(5);
49
50/// The user agent this node announces itself with.
51///
52/// `saorsa-core` admits a peer to the DHT only when its agent starts with `node/`, so a node
53/// that lost the prefix would stop being routed to. The version is this build's rather than
54/// the transport's, because it is the one a peer needs in order to tell which release it is
55/// talking to.
56///
57/// A node that serves chunks also carries the get-or-closer token (ADR-0020). Native peers
58/// exchange no capabilities, and a node built before that request drops it without a reply,
59/// so this token is how a client knows it may send one. A node with storage switched off
60/// never answers chunk requests, so it does not announce it.
61pub(crate) fn user_agent(serves_chunks: bool) -> String {
62    let agent = format!("node/{}", env!("CARGO_PKG_VERSION"));
63    if serves_chunks {
64        format!("{agent} {GET_OR_CLOSER_AGENT_TOKEN}")
65    } else {
66        agent
67    }
68}
69
70/// Builder for constructing an Ant node.
71pub struct NodeBuilder {
72    config: NodeConfig,
73}
74
75impl NodeBuilder {
76    /// Create a new node builder with the given configuration.
77    #[must_use]
78    pub fn new(config: NodeConfig) -> Self {
79        Self { config }
80    }
81
82    /// Reject startup in production mode without a usable rewards address.
83    ///
84    /// A node that cannot receive payment must not silently run on the
85    /// production network. The placeholder address shipped in the example
86    /// config and an empty string both count as "unconfigured".
87    ///
88    /// # Errors
89    ///
90    /// Returns [`Error::Config`] if `network_mode` is `Production` and
91    /// `payment.rewards_address` is unset, empty, or the example placeholder.
92    fn validate_production_rewards_address(config: &NodeConfig) -> Result<()> {
93        if config.network_mode != NetworkMode::Production {
94            return Ok(());
95        }
96        let configured = config
97            .payment
98            .rewards_address
99            .as_deref()
100            .is_some_and(|addr| !addr.is_empty() && addr != "0xYOUR_ARBITRUM_ADDRESS_HERE");
101        if configured {
102            Ok(())
103        } else {
104            Err(Error::Config(
105                "CRITICAL: Rewards address is not configured. \
106                 Set payment.rewards_address in config to your Arbitrum wallet address."
107                    .to_string(),
108            ))
109        }
110    }
111
112    /// Build and start the node.
113    ///
114    /// # Errors
115    ///
116    /// Returns an error if the node fails to start.
117    #[allow(clippy::too_many_lines)]
118    pub async fn build(mut self) -> Result<RunningNode> {
119        info!("Building ant-node with config: {:?}", self.config);
120
121        Self::validate_production_rewards_address(&self.config)?;
122
123        #[cfg(not(feature = "webrtc-direct"))]
124        if self.config.webrtc_direct.enabled {
125            return Err(Error::Config(
126                "webrtc_direct is enabled but this binary was not built with the \
127                 'webrtc-direct' feature"
128                    .to_string(),
129            ));
130        }
131
132        // Resolve identity and root_dir (may update self.config.root_dir)
133        let identity = Arc::new(Self::resolve_identity(&mut self.config).await?);
134        let peer_id = identity.peer_id().to_hex();
135
136        info!(peer_id = %peer_id, root_dir = %self.config.root_dir.display(), "Node identity resolved");
137
138        // Ensure root directory exists
139        std::fs::create_dir_all(&self.config.root_dir)?;
140
141        // Create shutdown token
142        let shutdown = CancellationToken::new();
143
144        // Create event channel
145        let (events_tx, events_rx) = create_event_channel();
146
147        // Convert our config to saorsa-core's config
148        let mut core_config = Self::build_core_config(&self.config)?;
149        // Inject the ML-DSA identity so the P2PNode's transport peer ID
150        // matches the pub_key embedded in payment quotes.
151        core_config.node_identity = Some(Arc::clone(&identity));
152        debug!("Core config: {:?}", core_config);
153
154        // Initialize saorsa-core's P2PNode
155        let p2p_node = P2PNode::new(core_config)
156            .await
157            .map_err(|e| Error::Startup(format!("Failed to create P2P node: {e}")))?;
158
159        // Create upgrade monitor
160        let upgrade_monitor = {
161            let node_id_seed = p2p_node.peer_id().as_bytes();
162            Some(Self::build_upgrade_monitor(&self.config, node_id_seed))
163        };
164
165        let repl_config = ReplicationConfig::default();
166
167        // Initialize ANT protocol handler for chunk storage and
168        // wire the fresh-write channel so PUTs trigger replication.
169        let (ant_protocol, fresh_write_rx) = if self.config.storage.enabled {
170            let (fresh_write_tx, fresh_write_rx) = tokio::sync::mpsc::unbounded_channel();
171            let mut protocol =
172                Self::build_ant_protocol(&self.config, &identity, repl_config.close_group_size)
173                    .await?;
174            protocol.set_fresh_write_sender(fresh_write_tx);
175            (Some(Arc::new(protocol)), Some(fresh_write_rx))
176        } else {
177            info!("Chunk storage disabled");
178            (None, None)
179        };
180
181        // Only now, and only if a store was actually opened. Clearing up after the storage
182        // migration deletes directories the previous release had retired, and retirement
183        // counted on every chunk the node kept being in the file store — which is only true
184        // if the file store is there. Doing this earlier put the deletion in front of a
185        // constructor that can still fail on an unreadable layout, a directory it cannot
186        // create, or a lock another process has not let go of, and a node that lost both
187        // stores that way had nothing to go back to.
188        //
189        // A node with storage switched off never builds one at all, so it never establishes
190        // that anything was copied anywhere, and it does not delete. It also has no use for
191        // the disk it would recover. Leaving the directory costs space on a node that is not
192        // storing anything anyway.
193        if ant_protocol.is_some() {
194            legacy_artifacts::clean_up(&self.config.root_dir);
195        } else {
196            info!(
197                "Chunk storage is disabled, so anything the storage migration left behind is \
198                 being left where it is: nothing here can establish that its chunks were \
199                 copied anywhere."
200            );
201        }
202
203        let p2p_arc = Arc::new(p2p_node);
204
205        // Wire the P2PNode handle into AntProtocol so payment proofs can query
206        // live-DHT closeness.
207        if let Some(ref protocol) = ant_protocol {
208            protocol.attach_p2p_node(Arc::clone(&p2p_arc));
209        }
210
211        let replication_engine = match (&ant_protocol, fresh_write_rx) {
212            (Some(protocol), Some(fresh_rx)) => {
213                Self::build_replication_engine(
214                    protocol,
215                    repl_config,
216                    &p2p_arc,
217                    &identity,
218                    &self.config.root_dir,
219                    fresh_rx,
220                    &shutdown,
221                )
222                .await?
223            }
224            _ => None,
225        };
226
227        let node = RunningNode {
228            config: self.config,
229            p2p_node: p2p_arc,
230            shutdown,
231            events_tx,
232            events_rx: Some(events_rx),
233            upgrade_monitor,
234            ant_protocol,
235            replication_engine,
236            protocol_task: None,
237            protocol_children: TaskTracker::new(),
238            #[cfg(feature = "webrtc-direct")]
239            webrtc_direct_task: None,
240            #[cfg(feature = "webrtc-direct")]
241            webrtc_diagnostics: tokio::sync::watch::channel(None).0,
242            upgrade_exit_code: Arc::new(AtomicI32::new(-1)),
243        };
244
245        Ok(node)
246    }
247
248    /// Start the replication engine.
249    ///
250    /// # Errors
251    ///
252    /// Never, currently: an engine that fails to start is logged and the node runs without
253    /// one, as it always has. The signature keeps its `Result` because the caller's does.
254    async fn build_replication_engine(
255        protocol: &Arc<AntProtocol>,
256        repl_config: ReplicationConfig,
257        p2p: &Arc<P2PNode>,
258        identity: &Arc<NodeIdentity>,
259        root_dir: &Path,
260        fresh_rx: UnboundedReceiver<FreshWriteEvent>,
261        shutdown: &CancellationToken,
262    ) -> Result<Option<ReplicationEngine>> {
263        let mut engine = match ReplicationEngine::new(
264            repl_config,
265            Arc::clone(p2p),
266            protocol.storage(),
267            protocol.payment_verifier_arc(),
268            Arc::clone(identity),
269            root_dir,
270            fresh_rx,
271            shutdown.clone(),
272        )
273        .await
274        {
275            Ok(engine) => engine,
276            Err(e) => {
277                warn!("Failed to initialize replication engine: {e}");
278                return Ok(None);
279            }
280        };
281
282        // ADR-0016: pointers replicate through the same engine. The PUT handler
283        // hands each newly stored paid state to it, and asks it before taking
284        // a final state (ADR-0018).
285        if let Some(service) = protocol.pointer_service() {
286            engine.with_pointer_service(service);
287        }
288
289        // ADR-0004: wire the engine's commitment state as the quote generator's
290        // commitment source so quotes force their price from the live storage
291        // commitment. Done here because the engine owns the commitment state and is
292        // built after the protocol.
293        let concrete = Arc::clone(engine.commitment_state());
294        let source: Arc<dyn crate::payment::quote::CommitmentSource> = concrete;
295        protocol.attach_commitment_source(source);
296        // ADR-0004: share the engine's gossip commitment cache with the verifier so the
297        // cross-check can resolve quote pins against neighbours' commitments.
298        protocol
299            .payment_verifier_arc()
300            .attach_commitment_cache(Arc::clone(engine.last_commitment_by_peer()));
301        // ADR-0004: give the verifier the monetized-pin sender so commitments that back
302        // a payment get a deterministic first audit from the engine's drainer.
303        protocol
304            .payment_verifier_arc()
305            .attach_monetized_pin_sender(engine.monetized_pin_sender());
306
307        Ok(Some(engine))
308    }
309
310    /// Build the saorsa-core `NodeConfig` from our config.
311    fn build_core_config(config: &NodeConfig) -> Result<CoreNodeConfig> {
312        let local = matches!(config.network_mode, NetworkMode::Development);
313
314        let mut core_config = CoreNodeConfig::builder()
315            .port(config.port)
316            .ipv6(!config.ipv4_only)
317            .local(local)
318            .max_message_size(config.max_message_size)
319            .build()
320            .map_err(|e| Error::Config(format!("Failed to create core config: {e}")))?;
321
322        // Add bootstrap peers.
323        core_config.bootstrap_peers = config
324            .bootstrap
325            .iter()
326            .map(|addr| MultiAddr::quic(*addr))
327            .collect();
328
329        // Propagate network-mode tuning into saorsa-core where supported.
330        match config.network_mode {
331            NetworkMode::Production => {
332                core_config.diversity_config = Some(CoreDiversityConfig::default());
333            }
334            NetworkMode::Testnet => {
335                // Testnet allows loopback so nodes can be co-located on one machine.
336                core_config.allow_loopback = true;
337                core_config.diversity_config = Some(CoreDiversityConfig {
338                    max_per_ip: config.testnet.max_per_ip,
339                    max_per_subnet: config.testnet.max_per_subnet,
340                });
341            }
342            NetworkMode::Development => {
343                core_config.diversity_config = Some(CoreDiversityConfig::permissive());
344            }
345        }
346
347        core_config.custom_user_agent = Some(user_agent(config.storage.enabled));
348
349        // Persist close group peers + trust scores across restarts.
350        // Default to root_dir (alongside node_identity.key) when not explicitly set.
351        core_config.close_group_cache_dir = Some(
352            config
353                .close_group_cache_dir
354                .clone()
355                .unwrap_or_else(|| config.root_dir.clone()),
356        );
357
358        Ok(core_config)
359    }
360
361    /// Resolve the node identity from disk or generate a new one.
362    ///
363    /// **When `root_dir` differs from the platform default** (set via `--root-dir`
364    /// or loaded from `config.toml`):
365    ///   - Use `root_dir` directly: load existing identity or generate a new one.
366    ///
367    /// **When `root_dir` is the platform default** (first run, no config file):
368    ///   1. Scan `{default_root_dir}/nodes/` for subdirectories containing
369    ///      `node_identity.key`.
370    ///   2. **None found** — first run: generate identity, create
371    ///      `nodes/{full_peer_id}/`, save identity there, update `config.root_dir`.
372    ///   3. **Exactly one found** — load it and update `config.root_dir`.
373    ///   4. **Multiple found** — return an error asking for `--root-dir`.
374    async fn resolve_identity(config: &mut NodeConfig) -> Result<NodeIdentity> {
375        if config.root_dir != default_root_dir() {
376            return Self::load_or_generate_identity(&config.root_dir).await;
377        }
378
379        let nodes_dir = default_nodes_dir();
380        let identity_dirs = Self::scan_identity_dirs(&nodes_dir)?;
381
382        match identity_dirs.len() {
383            0 => {
384                // First run: generate new identity and create a peer-id-scoped subdirectory
385                let identity = NodeIdentity::generate().map_err(|e| {
386                    Error::Startup(format!("Failed to generate node identity: {e}"))
387                })?;
388                let peer_id = identity.peer_id().to_hex();
389                let peer_dir = nodes_dir.join(&peer_id);
390                std::fs::create_dir_all(&peer_dir)?;
391                identity
392                    .save_to_file(&peer_dir.join(NODE_IDENTITY_FILENAME))
393                    .await
394                    .map_err(|e| Error::Startup(format!("Failed to save node identity: {e}")))?;
395                config.root_dir = peer_dir;
396                Ok(identity)
397            }
398            1 => {
399                let dir = identity_dirs
400                    .first()
401                    .ok_or_else(|| Error::Config("No identity dirs found".to_string()))?;
402                let identity = NodeIdentity::load_from_file(&dir.join(NODE_IDENTITY_FILENAME))
403                    .await
404                    .map_err(|e| Error::Startup(format!("Failed to load node identity: {e}")))?;
405                config.root_dir.clone_from(dir);
406                Ok(identity)
407            }
408            _ => {
409                let dirs: Vec<String> = identity_dirs
410                    .iter()
411                    .filter_map(|d| d.file_name().map(|n| n.to_string_lossy().into_owned()))
412                    .collect();
413                Err(Error::Config(format!(
414                    "Multiple node identities found at {}: [{}]. Specify --root-dir to select one.",
415                    nodes_dir.display(),
416                    dirs.join(", ")
417                )))
418            }
419        }
420    }
421
422    /// Load an existing identity from `dir/node_identity.key`, or generate and save a new one.
423    async fn load_or_generate_identity(dir: &std::path::Path) -> Result<NodeIdentity> {
424        let key_path = dir.join(NODE_IDENTITY_FILENAME);
425        if key_path.exists() {
426            NodeIdentity::load_from_file(&key_path)
427                .await
428                .map_err(|e| Error::Startup(format!("Failed to load node identity: {e}")))
429        } else {
430            let identity = NodeIdentity::generate()
431                .map_err(|e| Error::Startup(format!("Failed to generate node identity: {e}")))?;
432            std::fs::create_dir_all(dir)?;
433            identity
434                .save_to_file(&key_path)
435                .await
436                .map_err(|e| Error::Startup(format!("Failed to save node identity: {e}")))?;
437            Ok(identity)
438        }
439    }
440
441    /// Scan `base_dir` for immediate subdirectories that contain `node_identity.key`.
442    fn scan_identity_dirs(base_dir: &std::path::Path) -> Result<Vec<PathBuf>> {
443        let mut dirs = Vec::new();
444        let read_dir = match std::fs::read_dir(base_dir) {
445            Ok(rd) => rd,
446            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(dirs),
447            Err(e) => return Err(e.into()),
448        };
449        for entry in read_dir {
450            let entry = entry?;
451            let path = entry.path();
452            if path.is_dir() && path.join(NODE_IDENTITY_FILENAME).exists() {
453                dirs.push(path);
454            }
455        }
456        Ok(dirs)
457    }
458
459    fn build_upgrade_monitor(config: &NodeConfig, node_id_seed: &[u8]) -> UpgradeMonitor {
460        let mut monitor = UpgradeMonitor::new(
461            config.upgrade.github_repo.clone(),
462            config.upgrade.channel,
463            config.upgrade.check_interval_hours,
464        );
465
466        if let Ok(cache_dir) = upgrade_cache_dir() {
467            monitor = monitor.with_release_cache(ReleaseCache::new(
468                cache_dir,
469                std::time::Duration::from_hours(1),
470            ));
471        }
472
473        if config.upgrade.staged_rollout_hours > 0 {
474            monitor =
475                monitor.with_staged_rollout(node_id_seed, config.upgrade.staged_rollout_hours);
476        }
477
478        monitor
479    }
480    /// Build the ANT protocol handler from config.
481    ///
482    /// Initializes the chunk store, payment verifier, and quote generator.
483    /// Wires ML-DSA-65 signing from the node's identity into the quote generator.
484    async fn build_ant_protocol(
485        config: &NodeConfig,
486        identity: &NodeIdentity,
487        close_group_size: usize,
488    ) -> Result<AntProtocol> {
489        let storage_config = ChunkStoreConfig {
490            root_dir: config.root_dir.clone(),
491            verify_on_read: config.storage.verify_on_read,
492            disk_reserve: config.storage.disk_reserve_mb.saturating_mul(MIB),
493        };
494        let storage = ChunkStore::new(storage_config)
495            .await
496            .map_err(|e| Error::Startup(format!("Failed to create the chunk store: {e}")))?;
497
498        // Parse rewards address (required — node must know where to receive payments)
499        let rewards_address = match config.payment.rewards_address {
500            Some(ref addr) => parse_rewards_address(addr)?,
501            None => {
502                return Err(Error::Startup(
503                    "No rewards address configured. Set --rewards-address or payment.rewards_address in config.".to_string(),
504                ));
505            }
506        };
507
508        // Create payment verifier
509        let evm_network = config.payment.evm_network.clone().into_evm_network();
510        let payment_config = PaymentVerifierConfig {
511            evm: EvmVerifierConfig {
512                network: evm_network,
513            },
514            cache_capacity: config.payment.cache_capacity,
515            close_group_size,
516            local_rewards_address: rewards_address,
517            // Shadow mode by default; enforcement is a per-node canary opt-in
518            // via ANT_PRICE_FLOOR_ENFORCE (see PriceFloorConfig).
519            price_floor: PriceFloorConfig::from_env(),
520        };
521        if payment_config.price_floor.enforce {
522            info!(
523                "Price floor ENFORCEMENT enabled (tolerance {}%)",
524                payment_config.price_floor.tolerance_percent
525            );
526        }
527        let payment_verifier = PaymentVerifier::new(payment_config);
528        let metrics_tracker = QuotingMetricsTracker::new(0);
529        let mut quote_generator = QuoteGenerator::new(rewards_address, metrics_tracker);
530
531        // Wire ML-DSA-65 signing from node identity.
532        // This same signer is used for both regular quotes and merkle candidate quotes.
533        crate::payment::wire_ml_dsa_signer(&mut quote_generator, identity)?;
534
535        let storage = Arc::new(storage);
536        let payment_verifier = Arc::new(payment_verifier);
537
538        // Pointers live beside the chunks, under the same root. Opening the
539        // store here is what makes pointer PUT/GET answerable at all: without
540        // it every pointer request is refused, which is the right answer for a
541        // node that keeps none but the wrong one for a node that should.
542        let pointer_store = crate::pointer::PointerStore::new(&config.root_dir).await?;
543        let pointers = crate::pointer::PointerService::new(pointer_store)
544            // Refuse a pointer whose address a chunk already occupies, rather
545            // than letting one kind silently overwrite the other.
546            .with_chunk_store(Arc::clone(&storage))
547            // Payment is verified against each record's state, so every update
548            // is paid for rather than riding the first one.
549            .with_payments(Arc::clone(&payment_verifier));
550
551        let protocol = AntProtocol::new(storage, payment_verifier, Arc::new(quote_generator))
552            .with_pointer_service(pointers);
553
554        info!(
555            "ANT protocol handler initialized with ML-DSA-65 signing (protocol={CHUNK_PROTOCOL_ID})"
556        );
557
558        Ok(protocol)
559    }
560}
561
562/// A running Ant node.
563pub struct RunningNode {
564    config: NodeConfig,
565    p2p_node: Arc<P2PNode>,
566    shutdown: CancellationToken,
567    events_tx: NodeEventsSender,
568    events_rx: Option<NodeEventsChannel>,
569    upgrade_monitor: Option<UpgradeMonitor>,
570    /// ANT protocol handler for chunk storage.
571    ant_protocol: Option<Arc<AntProtocol>>,
572    /// Replication engine (manages neighbor sync, verification, audits).
573    replication_engine: Option<ReplicationEngine>,
574    /// Protocol message routing background task.
575    protocol_task: Option<JoinHandle<()>>,
576    /// The per-message handler tasks the protocol loop spawns.
577    ///
578    /// Tracked rather than detached so shutdown can stop accepting work and then wait for
579    /// what is already in flight. Aborting only the loop leaves its children running, and
580    /// a chunk read that outlives the loop keeps working against a store the shutdown is
581    /// about to tear down.
582    protocol_children: TaskTracker,
583    /// ADR-0015 browser listener task.
584    #[cfg(feature = "webrtc-direct")]
585    webrtc_direct_task: Option<JoinHandle<()>>,
586    #[cfg(feature = "webrtc-direct")]
587    webrtc_diagnostics: tokio::sync::watch::Sender<Option<crate::web_rtc::WebRtcServerDiagnostics>>,
588    /// Exit code requested by a successful upgrade (-1 = no upgrade exit pending).
589    upgrade_exit_code: Arc<AtomicI32>,
590}
591
592impl RunningNode {
593    /// Subscribe before `run()` to receive the browser diagnostics handle after startup.
594    /// The handle can be sampled at any time and retains counters after shutdown.
595    #[cfg(feature = "webrtc-direct")]
596    #[must_use]
597    pub fn subscribe_webrtc_diagnostics(
598        &self,
599    ) -> tokio::sync::watch::Receiver<Option<crate::web_rtc::WebRtcServerDiagnostics>> {
600        self.webrtc_diagnostics.subscribe()
601    }
602
603    /// Get the node's root directory.
604    #[must_use]
605    pub fn root_dir(&self) -> &PathBuf {
606        &self.config.root_dir
607    }
608
609    /// Get a receiver for node events.
610    ///
611    /// Note: Can only be called once. Subsequent calls return None.
612    pub fn events(&mut self) -> Option<NodeEventsChannel> {
613        self.events_rx.take()
614    }
615
616    /// Subscribe to node events.
617    #[must_use]
618    pub fn subscribe_events(&self) -> NodeEventsChannel {
619        self.events_tx.subscribe()
620    }
621
622    /// Run the node until shutdown is requested.
623    ///
624    /// # Errors
625    ///
626    /// Returns an error if the node encounters a fatal error.
627    pub async fn run(&mut self) -> Result<()> {
628        let result = self.run_until_shutdown().await;
629        self.cleanup().await;
630        // If an upgrade triggered the shutdown, exit with the requested code.
631        // This happens *after* all cleanup (P2P shutdown, log flush, etc.) so
632        // that destructors and async resources are properly torn down.
633        let exit_code = self.upgrade_exit_code.load(Ordering::SeqCst);
634        if result.is_ok() && exit_code >= 0 {
635            info!("Exiting with code {} for upgrade restart", exit_code);
636            std::process::exit(exit_code);
637        }
638
639        result
640    }
641
642    /// Start serving and wait for shutdown; the caller owns cleanup on every exit.
643    #[allow(clippy::too_many_lines)]
644    async fn run_until_shutdown(&mut self) -> Result<()> {
645        info!("Node runtime loop starting");
646
647        // Subscribe to DHT events BEFORE starting the P2P node so the
648        // bootstrap-sync task does not miss the BootstrapComplete event
649        // emitted during P2PNode::start().
650        let dht_events_for_bootstrap = self
651            .replication_engine
652            .as_ref()
653            .map(|_| self.p2p_node.dht_manager().subscribe_events());
654
655        // Start the P2P node
656        self.p2p_node
657            .start()
658            .await
659            .map_err(|e| Error::Startup(format!("Failed to start P2P node: {e}")))?;
660
661        let listen_addrs = self.p2p_node.listen_addrs().await;
662        info!(listen_addrs = ?listen_addrs, "P2P node started");
663
664        // Extract the actual bound port (config port may be 0 = auto-select)
665        let actual_port = listen_addrs
666            .first()
667            .and_then(MultiAddr::port)
668            .unwrap_or(self.config.port);
669        info!(
670            port = actual_port,
671            "Node is running on port: {}", actual_port
672        );
673
674        #[cfg(feature = "webrtc-direct")]
675        if self.config.webrtc_direct.enabled {
676            let evm_network = self.config.payment.evm_network.clone().into_evm_network();
677            match crate::web_rtc::spawn(
678                &self.config.webrtc_direct,
679                &self.config.root_dir,
680                Arc::clone(&self.p2p_node),
681                self.ant_protocol.clone(),
682                &evm_network,
683                self.shutdown.clone(),
684                None,
685            )
686            .await
687            {
688                Ok(server) => {
689                    let _ = self
690                        .webrtc_diagnostics
691                        .send_replace(Some(server.diagnostics));
692                    self.webrtc_direct_task = Some(server.task);
693                }
694                Err(error) => {
695                    return Err(error);
696                }
697            }
698        }
699
700        // Emit started event
701        if let Err(e) = self.events_tx.send(NodeEvent::Started) {
702            warn!("Failed to send Started event: {e}");
703        }
704
705        // Start protocol message routing (P2P → AntProtocol → P2P response)
706        self.start_protocol_routing();
707
708        // Start replication engine background tasks
709        if let Some(ref mut engine) = self.replication_engine {
710            // Safety: dht_events_for_bootstrap is Some when replication_engine
711            // is Some (both arms use the same condition).
712            if let Some(dht_events) = dht_events_for_bootstrap {
713                engine.start(dht_events);
714            }
715            info!("Replication engine started");
716        }
717
718        // Start upgrade monitor if enabled
719        if let Some(monitor) = self.upgrade_monitor.take() {
720            let events_tx = self.events_tx.clone();
721            let shutdown = self.shutdown.clone();
722            let stop_on_upgrade = self.config.upgrade.stop_on_upgrade;
723            let upgrade_exit_code = Arc::clone(&self.upgrade_exit_code);
724
725            tokio::spawn(async move {
726                let mut monitor = monitor;
727                let mut upgrader = AutoApplyUpgrader::new().with_stop_on_upgrade(stop_on_upgrade);
728                if let Ok(cache_dir) = upgrade_cache_dir() {
729                    upgrader = upgrader.with_binary_cache(BinaryCache::new(cache_dir));
730                }
731
732                // Add randomized jitter before the first upgrade check to prevent all nodes
733                // from hitting the GitHub API simultaneously when started together.
734                {
735                    let jitter_duration = jittered_interval(monitor.check_interval());
736                    let first_check_time = chrono::Utc::now()
737                        + chrono::Duration::from_std(jitter_duration).unwrap_or_else(|e| {
738                            warn!("chrono::Duration::from_std failed for jitter ({e}), defaulting to 1 minute");
739                            chrono::Duration::minutes(1)
740                        });
741                    info!(
742                        "First upgrade check scheduled for {} (jitter: {}s)",
743                        first_check_time.to_rfc3339(),
744                        jitter_duration.as_secs()
745                    );
746                    tokio::time::sleep(jitter_duration).await;
747                }
748
749                loop {
750                    tokio::select! {
751                        () = shutdown.cancelled() => {
752                            break;
753                        }
754                        result = monitor.check_for_ready_upgrade() => {
755                            match result {
756                                Ok(Some(upgrade_info)) => {
757                                    info!(
758                                        current_version = %upgrader.current_version(),
759                                        new_version = %upgrade_info.version,
760                                        "Upgrade available"
761                                    );
762
763                                    // Send notification event
764                                    if let Err(e) = events_tx.send(NodeEvent::UpgradeAvailable {
765                                        version: upgrade_info.version.to_string(),
766                                    }) {
767                                        warn!("Failed to send UpgradeAvailable event: {e}");
768                                    }
769
770                                    // Auto-apply the upgrade
771                                    info!("Starting auto-apply upgrade...");
772                                    match upgrader.apply_upgrade(&upgrade_info).await {
773                                        Ok(UpgradeResult::Success { version, exit_code }) => {
774                                            info!("Upgrade to {} successful, initiating graceful shutdown", version);
775                                            upgrade_exit_code.store(exit_code, Ordering::SeqCst);
776                                            shutdown.cancel();
777                                            break;
778                                        }
779                                        Ok(UpgradeResult::RolledBack { reason }) => {
780                                            warn!("Error during upgrade process: {}", reason);
781                                        }
782                                        Ok(UpgradeResult::NoUpgrade) => {
783                                            info!("Already running latest version");
784                                        }
785                                        Err(e) => {
786                                            error!("Error during upgrade process: {}", e);
787                                        }
788                                    }
789                                }
790                                Ok(None) => {
791                                    if let Some(remaining) = monitor.time_until_upgrade() {
792                                        info!(
793                                            "Upgrade pending, rollout delay remaining: {}m {}s",
794                                            remaining.as_secs() / 60,
795                                            remaining.as_secs() % 60
796                                        );
797                                    } else {
798                                        info!("No upgrade available");
799                                    }
800                                }
801                                Err(e) => {
802                                    warn!("Error during upgrade process: {}", e);
803                                }
804                            }
805                            // If an upgrade is pending, sleep for exactly the remaining
806                            // rollout delay so the node restarts at its scheduled time
807                            // rather than waiting for the next check interval tick.
808                            let sleep_duration = monitor.time_until_upgrade().map_or_else(
809                                || {
810                                    // No pending upgrade - schedule next check with jitter
811                                    let jittered_duration =
812                                        jittered_interval(monitor.check_interval());
813                                    let next_check = chrono::Utc::now()
814                                        + chrono::Duration::from_std(jittered_duration).unwrap_or_else(|e| {
815                                            warn!("chrono::Duration::from_std failed for interval ({e}), defaulting to 1 hour");
816                                            chrono::Duration::hours(1)
817                                        });
818                                    info!("Next upgrade check scheduled for {}", next_check.to_rfc3339());
819                                    jittered_duration
820                                },
821                                |remaining| {
822                                    // If the rollout delay has fully elapsed but the upgrade was
823                                    // not successfully applied, avoid a tight loop by backing off
824                                    // at least one check interval before retrying.
825                                    if remaining.is_zero() {
826                                        let backoff = jittered_interval(monitor.check_interval());
827                                        let next_check = chrono::Utc::now()
828                                            + chrono::Duration::from_std(backoff).unwrap_or_else(|e| {
829                                                warn!("chrono::Duration::from_std failed for backoff ({e}), defaulting to 1 hour");
830                                                chrono::Duration::hours(1)
831                                            });
832                                        info!(
833                                            "Upgrade rollout delay elapsed but previous apply did not succeed; \
834                                             backing off, next check scheduled for {}",
835                                            next_check.to_rfc3339()
836                                        );
837                                        backoff
838                                    } else {
839                                        let wake_time = chrono::Utc::now()
840                                            + chrono::Duration::from_std(remaining).unwrap_or_else(|e| {
841                                                warn!("chrono::Duration::from_std failed for rollout delay ({e}), defaulting to 1 minute");
842                                                chrono::Duration::minutes(1)
843                                            });
844                                        info!("Will apply upgrade at {}", wake_time.to_rfc3339());
845                                        remaining
846                                    }
847                                },
848                            );
849                            // Use select! so shutdown can interrupt long sleeps
850                            // (e.g. during a full rollout window delay).
851                            tokio::select! {
852                                () = shutdown.cancelled() => {
853                                    break;
854                                }
855                                () = tokio::time::sleep(sleep_duration) => {}
856                            }
857                        }
858                    }
859                }
860            });
861        }
862
863        info!("Node running, waiting for shutdown signal");
864
865        // The main event loop, with signal handling. Everything above this starts
866        // something; this is where the node waits.
867        self.run_event_loop().await
868    }
869
870    /// Drain dependent work before shutting down native networking.
871    async fn cleanup(&mut self) {
872        self.shutdown.cancel();
873        // The shared token closes the WebRtcDirect accept loop and active
874        // browser sessions before storage and native P2P are torn down.
875        #[cfg(feature = "webrtc-direct")]
876        if let Some(task) = self.webrtc_direct_task.take() {
877            if let Err(error) = task.await {
878                warn!("WebRtcDirect task shutdown failed: {error}");
879            }
880        }
881
882        // Protocol routing stops first, loop and children both. The routing loop waits on
883        // `events.recv()` and has no cancellation branch of its own, and it holds an `Arc`
884        // on the P2P node that keeps the sender it is waiting on alive, so nothing else
885        // here will ever wake it. Left running it holds the chunk store and its
886        // single-process lock open after the node has returned. Aborting the accept loop
887        // alone is not enough either: the requests already in flight run in their own
888        // tasks, which is what the drain below is for.
889        if let Some(handle) = self.protocol_task.take() {
890            handle.abort();
891            // Awaited, not just asked to stop. `abort` schedules cancellation; it does not
892            // establish that the task is gone, and what matters here is that it has
893            // dropped its `Arc` on the protocol and with it the store's single-process
894            // lock before this function returns. The join resolves as cancelled.
895            let _ = handle.await;
896        }
897        // Cancelled first, so anything still queued behind the concurrency permits gives
898        // up rather than starting fresh storage work, then given a moment to finish what
899        // is genuinely in flight.
900        self.shutdown.cancel();
901        self.protocol_children.close();
902        if tokio::time::timeout(PROTOCOL_DRAIN_GRACE, self.protocol_children.wait())
903            .await
904            .is_err()
905        {
906            warn!(
907                "{} request handler(s) had not finished after {}s; continuing shutdown \
908                 without them.",
909                self.protocol_children.len(),
910                PROTOCOL_DRAIN_GRACE.as_secs()
911            );
912        }
913
914        // Shutdown replication engine before P2P so background tasks don't
915        // use a dead P2P layer, and Arc<ChunkStore> references are released.
916        if let Some(ref mut engine) = self.replication_engine {
917            engine.shutdown().await;
918        }
919
920        // Shutdown P2P node
921        info!("Shutting down P2P node...");
922        if let Err(e) = self.p2p_node.shutdown().await {
923            warn!("Error during P2P node shutdown: {e}");
924        }
925
926        if let Err(e) = self.events_tx.send(NodeEvent::ShuttingDown) {
927            warn!("Failed to send ShuttingDown event: {e}");
928        }
929        info!("Node shutdown complete");
930    }
931
932    /// Run the main event loop, handling shutdown and signals.
933    #[cfg(unix)]
934    async fn run_event_loop(&self) -> Result<()> {
935        let mut sigterm = signal(SignalKind::terminate())?;
936        let mut sighup = signal(SignalKind::hangup())?;
937
938        loop {
939            tokio::select! {
940                () = self.shutdown.cancelled() => {
941                    info!("Shutdown signal received");
942                    break;
943                }
944                _ = tokio::signal::ctrl_c() => {
945                    info!("Received SIGINT (Ctrl-C), initiating shutdown");
946                    self.shutdown();
947                    break;
948                }
949                _ = sigterm.recv() => {
950                    info!("Received SIGTERM, initiating shutdown");
951                    self.shutdown();
952                    break;
953                }
954                _ = sighup.recv() => {
955                    info!("Received SIGHUP (config reload not yet supported)");
956                }
957            }
958        }
959        Ok(())
960    }
961
962    /// Run the main event loop, handling shutdown signals (non-Unix version).
963    #[cfg(not(unix))]
964    async fn run_event_loop(&self) -> Result<()> {
965        loop {
966            tokio::select! {
967                () = self.shutdown.cancelled() => {
968                    info!("Shutdown signal received");
969                    break;
970                }
971                _ = tokio::signal::ctrl_c() => {
972                    info!("Received Ctrl-C, initiating shutdown");
973                    self.shutdown();
974                    break;
975                }
976            }
977        }
978        Ok(())
979    }
980
981    /// Answer one inbound chunk-protocol message from `source` as a running
982    /// node's router does, and send the reply. For test networks that route
983    /// messages themselves.
984    #[cfg(any(test, feature = "test-utils"))]
985    pub async fn answer_chunk_request(
986        protocol: &Arc<AntProtocol>,
987        p2p: &Arc<P2PNode>,
988        source: &saorsa_core::identity::PeerId,
989        data: &[u8],
990    ) {
991        Self::answer_one_request(
992            protocol,
993            p2p,
994            source,
995            data,
996            "chunk",
997            CHUNK_PROTOCOL_ID,
998            Instant::now(),
999        )
1000        .await;
1001    }
1002
1003    /// Handle one inbound protocol message and send whatever it produced.
1004    async fn answer_one_request(
1005        protocol: &Arc<AntProtocol>,
1006        p2p: &Arc<P2PNode>,
1007        source: &saorsa_core::identity::PeerId,
1008        data: &[u8],
1009        data_type: &str,
1010        response_topic: &str,
1011        received_at: Instant,
1012    ) {
1013        if data_type != "chunk" {
1014            return;
1015        }
1016        let queue_wait = received_at.elapsed();
1017        let handled = protocol
1018            .try_handle_request_with_context(
1019                data,
1020                Some(
1021                    ChunkRequestContext::new(source.to_string(), received_at, queue_wait)
1022                        .with_requester(*source),
1023                ),
1024            )
1025            .await;
1026        let telemetry = handled.get_telemetry;
1027        let traffic_key = handled.traffic_key;
1028        match handled.response {
1029            Ok(Some(response)) => {
1030                let response_len = response.len();
1031                let send_started = Instant::now();
1032                // Handed over as the `Bytes` it already is: a chunk GET
1033                // response is up to a whole chunk, and `to_vec` copied it.
1034                let send_result = p2p
1035                    .send_message(source, response_topic, response, &[])
1036                    .await;
1037                if let Some(telemetry) = telemetry {
1038                    telemetry.finish_send(send_started.elapsed(), send_result.is_ok());
1039                }
1040                // V2-834: attribute response bytes only once the send is
1041                // confirmed; failed sends are itemised separately.
1042                match (&send_result, traffic_key) {
1043                    (Ok(()), Some(key)) => storage_traffic::record_tx(key, response_len),
1044                    (Ok(()), None) => {
1045                        storage_traffic::record_tx(
1046                            storage_traffic::ChunkResponseKey::Other,
1047                            response_len,
1048                        );
1049                    }
1050                    (Err(_), _) => storage_traffic::record_send_failed(response_len),
1051                }
1052                if let Err(e) = send_result {
1053                    warn!("Failed to send {data_type} protocol response to {source}: {e}");
1054                }
1055            }
1056            Ok(None) => {
1057                if let Some(telemetry) = telemetry {
1058                    telemetry.finish_without_send("no_response");
1059                }
1060            }
1061            Err(e) => {
1062                if let Some(telemetry) = telemetry {
1063                    telemetry.finish_without_send("encode_error");
1064                }
1065                warn!("{data_type} protocol handler error: {e}");
1066            }
1067        }
1068    }
1069
1070    /// Start the protocol message routing background task.
1071    ///
1072    /// Subscribes to P2P events and routes incoming chunk protocol messages
1073    /// to the `AntProtocol` handler, sending responses back to the sender.
1074    fn start_protocol_routing(&mut self) {
1075        let protocol = match self.ant_protocol {
1076            Some(ref p) => Arc::clone(p),
1077            None => return,
1078        };
1079
1080        let mut events = self.p2p_node.subscribe_events();
1081        let p2p = Arc::clone(&self.p2p_node);
1082        let semaphore = Arc::new(Semaphore::new(64));
1083        let children = self.protocol_children.clone();
1084        let stopping = self.shutdown.clone();
1085
1086        self.protocol_task = Some(tokio::spawn(async move {
1087            while let Ok(event) = events.recv().await {
1088                if let P2PEvent::Message {
1089                    topic,
1090                    source: Some(source),
1091                    data,
1092                    ..
1093                } = event
1094                {
1095                    let handler_info: Option<(&str, &str)> = if topic == CHUNK_PROTOCOL_ID {
1096                        Some(("chunk", CHUNK_PROTOCOL_ID))
1097                    } else {
1098                        None
1099                    };
1100
1101                    if let Some((data_type, response_topic)) = handler_info {
1102                        debug!("Received {data_type} protocol message from {source}");
1103                        let received_at = Instant::now();
1104                        let protocol = Arc::clone(&protocol);
1105                        let p2p = Arc::clone(&p2p);
1106                        let sem = semaphore.clone();
1107                        let stopping = stopping.clone();
1108                        children.spawn(async move {
1109                            // A queued handler must not start work once shutdown has
1110                            // begun. With 64 permits and a busy node the queue behind them
1111                            // can be long, and every one of those would otherwise start
1112                            // fresh storage reads while the store beneath is being torn
1113                            // down.
1114                            let _permit = {
1115                                let acquired = tokio::select! {
1116                                    biased;
1117                                    () = stopping.cancelled() => return,
1118                                    p = sem.acquire() => p,
1119                                };
1120                                match acquired {
1121                                    Ok(permit) => permit,
1122                                    Err(_) => return,
1123                                }
1124                            };
1125                            // Checked again: the wait for a permit may have been long.
1126                            if stopping.is_cancelled() {
1127                                return;
1128                            }
1129                            Self::answer_one_request(
1130                                &protocol,
1131                                &p2p,
1132                                &source,
1133                                &data,
1134                                data_type,
1135                                response_topic,
1136                                received_at,
1137                            )
1138                            .await;
1139                        });
1140                    }
1141                }
1142            }
1143        }));
1144        info!("Protocol message routing started");
1145    }
1146
1147    /// Request the node to shut down.
1148    pub fn shutdown(&self) {
1149        self.shutdown.cancel();
1150    }
1151}
1152
1153/// Apply ±5% jitter to a base interval to prevent thundering-herd behaviour
1154/// when multiple nodes check for upgrades on the same schedule.
1155fn jittered_interval(base: std::time::Duration) -> std::time::Duration {
1156    let secs = base.as_secs();
1157    let variance = secs / 20; // 5%
1158    if variance == 0 {
1159        return base;
1160    }
1161    let jitter = rand::thread_rng().gen_range(0..=variance * 2);
1162    std::time::Duration::from_secs(secs.saturating_sub(variance) + jitter)
1163}
1164
1165#[cfg(test)]
1166#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1167mod tests {
1168    use rand::Rng;
1169    use tempfile::TempDir;
1170
1171    use crate::storage::legacy_artifacts::LEGACY_ENV_DIR;
1172
1173    /// The e2e port range, so a test bind never lands on a production or dev instance.
1174    const TEST_PORT_RANGE: std::ops::Range<u16> = 20000..60000;
1175
1176    /// How many times a bind is retried before the failure is treated as real.
1177    const BIND_ATTEMPTS: u32 = 5;
1178
1179    /// A well-formed address that receives nothing; no chain is contacted in these tests.
1180    const TEST_REWARDS_ADDRESS: &str = "0x0000000000000000000000000000000000000001";
1181
1182    /// A node config that builds without touching a chain or a real network.
1183    fn local_node_config(root: &std::path::Path, port: u16) -> NodeConfig {
1184        NodeConfig {
1185            root_dir: root.to_path_buf(),
1186            port,
1187            ipv4_only: true,
1188            network_mode: NetworkMode::Development,
1189            payment: crate::config::PaymentConfig {
1190                rewards_address: Some(TEST_REWARDS_ADDRESS.to_string()),
1191                ..crate::config::PaymentConfig::default()
1192            },
1193            ..NodeConfig::default()
1194        }
1195    }
1196
1197    /// A browser listener that cannot bind fails startup, and `run` still drains what it
1198    /// had started before returning.
1199    #[cfg(feature = "webrtc-direct")]
1200    #[tokio::test]
1201    async fn browser_startup_failure_drains_before_returning() {
1202        let dir = TempDir::new().expect("temp dir");
1203        let root = dir.path().join("node");
1204        std::fs::create_dir_all(&root).expect("mkdir");
1205        let occupied = tokio::net::UdpSocket::bind("127.0.0.1:0")
1206            .await
1207            .expect("bind");
1208        let mut config = local_node_config(&root, 0);
1209        config.webrtc_direct.enabled = true;
1210        config.webrtc_direct.bind = occupied.local_addr().expect("address");
1211        let mut node = NodeBuilder::new(config).build().await.expect("build");
1212        let cancelled = node.shutdown.clone();
1213        let result = node.run().await;
1214        assert!(result.is_err(), "occupied browser port must fail startup");
1215        assert!(cancelled.is_cancelled());
1216        assert!(node.protocol_children.is_empty());
1217        // The test runtime remains alive: cleanup must not rely on process exit.
1218        tokio::task::yield_now().await;
1219    }
1220
1221    /// A node builds on a root with nothing left over from the old store.
1222    #[tokio::test]
1223    async fn a_node_builds_on_a_clean_root() {
1224        let dir = TempDir::new().expect("temp dir");
1225        let root = dir.path().join("node");
1226        std::fs::create_dir_all(&root).expect("mkdir");
1227
1228        let mut built = None;
1229        let mut last_err = String::new();
1230        for _ in 0..BIND_ATTEMPTS {
1231            let port = rand::thread_rng().gen_range(TEST_PORT_RANGE);
1232            match NodeBuilder::new(local_node_config(&root, port))
1233                .build()
1234                .await
1235            {
1236                Ok(node) => {
1237                    built = Some(node);
1238                    break;
1239                }
1240                Err(e) => {
1241                    last_err = e.to_string();
1242                    tokio::time::sleep(std::time::Duration::from_millis(250)).await;
1243                }
1244            }
1245        }
1246        let Some(node) = built else {
1247            panic!("could not build a node after {BIND_ATTEMPTS} attempts: {last_err}");
1248        };
1249
1250        node.shutdown.cancel();
1251    }
1252
1253    /// A node with chunks in a store this build cannot read STARTS, however it is
1254    /// configured, and does not lose them.
1255    ///
1256    /// This asserted the opposite until the release that shipped it was reconsidered twice.
1257    /// First it refused to start, which serves nothing at all and cannot be recovered by
1258    /// hand, because nothing can hold a node on an older build. Then it deleted whatever it
1259    /// found, which is data loss for exactly the node that most needs the data: the upgrade
1260    /// monitor picks the newest eligible release rather than the next one, so a node that was
1261    /// offline through the previous release arrives here with everything it owns in that
1262    /// directory and nothing in the file store.
1263    ///
1264    /// Both configurations, because they are different code paths: a node with
1265    /// `storage.enabled = false` never builds a store, and the old environment is on its disk
1266    /// just the same.
1267    #[tokio::test]
1268    async fn a_node_with_an_unmigrated_store_starts_and_keeps_it() {
1269        for storage_enabled in [true, false] {
1270            let dir = TempDir::new().expect("temp dir");
1271            let root = dir.path().join("node");
1272            let env = root.join(LEGACY_ENV_DIR);
1273            std::fs::create_dir_all(&env).expect("mkdir");
1274            std::fs::write(env.join("data.mdb"), b"chunks that were never copied out")
1275                .expect("seed");
1276
1277            let port = rand::thread_rng().gen_range(TEST_PORT_RANGE);
1278            let mut config = local_node_config(&root, port);
1279            config.storage.enabled = storage_enabled;
1280
1281            let node = NodeBuilder::new(config).build().await.unwrap_or_else(|e| {
1282                panic!(
1283                    "a node with an unmigrated store must start (storage.enabled = \
1284                     {storage_enabled}): {e}"
1285                )
1286            });
1287            settle();
1288            assert!(
1289                env.join("data.mdb").exists(),
1290                "chunks that were never copied out were deleted (storage.enabled = \
1291                 {storage_enabled})"
1292            );
1293            node.shutdown.cancel();
1294        }
1295    }
1296
1297    /// A node with storage switched off deletes nothing, even a leftover marked finished.
1298    ///
1299    /// It never builds a store, so nothing about this node establishes that those chunks were
1300    /// copied anywhere: the mark is a claim made by a previous release about a file store
1301    /// this process has not opened and will not open. It also has no use for the disk. So the
1302    /// directory stays and stays recoverable.
1303    #[tokio::test]
1304    async fn a_node_with_storage_disabled_deletes_nothing() {
1305        let dir = TempDir::new().expect("temp dir");
1306        let root = dir.path().join("node");
1307        let env = root.join(LEGACY_ENV_DIR);
1308        std::fs::create_dir_all(&env).expect("mkdir");
1309        std::fs::write(
1310            env.join("data.mdb"),
1311            b"bytes retirement had already cleared",
1312        )
1313        .expect("seed");
1314        std::fs::write(env.join("RETIRED"), b"retired").expect("mark");
1315
1316        let port = rand::thread_rng().gen_range(TEST_PORT_RANGE);
1317        let mut config = local_node_config(&root, port);
1318        config.storage.enabled = false;
1319        let node = NodeBuilder::new(config).build().await.expect("must start");
1320        settle();
1321        assert!(
1322            env.join("data.mdb").exists(),
1323            "a node that never opened a store deleted one on the strength of a mark it \
1324             could not check"
1325        );
1326        node.shutdown.cancel();
1327    }
1328
1329    /// A store the migration finished with is removed, once the file store has opened.
1330    #[tokio::test]
1331    async fn a_finished_store_is_removed_once_the_replacement_opens() {
1332        let dir = TempDir::new().expect("temp dir");
1333        let root = dir.path().join("node");
1334        let env = root.join(LEGACY_ENV_DIR);
1335        std::fs::create_dir_all(&env).expect("mkdir");
1336        std::fs::write(
1337            env.join("data.mdb"),
1338            b"bytes retirement had already cleared",
1339        )
1340        .expect("seed");
1341        std::fs::write(env.join("RETIRED"), b"retired").expect("mark");
1342
1343        let port = rand::thread_rng().gen_range(TEST_PORT_RANGE);
1344        let node = NodeBuilder::new(local_node_config(&root, port))
1345            .build()
1346            .await
1347            .expect("a node with a finished leftover must start");
1348        assert!(wait_gone(&env));
1349        node.shutdown.cancel();
1350    }
1351
1352    /// Nothing is deleted until the store that replaced it has actually opened.
1353    ///
1354    /// Retirement counted on every chunk the node kept being in the file store, which is only
1355    /// true if the file store opens. An earlier version deleted first and let the constructor fail behind it,
1356    /// on an unreadable layout or a directory it could not create, and a node that lost both
1357    /// stores that way had nothing left to go back to.
1358    #[tokio::test]
1359    async fn a_finished_store_survives_a_file_store_that_will_not_open() {
1360        let dir = TempDir::new().expect("temp dir");
1361        let root = dir.path().join("node");
1362        let env = root.join(LEGACY_ENV_DIR);
1363        std::fs::create_dir_all(&env).expect("mkdir");
1364        std::fs::write(
1365            env.join("data.mdb"),
1366            b"bytes retirement had already cleared",
1367        )
1368        .expect("seed");
1369        std::fs::write(env.join("RETIRED"), b"retired").expect("mark");
1370
1371        // A file where the chunk directory has to be, so the store cannot create it.
1372        std::fs::write(root.join("chunks"), b"not a directory").expect("block the store");
1373
1374        let port = rand::thread_rng().gen_range(TEST_PORT_RANGE);
1375        let built = NodeBuilder::new(local_node_config(&root, port))
1376            .build()
1377            .await;
1378        assert!(
1379            built.is_err(),
1380            "the file store was supposed to fail to open"
1381        );
1382        settle();
1383        assert!(
1384            env.join("data.mdb").exists(),
1385            "the old store was deleted before the one replacing it could open"
1386        );
1387    }
1388
1389    /// The removal runs on its own thread.
1390    fn settle() {
1391        std::thread::sleep(std::time::Duration::from_millis(200));
1392    }
1393
1394    /// The removal runs on its own thread, so give it a moment.
1395    fn wait_gone(path: &std::path::Path) -> bool {
1396        for _ in 0..200 {
1397            if !path.exists() {
1398                return true;
1399            }
1400            std::thread::sleep(std::time::Duration::from_millis(10));
1401        }
1402        false
1403    }
1404
1405    use super::*;
1406    use crate::config::NODES_SUBDIR;
1407
1408    #[test]
1409    fn test_build_upgrade_monitor_staged_rollout_enabled() {
1410        let config = NodeConfig {
1411            upgrade: crate::config::UpgradeConfig {
1412                staged_rollout_hours: 24,
1413                ..Default::default()
1414            },
1415            ..Default::default()
1416        };
1417        let seed = b"node-seed";
1418
1419        let monitor = NodeBuilder::build_upgrade_monitor(&config, seed);
1420        assert!(monitor.has_staged_rollout());
1421    }
1422
1423    #[test]
1424    fn test_build_upgrade_monitor_staged_rollout_disabled() {
1425        let config = NodeConfig {
1426            upgrade: crate::config::UpgradeConfig {
1427                staged_rollout_hours: 0,
1428                ..Default::default()
1429            },
1430            ..Default::default()
1431        };
1432        let seed = b"node-seed";
1433
1434        let monitor = NodeBuilder::build_upgrade_monitor(&config, seed);
1435        assert!(!monitor.has_staged_rollout());
1436    }
1437
1438    #[test]
1439    fn test_build_core_config_sets_production_mode() {
1440        let config = NodeConfig {
1441            network_mode: NetworkMode::Production,
1442            ..Default::default()
1443        };
1444        let core = NodeBuilder::build_core_config(&config).expect("core config");
1445        assert!(core.diversity_config.is_some());
1446    }
1447
1448    #[test]
1449    fn test_build_core_config_ipv4_only() {
1450        let config = NodeConfig {
1451            ipv4_only: true,
1452            ..Default::default()
1453        };
1454        let core = NodeBuilder::build_core_config(&config).expect("core config");
1455        assert!(!core.ipv6, "ipv4_only should disable IPv6");
1456    }
1457
1458    #[test]
1459    fn test_build_core_config_dual_stack_by_default() {
1460        let config = NodeConfig::default();
1461        let core = NodeBuilder::build_core_config(&config).expect("core config");
1462        assert!(core.ipv6, "dual-stack should be the default");
1463    }
1464
1465    #[test]
1466    fn test_build_core_config_sets_development_mode_permissive() {
1467        let config = NodeConfig {
1468            network_mode: NetworkMode::Development,
1469            ..Default::default()
1470        };
1471        let core = NodeBuilder::build_core_config(&config).expect("core config");
1472        let diversity = core.diversity_config.expect("diversity");
1473        assert_eq!(diversity.max_per_ip, Some(usize::MAX));
1474        assert_eq!(diversity.max_per_subnet, Some(usize::MAX));
1475    }
1476
1477    #[test]
1478    fn test_scan_identity_dirs_empty_dir() {
1479        let tmp = tempfile::tempdir().unwrap();
1480        let dirs = NodeBuilder::scan_identity_dirs(tmp.path()).unwrap();
1481        assert!(dirs.is_empty(), "expected no identity dirs, got {dirs:?}");
1482    }
1483
1484    #[test]
1485    fn test_scan_identity_dirs_nonexistent_dir() {
1486        let tmp = tempfile::tempdir().unwrap();
1487        let path = tmp.path().join("nonexistent_identity_dir");
1488        let dirs = NodeBuilder::scan_identity_dirs(&path).unwrap();
1489        assert!(dirs.is_empty(), "expected no identity dirs, got {dirs:?}");
1490    }
1491
1492    #[test]
1493    fn test_scan_identity_dirs_finds_one() {
1494        let tmp = tempfile::tempdir().unwrap();
1495        let node_dir = tmp.path().join("abc123");
1496        std::fs::create_dir_all(&node_dir).unwrap();
1497        std::fs::write(node_dir.join(NODE_IDENTITY_FILENAME), "{}").unwrap();
1498
1499        let dirs = NodeBuilder::scan_identity_dirs(tmp.path()).unwrap();
1500        assert_eq!(dirs.len(), 1);
1501        assert_eq!(dirs[0], node_dir);
1502    }
1503
1504    #[test]
1505    fn test_scan_identity_dirs_finds_multiple() {
1506        let tmp = tempfile::tempdir().unwrap();
1507        for name in &["node_a", "node_b"] {
1508            let dir = tmp.path().join(name);
1509            std::fs::create_dir_all(&dir).unwrap();
1510            std::fs::write(dir.join(NODE_IDENTITY_FILENAME), "{}").unwrap();
1511        }
1512        // A directory without a key file should be ignored
1513        std::fs::create_dir_all(tmp.path().join("no_key")).unwrap();
1514
1515        let dirs = NodeBuilder::scan_identity_dirs(tmp.path()).unwrap();
1516        assert_eq!(dirs.len(), 2);
1517    }
1518
1519    #[tokio::test]
1520    async fn test_resolve_identity_first_run_creates_identity() {
1521        let tmp = tempfile::tempdir().unwrap();
1522        let mut config = NodeConfig {
1523            root_dir: tmp.path().to_path_buf(),
1524            ..Default::default()
1525        };
1526
1527        let identity = NodeBuilder::resolve_identity(&mut config).await.unwrap();
1528        // Key file should exist
1529        assert!(tmp.path().join(NODE_IDENTITY_FILENAME).exists());
1530        // peer_id should be derivable from the identity
1531        let peer_id = identity.peer_id().to_hex();
1532        assert_eq!(peer_id.len(), 64); // 32 bytes hex-encoded
1533    }
1534
1535    #[tokio::test]
1536    async fn test_resolve_identity_loads_existing() {
1537        let tmp = tempfile::tempdir().unwrap();
1538
1539        // Generate and save an identity
1540        let original = NodeIdentity::generate().unwrap();
1541        original
1542            .save_to_file(&tmp.path().join(NODE_IDENTITY_FILENAME))
1543            .await
1544            .unwrap();
1545
1546        let mut config = NodeConfig {
1547            root_dir: tmp.path().to_path_buf(),
1548            ..Default::default()
1549        };
1550
1551        let loaded = NodeBuilder::resolve_identity(&mut config).await.unwrap();
1552        assert_eq!(loaded.peer_id(), original.peer_id());
1553    }
1554
1555    #[test]
1556    fn test_peer_id_hex_length() {
1557        let id = saorsa_core::identity::PeerId::from_bytes([0x42; 32]);
1558        let hex = id.to_hex();
1559        assert_eq!(hex.len(), 64); // 32 bytes = 64 hex chars
1560    }
1561
1562    /// Simulates a node restart: first run creates identity in a scoped subdir
1563    /// under `nodes/`, second run discovers and reloads it — `peer_id` must be
1564    /// identical and the directory name is the full 64-char hex peer ID.
1565    #[tokio::test]
1566    async fn test_identity_persisted_across_restarts() {
1567        let base_dir = tempfile::tempdir().unwrap();
1568        let nodes_dir = base_dir.path().join(NODES_SUBDIR);
1569
1570        // First "boot": generate identity, save it in nodes/{peer_id}/
1571        let identity1 = NodeIdentity::generate().unwrap();
1572        let peer_id1 = identity1.peer_id().to_hex();
1573        let peer_dir = nodes_dir.join(&peer_id1);
1574        std::fs::create_dir_all(&peer_dir).unwrap();
1575        identity1
1576            .save_to_file(&peer_dir.join(NODE_IDENTITY_FILENAME))
1577            .await
1578            .unwrap();
1579
1580        // Verify directory name is the full 64-char hex peer ID
1581        assert_eq!(peer_id1.len(), 64);
1582        assert_eq!(peer_dir.file_name().unwrap().to_string_lossy(), peer_id1);
1583
1584        // Second "boot": scan should find and reload the same identity
1585        let identity_dirs = NodeBuilder::scan_identity_dirs(&nodes_dir).unwrap();
1586        assert_eq!(identity_dirs.len(), 1);
1587        let loaded = NodeIdentity::load_from_file(&identity_dirs[0].join(NODE_IDENTITY_FILENAME))
1588            .await
1589            .unwrap();
1590        let peer_id2 = loaded.peer_id().to_hex();
1591
1592        assert_eq!(peer_id1, peer_id2, "peer_id must survive restart");
1593        assert_eq!(
1594            identity_dirs[0], peer_dir,
1595            "root_dir must be the same directory"
1596        );
1597    }
1598
1599    /// When two identity subdirs exist under `nodes/`, the scan finds multiple
1600    /// and the resolve path would error asking for `--root-dir`.
1601    #[tokio::test]
1602    async fn test_multiple_identities_errors() {
1603        let base_dir = tempfile::tempdir().unwrap();
1604        let nodes_dir = base_dir.path().join(NODES_SUBDIR);
1605
1606        // Create two identity subdirectories under nodes/
1607        for name in &["aaaa", "bbbb"] {
1608            let dir = nodes_dir.join(name);
1609            std::fs::create_dir_all(&dir).unwrap();
1610            let identity = NodeIdentity::generate().unwrap();
1611            identity
1612                .save_to_file(&dir.join(NODE_IDENTITY_FILENAME))
1613                .await
1614                .unwrap();
1615        }
1616
1617        let identity_dirs = NodeBuilder::scan_identity_dirs(&nodes_dir).unwrap();
1618        assert_eq!(identity_dirs.len(), 2, "should find both identity dirs");
1619    }
1620
1621    /// With a non-default `root_dir` (explicit path), the identity is created on
1622    /// first run and reloaded on subsequent runs from the same directory.
1623    #[tokio::test]
1624    async fn test_explicit_root_dir_persists_across_restarts() {
1625        let tmp = tempfile::tempdir().unwrap();
1626
1627        // First boot — non-default root_dir triggers explicit path
1628        let mut config1 = NodeConfig {
1629            root_dir: tmp.path().to_path_buf(),
1630            ..Default::default()
1631        };
1632        let identity1 = NodeBuilder::resolve_identity(&mut config1).await.unwrap();
1633
1634        // Second boot — same dir
1635        let mut config2 = NodeConfig {
1636            root_dir: tmp.path().to_path_buf(),
1637            ..Default::default()
1638        };
1639        let identity2 = NodeBuilder::resolve_identity(&mut config2).await.unwrap();
1640
1641        assert_eq!(
1642            identity1.peer_id(),
1643            identity2.peer_id(),
1644            "explicit --root-dir must yield stable identity"
1645        );
1646    }
1647
1648    /// The prefix is what keeps this node in its peers' routing tables, and the version is
1649    /// this build's, with nothing after it on a node that does not serve chunks.
1650    #[test]
1651    fn the_user_agent_is_this_builds_version_under_the_node_prefix() {
1652        assert_eq!(
1653            super::user_agent(false),
1654            format!("node/{}", env!("CARGO_PKG_VERSION"))
1655        );
1656        assert!(super::user_agent(true).starts_with("node/"));
1657    }
1658
1659    #[test]
1660    fn user_agent_advertises_get_or_closer_only_when_serving_chunks() {
1661        assert!(crate::ant_protocol::advertises_get_or_closer(
1662            &super::user_agent(true)
1663        ));
1664        assert!(!crate::ant_protocol::advertises_get_or_closer(
1665            &super::user_agent(false)
1666        ));
1667    }
1668}