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