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