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