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