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::ReplicationEngine;
17use crate::storage::lmdb::MIB;
18use crate::storage::{AntProtocol, LmdbStorage, LmdbStorageConfig};
19use crate::upgrade::{
20    upgrade_cache_dir, AutoApplyUpgrader, BinaryCache, ReleaseCache, UpgradeMonitor, UpgradeResult,
21};
22use rand::Rng;
23use saorsa_core::identity::NodeIdentity;
24use saorsa_core::{
25    IPDiversityConfig as CoreDiversityConfig, MultiAddr, NodeConfig as CoreNodeConfig, P2PEvent,
26    P2PNode,
27};
28use std::path::PathBuf;
29use std::sync::atomic::{AtomicI32, Ordering};
30use std::sync::Arc;
31use tokio::sync::Semaphore;
32use tokio::task::JoinHandle;
33use tokio_util::sync::CancellationToken;
34
35#[cfg(unix)]
36use tokio::signal::unix::{signal, SignalKind};
37
38/// Builder for constructing an Ant node.
39pub struct NodeBuilder {
40    config: NodeConfig,
41}
42
43impl NodeBuilder {
44    /// Create a new node builder with the given configuration.
45    #[must_use]
46    pub fn new(config: NodeConfig) -> Self {
47        Self { config }
48    }
49
50    /// Reject startup in production mode without a usable rewards address.
51    ///
52    /// A node that cannot receive payment must not silently run on the
53    /// production network. The placeholder address shipped in the example
54    /// config and an empty string both count as "unconfigured".
55    ///
56    /// # Errors
57    ///
58    /// Returns [`Error::Config`] if `network_mode` is `Production` and
59    /// `payment.rewards_address` is unset, empty, or the example placeholder.
60    fn validate_production_rewards_address(config: &NodeConfig) -> Result<()> {
61        if config.network_mode != NetworkMode::Production {
62            return Ok(());
63        }
64        let configured = config
65            .payment
66            .rewards_address
67            .as_deref()
68            .is_some_and(|addr| !addr.is_empty() && addr != "0xYOUR_ARBITRUM_ADDRESS_HERE");
69        if configured {
70            Ok(())
71        } else {
72            Err(Error::Config(
73                "CRITICAL: Rewards address is not configured. \
74                 Set payment.rewards_address in config to your Arbitrum wallet address."
75                    .to_string(),
76            ))
77        }
78    }
79
80    /// Build and start the node.
81    ///
82    /// # Errors
83    ///
84    /// Returns an error if the node fails to start.
85    pub async fn build(mut self) -> Result<RunningNode> {
86        info!("Building ant-node with config: {:?}", self.config);
87
88        Self::validate_production_rewards_address(&self.config)?;
89
90        // Resolve identity and root_dir (may update self.config.root_dir)
91        let identity = Arc::new(Self::resolve_identity(&mut self.config).await?);
92        let peer_id = identity.peer_id().to_hex();
93
94        info!(peer_id = %peer_id, root_dir = %self.config.root_dir.display(), "Node identity resolved");
95
96        // Ensure root directory exists
97        std::fs::create_dir_all(&self.config.root_dir)?;
98
99        // Create shutdown token
100        let shutdown = CancellationToken::new();
101
102        // Create event channel
103        let (events_tx, events_rx) = create_event_channel();
104
105        // Convert our config to saorsa-core's config
106        let mut core_config = Self::build_core_config(&self.config)?;
107        // Inject the ML-DSA identity so the P2PNode's transport peer ID
108        // matches the pub_key embedded in payment quotes.
109        core_config.node_identity = Some(Arc::clone(&identity));
110        debug!("Core config: {:?}", core_config);
111
112        // Initialize saorsa-core's P2PNode
113        let p2p_node = P2PNode::new(core_config)
114            .await
115            .map_err(|e| Error::Startup(format!("Failed to create P2P node: {e}")))?;
116
117        // Create upgrade monitor
118        let upgrade_monitor = {
119            let node_id_seed = p2p_node.peer_id().as_bytes();
120            Some(Self::build_upgrade_monitor(&self.config, node_id_seed))
121        };
122
123        let repl_config = ReplicationConfig::default();
124
125        // Initialize ANT protocol handler for chunk storage and
126        // wire the fresh-write channel so PUTs trigger replication.
127        let (ant_protocol, fresh_write_rx) = if self.config.storage.enabled {
128            let (fresh_write_tx, fresh_write_rx) = tokio::sync::mpsc::unbounded_channel();
129            let mut protocol =
130                Self::build_ant_protocol(&self.config, &identity, repl_config.close_group_size)
131                    .await?;
132            protocol.set_fresh_write_sender(fresh_write_tx);
133            (Some(Arc::new(protocol)), Some(fresh_write_rx))
134        } else {
135            info!("Chunk storage disabled");
136            (None, None)
137        };
138
139        let p2p_arc = Arc::new(p2p_node);
140
141        // Wire the P2PNode handle into AntProtocol so payment proofs can query
142        // live-DHT closeness.
143        if let Some(ref protocol) = ant_protocol {
144            protocol.attach_p2p_node(Arc::clone(&p2p_arc));
145        }
146
147        // Initialize replication engine (if storage is enabled)
148        let replication_engine = if let (Some(ref protocol), Some(fresh_rx)) =
149            (&ant_protocol, fresh_write_rx)
150        {
151            let storage_arc = protocol.storage();
152            let payment_verifier_arc = protocol.payment_verifier_arc();
153            match ReplicationEngine::new(
154                repl_config,
155                Arc::clone(&p2p_arc),
156                storage_arc,
157                payment_verifier_arc,
158                Arc::clone(&identity),
159                &self.config.root_dir,
160                fresh_rx,
161                shutdown.clone(),
162            )
163            .await
164            {
165                Ok(engine) => {
166                    // ADR-0004: wire the engine's commitment state as the
167                    // quote generator's commitment source so quotes force
168                    // their price from the live storage commitment. Done
169                    // here because the engine owns the commitment state and
170                    // is built after the protocol.
171                    if let Some(ref protocol) = ant_protocol {
172                        let concrete = Arc::clone(engine.commitment_state());
173                        let source: Arc<dyn crate::payment::quote::CommitmentSource> = concrete;
174                        protocol.attach_commitment_source(source);
175                        // ADR-0004: share the engine's gossip commitment
176                        // cache with the verifier so the cross-check can
177                        // resolve quote pins against neighbours' commitments.
178                        protocol
179                            .payment_verifier_arc()
180                            .attach_commitment_cache(Arc::clone(engine.last_commitment_by_peer()));
181                        // ADR-0004: give the verifier the monetized-pin sender so
182                        // commitments that back a payment get a deterministic
183                        // first audit from the engine's drainer.
184                        protocol
185                            .payment_verifier_arc()
186                            .attach_monetized_pin_sender(engine.monetized_pin_sender());
187                    }
188                    Some(engine)
189                }
190                Err(e) => {
191                    warn!("Failed to initialize replication engine: {e}");
192                    None
193                }
194            }
195        } else {
196            None
197        };
198
199        let node = RunningNode {
200            config: self.config,
201            p2p_node: p2p_arc,
202            shutdown,
203            events_tx,
204            events_rx: Some(events_rx),
205            upgrade_monitor,
206            ant_protocol,
207            replication_engine,
208            protocol_task: None,
209            upgrade_exit_code: Arc::new(AtomicI32::new(-1)),
210        };
211
212        Ok(node)
213    }
214
215    /// Build the saorsa-core `NodeConfig` from our config.
216    fn build_core_config(config: &NodeConfig) -> Result<CoreNodeConfig> {
217        let local = matches!(config.network_mode, NetworkMode::Development);
218
219        let mut core_config = CoreNodeConfig::builder()
220            .port(config.port)
221            .ipv6(!config.ipv4_only)
222            .local(local)
223            .max_message_size(config.max_message_size)
224            .build()
225            .map_err(|e| Error::Config(format!("Failed to create core config: {e}")))?;
226
227        // Add bootstrap peers.
228        core_config.bootstrap_peers = config
229            .bootstrap
230            .iter()
231            .map(|addr| MultiAddr::quic(*addr))
232            .collect();
233
234        // Propagate network-mode tuning into saorsa-core where supported.
235        match config.network_mode {
236            NetworkMode::Production => {
237                core_config.diversity_config = Some(CoreDiversityConfig::default());
238            }
239            NetworkMode::Testnet => {
240                // Testnet allows loopback so nodes can be co-located on one machine.
241                core_config.allow_loopback = true;
242                core_config.diversity_config = Some(CoreDiversityConfig {
243                    max_per_ip: config.testnet.max_per_ip,
244                    max_per_subnet: config.testnet.max_per_subnet,
245                });
246            }
247            NetworkMode::Development => {
248                core_config.diversity_config = Some(CoreDiversityConfig::permissive());
249            }
250        }
251
252        // Persist close group peers + trust scores across restarts.
253        // Default to root_dir (alongside node_identity.key) when not explicitly set.
254        core_config.close_group_cache_dir = Some(
255            config
256                .close_group_cache_dir
257                .clone()
258                .unwrap_or_else(|| config.root_dir.clone()),
259        );
260
261        Ok(core_config)
262    }
263
264    /// Resolve the node identity from disk or generate a new one.
265    ///
266    /// **When `root_dir` differs from the platform default** (set via `--root-dir`
267    /// or loaded from `config.toml`):
268    ///   - Use `root_dir` directly: load existing identity or generate a new one.
269    ///
270    /// **When `root_dir` is the platform default** (first run, no config file):
271    ///   1. Scan `{default_root_dir}/nodes/` for subdirectories containing
272    ///      `node_identity.key`.
273    ///   2. **None found** — first run: generate identity, create
274    ///      `nodes/{full_peer_id}/`, save identity there, update `config.root_dir`.
275    ///   3. **Exactly one found** — load it and update `config.root_dir`.
276    ///   4. **Multiple found** — return an error asking for `--root-dir`.
277    async fn resolve_identity(config: &mut NodeConfig) -> Result<NodeIdentity> {
278        if config.root_dir != default_root_dir() {
279            return Self::load_or_generate_identity(&config.root_dir).await;
280        }
281
282        let nodes_dir = default_nodes_dir();
283        let identity_dirs = Self::scan_identity_dirs(&nodes_dir)?;
284
285        match identity_dirs.len() {
286            0 => {
287                // First run: generate new identity and create a peer-id-scoped subdirectory
288                let identity = NodeIdentity::generate().map_err(|e| {
289                    Error::Startup(format!("Failed to generate node identity: {e}"))
290                })?;
291                let peer_id = identity.peer_id().to_hex();
292                let peer_dir = nodes_dir.join(&peer_id);
293                std::fs::create_dir_all(&peer_dir)?;
294                identity
295                    .save_to_file(&peer_dir.join(NODE_IDENTITY_FILENAME))
296                    .await
297                    .map_err(|e| Error::Startup(format!("Failed to save node identity: {e}")))?;
298                config.root_dir = peer_dir;
299                Ok(identity)
300            }
301            1 => {
302                let dir = identity_dirs
303                    .first()
304                    .ok_or_else(|| Error::Config("No identity dirs found".to_string()))?;
305                let identity = NodeIdentity::load_from_file(&dir.join(NODE_IDENTITY_FILENAME))
306                    .await
307                    .map_err(|e| Error::Startup(format!("Failed to load node identity: {e}")))?;
308                config.root_dir.clone_from(dir);
309                Ok(identity)
310            }
311            _ => {
312                let dirs: Vec<String> = identity_dirs
313                    .iter()
314                    .filter_map(|d| d.file_name().map(|n| n.to_string_lossy().into_owned()))
315                    .collect();
316                Err(Error::Config(format!(
317                    "Multiple node identities found at {}: [{}]. Specify --root-dir to select one.",
318                    nodes_dir.display(),
319                    dirs.join(", ")
320                )))
321            }
322        }
323    }
324
325    /// Load an existing identity from `dir/node_identity.key`, or generate and save a new one.
326    async fn load_or_generate_identity(dir: &std::path::Path) -> Result<NodeIdentity> {
327        let key_path = dir.join(NODE_IDENTITY_FILENAME);
328        if key_path.exists() {
329            NodeIdentity::load_from_file(&key_path)
330                .await
331                .map_err(|e| Error::Startup(format!("Failed to load node identity: {e}")))
332        } else {
333            let identity = NodeIdentity::generate()
334                .map_err(|e| Error::Startup(format!("Failed to generate node identity: {e}")))?;
335            std::fs::create_dir_all(dir)?;
336            identity
337                .save_to_file(&key_path)
338                .await
339                .map_err(|e| Error::Startup(format!("Failed to save node identity: {e}")))?;
340            Ok(identity)
341        }
342    }
343
344    /// Scan `base_dir` for immediate subdirectories that contain `node_identity.key`.
345    fn scan_identity_dirs(base_dir: &std::path::Path) -> Result<Vec<PathBuf>> {
346        let mut dirs = Vec::new();
347        let read_dir = match std::fs::read_dir(base_dir) {
348            Ok(rd) => rd,
349            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(dirs),
350            Err(e) => return Err(e.into()),
351        };
352        for entry in read_dir {
353            let entry = entry?;
354            let path = entry.path();
355            if path.is_dir() && path.join(NODE_IDENTITY_FILENAME).exists() {
356                dirs.push(path);
357            }
358        }
359        Ok(dirs)
360    }
361
362    fn build_upgrade_monitor(config: &NodeConfig, node_id_seed: &[u8]) -> UpgradeMonitor {
363        let mut monitor = UpgradeMonitor::new(
364            config.upgrade.github_repo.clone(),
365            config.upgrade.channel,
366            config.upgrade.check_interval_hours,
367        );
368
369        if let Ok(cache_dir) = upgrade_cache_dir() {
370            monitor = monitor.with_release_cache(ReleaseCache::new(
371                cache_dir,
372                std::time::Duration::from_secs(3600),
373            ));
374        }
375
376        if config.upgrade.staged_rollout_hours > 0 {
377            monitor =
378                monitor.with_staged_rollout(node_id_seed, config.upgrade.staged_rollout_hours);
379        }
380
381        monitor
382    }
383
384    /// Build the ANT protocol handler from config.
385    ///
386    /// Initializes LMDB storage, payment verifier, and quote generator.
387    /// Wires ML-DSA-65 signing from the node's identity into the quote generator.
388    async fn build_ant_protocol(
389        config: &NodeConfig,
390        identity: &NodeIdentity,
391        close_group_size: usize,
392    ) -> Result<AntProtocol> {
393        // Create LMDB storage
394        let storage_config = LmdbStorageConfig {
395            root_dir: config.root_dir.clone(),
396            verify_on_read: config.storage.verify_on_read,
397            max_map_size: config.storage.db_size_gb.saturating_mul(1024 * 1024 * 1024),
398            disk_reserve: config.storage.disk_reserve_mb.saturating_mul(MIB),
399        };
400        let storage = LmdbStorage::new(storage_config)
401            .await
402            .map_err(|e| Error::Startup(format!("Failed to create LMDB storage: {e}")))?;
403
404        // Parse rewards address (required — node must know where to receive payments)
405        let rewards_address = match config.payment.rewards_address {
406            Some(ref addr) => parse_rewards_address(addr)?,
407            None => {
408                return Err(Error::Startup(
409                    "No rewards address configured. Set --rewards-address or payment.rewards_address in config.".to_string(),
410                ));
411            }
412        };
413
414        // Create payment verifier
415        let evm_network = config.payment.evm_network.clone().into_evm_network();
416        let payment_config = PaymentVerifierConfig {
417            evm: EvmVerifierConfig {
418                network: evm_network,
419            },
420            cache_capacity: config.payment.cache_capacity,
421            close_group_size,
422            local_rewards_address: rewards_address,
423            // Shadow mode by default; enforcement is a per-node canary opt-in
424            // via ANT_PRICE_FLOOR_ENFORCE (see PriceFloorConfig).
425            price_floor: PriceFloorConfig::from_env(),
426        };
427        if payment_config.price_floor.enforce {
428            info!(
429                "Price floor ENFORCEMENT enabled (tolerance {}%)",
430                payment_config.price_floor.tolerance_percent
431            );
432        }
433        let payment_verifier = PaymentVerifier::new(payment_config);
434        let metrics_tracker = QuotingMetricsTracker::new(0);
435        let mut quote_generator = QuoteGenerator::new(rewards_address, metrics_tracker);
436
437        // Wire ML-DSA-65 signing from node identity.
438        // This same signer is used for both regular quotes and merkle candidate quotes.
439        crate::payment::wire_ml_dsa_signer(&mut quote_generator, identity)?;
440
441        let storage = Arc::new(storage);
442        let payment_verifier = Arc::new(payment_verifier);
443
444        let protocol = AntProtocol::new(storage, payment_verifier, Arc::new(quote_generator));
445
446        info!(
447            "ANT protocol handler initialized with ML-DSA-65 signing (protocol={CHUNK_PROTOCOL_ID})"
448        );
449
450        Ok(protocol)
451    }
452}
453
454/// A running Ant node.
455pub struct RunningNode {
456    config: NodeConfig,
457    p2p_node: Arc<P2PNode>,
458    shutdown: CancellationToken,
459    events_tx: NodeEventsSender,
460    events_rx: Option<NodeEventsChannel>,
461    upgrade_monitor: Option<UpgradeMonitor>,
462    /// ANT protocol handler for chunk storage.
463    ant_protocol: Option<Arc<AntProtocol>>,
464    /// Replication engine (manages neighbor sync, verification, audits).
465    replication_engine: Option<ReplicationEngine>,
466    /// Protocol message routing background task.
467    protocol_task: Option<JoinHandle<()>>,
468    /// Exit code requested by a successful upgrade (-1 = no upgrade exit pending).
469    upgrade_exit_code: Arc<AtomicI32>,
470}
471
472impl RunningNode {
473    /// Get the node's root directory.
474    #[must_use]
475    pub fn root_dir(&self) -> &PathBuf {
476        &self.config.root_dir
477    }
478
479    /// Get a receiver for node events.
480    ///
481    /// Note: Can only be called once. Subsequent calls return None.
482    pub fn events(&mut self) -> Option<NodeEventsChannel> {
483        self.events_rx.take()
484    }
485
486    /// Subscribe to node events.
487    #[must_use]
488    pub fn subscribe_events(&self) -> NodeEventsChannel {
489        self.events_tx.subscribe()
490    }
491
492    /// Run the node until shutdown is requested.
493    ///
494    /// # Errors
495    ///
496    /// Returns an error if the node encounters a fatal error.
497    #[allow(clippy::too_many_lines)]
498    pub async fn run(&mut self) -> Result<()> {
499        info!("Node runtime loop starting");
500
501        // Subscribe to DHT events BEFORE starting the P2P node so the
502        // bootstrap-sync task does not miss the BootstrapComplete event
503        // emitted during P2PNode::start().
504        let dht_events_for_bootstrap = self
505            .replication_engine
506            .as_ref()
507            .map(|_| self.p2p_node.dht_manager().subscribe_events());
508
509        // Start the P2P node
510        self.p2p_node
511            .start()
512            .await
513            .map_err(|e| Error::Startup(format!("Failed to start P2P node: {e}")))?;
514
515        let listen_addrs = self.p2p_node.listen_addrs().await;
516        info!(listen_addrs = ?listen_addrs, "P2P node started");
517
518        // Extract the actual bound port (config port may be 0 = auto-select)
519        let actual_port = listen_addrs
520            .first()
521            .and_then(MultiAddr::port)
522            .unwrap_or(self.config.port);
523        info!(
524            port = actual_port,
525            "Node is running on port: {}", actual_port
526        );
527
528        // Emit started event
529        if let Err(e) = self.events_tx.send(NodeEvent::Started) {
530            warn!("Failed to send Started event: {e}");
531        }
532
533        // Start protocol message routing (P2P → AntProtocol → P2P response)
534        self.start_protocol_routing();
535
536        // Start replication engine background tasks
537        if let Some(ref mut engine) = self.replication_engine {
538            // Safety: dht_events_for_bootstrap is Some when replication_engine
539            // is Some (both arms use the same condition).
540            if let Some(dht_events) = dht_events_for_bootstrap {
541                engine.start(dht_events);
542            }
543            info!("Replication engine started");
544        }
545
546        // Start upgrade monitor if enabled
547        if let Some(monitor) = self.upgrade_monitor.take() {
548            let events_tx = self.events_tx.clone();
549            let shutdown = self.shutdown.clone();
550            let stop_on_upgrade = self.config.upgrade.stop_on_upgrade;
551            let upgrade_exit_code = Arc::clone(&self.upgrade_exit_code);
552
553            tokio::spawn(async move {
554                let mut monitor = monitor;
555                let mut upgrader = AutoApplyUpgrader::new().with_stop_on_upgrade(stop_on_upgrade);
556                if let Ok(cache_dir) = upgrade_cache_dir() {
557                    upgrader = upgrader.with_binary_cache(BinaryCache::new(cache_dir));
558                }
559
560                // Add randomized jitter before the first upgrade check to prevent all nodes
561                // from hitting the GitHub API simultaneously when started together.
562                {
563                    let jitter_duration = jittered_interval(monitor.check_interval());
564                    let first_check_time = chrono::Utc::now()
565                        + chrono::Duration::from_std(jitter_duration).unwrap_or_else(|e| {
566                            warn!("chrono::Duration::from_std failed for jitter ({e}), defaulting to 1 minute");
567                            chrono::Duration::minutes(1)
568                        });
569                    info!(
570                        "First upgrade check scheduled for {} (jitter: {}s)",
571                        first_check_time.to_rfc3339(),
572                        jitter_duration.as_secs()
573                    );
574                    tokio::time::sleep(jitter_duration).await;
575                }
576
577                loop {
578                    tokio::select! {
579                        () = shutdown.cancelled() => {
580                            break;
581                        }
582                        result = monitor.check_for_ready_upgrade() => {
583                            match result {
584                                Ok(Some(upgrade_info)) => {
585                                    info!(
586                                        current_version = %upgrader.current_version(),
587                                        new_version = %upgrade_info.version,
588                                        "Upgrade available"
589                                    );
590
591                                    // Send notification event
592                                    if let Err(e) = events_tx.send(NodeEvent::UpgradeAvailable {
593                                        version: upgrade_info.version.to_string(),
594                                    }) {
595                                        warn!("Failed to send UpgradeAvailable event: {e}");
596                                    }
597
598                                    // Auto-apply the upgrade
599                                    info!("Starting auto-apply upgrade...");
600                                    match upgrader.apply_upgrade(&upgrade_info).await {
601                                        Ok(UpgradeResult::Success { version, exit_code }) => {
602                                            info!("Upgrade to {} successful, initiating graceful shutdown", version);
603                                            upgrade_exit_code.store(exit_code, Ordering::SeqCst);
604                                            shutdown.cancel();
605                                            break;
606                                        }
607                                        Ok(UpgradeResult::RolledBack { reason }) => {
608                                            warn!("Error during upgrade process: {}", reason);
609                                        }
610                                        Ok(UpgradeResult::NoUpgrade) => {
611                                            info!("Already running latest version");
612                                        }
613                                        Err(e) => {
614                                            error!("Error during upgrade process: {}", e);
615                                        }
616                                    }
617                                }
618                                Ok(None) => {
619                                    if let Some(remaining) = monitor.time_until_upgrade() {
620                                        info!(
621                                            "Upgrade pending, rollout delay remaining: {}m {}s",
622                                            remaining.as_secs() / 60,
623                                            remaining.as_secs() % 60
624                                        );
625                                    } else {
626                                        info!("No upgrade available");
627                                    }
628                                }
629                                Err(e) => {
630                                    warn!("Error during upgrade process: {}", e);
631                                }
632                            }
633                            // If an upgrade is pending, sleep for exactly the remaining
634                            // rollout delay so the node restarts at its scheduled time
635                            // rather than waiting for the next check interval tick.
636                            let sleep_duration = monitor.time_until_upgrade().map_or_else(
637                                || {
638                                    // No pending upgrade - schedule next check with jitter
639                                    let jittered_duration =
640                                        jittered_interval(monitor.check_interval());
641                                    let next_check = chrono::Utc::now()
642                                        + chrono::Duration::from_std(jittered_duration).unwrap_or_else(|e| {
643                                            warn!("chrono::Duration::from_std failed for interval ({e}), defaulting to 1 hour");
644                                            chrono::Duration::hours(1)
645                                        });
646                                    info!("Next upgrade check scheduled for {}", next_check.to_rfc3339());
647                                    jittered_duration
648                                },
649                                |remaining| {
650                                    // If the rollout delay has fully elapsed but the upgrade was
651                                    // not successfully applied, avoid a tight loop by backing off
652                                    // at least one check interval before retrying.
653                                    if remaining.is_zero() {
654                                        let backoff = jittered_interval(monitor.check_interval());
655                                        let next_check = chrono::Utc::now()
656                                            + chrono::Duration::from_std(backoff).unwrap_or_else(|e| {
657                                                warn!("chrono::Duration::from_std failed for backoff ({e}), defaulting to 1 hour");
658                                                chrono::Duration::hours(1)
659                                            });
660                                        info!(
661                                            "Upgrade rollout delay elapsed but previous apply did not succeed; \
662                                             backing off, next check scheduled for {}",
663                                            next_check.to_rfc3339()
664                                        );
665                                        backoff
666                                    } else {
667                                        let wake_time = chrono::Utc::now()
668                                            + chrono::Duration::from_std(remaining).unwrap_or_else(|e| {
669                                                warn!("chrono::Duration::from_std failed for rollout delay ({e}), defaulting to 1 minute");
670                                                chrono::Duration::minutes(1)
671                                            });
672                                        info!("Will apply upgrade at {}", wake_time.to_rfc3339());
673                                        remaining
674                                    }
675                                },
676                            );
677                            // Use select! so shutdown can interrupt long sleeps
678                            // (e.g. during a full rollout window delay).
679                            tokio::select! {
680                                () = shutdown.cancelled() => {
681                                    break;
682                                }
683                                () = tokio::time::sleep(sleep_duration) => {}
684                            }
685                        }
686                    }
687                }
688            });
689        }
690
691        info!("Node running, waiting for shutdown signal");
692
693        // Run the main event loop with signal handling
694        self.run_event_loop().await?;
695
696        // Shutdown replication engine before P2P so background tasks don't
697        // use a dead P2P layer, and Arc<LmdbStorage> references are released.
698        if let Some(ref mut engine) = self.replication_engine {
699            engine.shutdown().await;
700        }
701
702        // Stop protocol routing task
703        if let Some(handle) = self.protocol_task.take() {
704            handle.abort();
705        }
706
707        // Shutdown P2P node
708        info!("Shutting down P2P node...");
709        if let Err(e) = self.p2p_node.shutdown().await {
710            warn!("Error during P2P node shutdown: {e}");
711        }
712
713        if let Err(e) = self.events_tx.send(NodeEvent::ShuttingDown) {
714            warn!("Failed to send ShuttingDown event: {e}");
715        }
716        info!("Node shutdown complete");
717
718        // If an upgrade triggered the shutdown, exit with the requested code.
719        // This happens *after* all cleanup (P2P shutdown, log flush, etc.) so
720        // that destructors and async resources are properly torn down.
721        let exit_code = self.upgrade_exit_code.load(Ordering::SeqCst);
722        if exit_code >= 0 {
723            info!("Exiting with code {} for upgrade restart", exit_code);
724            std::process::exit(exit_code);
725        }
726
727        Ok(())
728    }
729
730    /// Run the main event loop, handling shutdown and signals.
731    #[cfg(unix)]
732    async fn run_event_loop(&self) -> Result<()> {
733        let mut sigterm = signal(SignalKind::terminate())?;
734        let mut sighup = signal(SignalKind::hangup())?;
735
736        loop {
737            tokio::select! {
738                () = self.shutdown.cancelled() => {
739                    info!("Shutdown signal received");
740                    break;
741                }
742                _ = tokio::signal::ctrl_c() => {
743                    info!("Received SIGINT (Ctrl-C), initiating shutdown");
744                    self.shutdown();
745                    break;
746                }
747                _ = sigterm.recv() => {
748                    info!("Received SIGTERM, initiating shutdown");
749                    self.shutdown();
750                    break;
751                }
752                _ = sighup.recv() => {
753                    info!("Received SIGHUP (config reload not yet supported)");
754                }
755            }
756        }
757        Ok(())
758    }
759
760    /// Run the main event loop, handling shutdown signals (non-Unix version).
761    #[cfg(not(unix))]
762    async fn run_event_loop(&self) -> Result<()> {
763        loop {
764            tokio::select! {
765                () = self.shutdown.cancelled() => {
766                    info!("Shutdown signal received");
767                    break;
768                }
769                _ = tokio::signal::ctrl_c() => {
770                    info!("Received Ctrl-C, initiating shutdown");
771                    self.shutdown();
772                    break;
773                }
774            }
775        }
776        Ok(())
777    }
778
779    /// Start the protocol message routing background task.
780    ///
781    /// Subscribes to P2P events and routes incoming chunk protocol messages
782    /// to the `AntProtocol` handler, sending responses back to the sender.
783    fn start_protocol_routing(&mut self) {
784        let protocol = match self.ant_protocol {
785            Some(ref p) => Arc::clone(p),
786            None => return,
787        };
788
789        let mut events = self.p2p_node.subscribe_events();
790        let p2p = Arc::clone(&self.p2p_node);
791        let semaphore = Arc::new(Semaphore::new(64));
792
793        self.protocol_task = Some(tokio::spawn(async move {
794            while let Ok(event) = events.recv().await {
795                if let P2PEvent::Message {
796                    topic,
797                    source: Some(source),
798                    data,
799                    ..
800                } = event
801                {
802                    let handler_info: Option<(&str, &str)> = if topic == CHUNK_PROTOCOL_ID {
803                        Some(("chunk", CHUNK_PROTOCOL_ID))
804                    } else {
805                        None
806                    };
807
808                    if let Some((data_type, response_topic)) = handler_info {
809                        debug!("Received {data_type} protocol message from {source}");
810                        let protocol = Arc::clone(&protocol);
811                        let p2p = Arc::clone(&p2p);
812                        let sem = semaphore.clone();
813                        tokio::spawn(async move {
814                            let Ok(_permit) = sem.acquire().await else {
815                                return;
816                            };
817                            let result = match data_type {
818                                "chunk" => protocol.try_handle_request(&data).await,
819                                _ => return,
820                            };
821                            match result {
822                                Ok(Some(response)) => {
823                                    if let Err(e) = p2p
824                                        .send_message(
825                                            &source,
826                                            response_topic,
827                                            response.to_vec(),
828                                            &[],
829                                        )
830                                        .await
831                                    {
832                                        warn!("Failed to send {data_type} protocol response to {source}: {e}");
833                                    }
834                                }
835                                Ok(None) => {}
836                                Err(e) => {
837                                    warn!("{data_type} protocol handler error: {e}");
838                                }
839                            }
840                        });
841                    }
842                }
843            }
844        }));
845        info!("Protocol message routing started");
846    }
847
848    /// Request the node to shut down.
849    pub fn shutdown(&self) {
850        self.shutdown.cancel();
851    }
852}
853
854/// Apply ±5% jitter to a base interval to prevent thundering-herd behaviour
855/// when multiple nodes check for upgrades on the same schedule.
856fn jittered_interval(base: std::time::Duration) -> std::time::Duration {
857    let secs = base.as_secs();
858    let variance = secs / 20; // 5%
859    if variance == 0 {
860        return base;
861    }
862    let jitter = rand::thread_rng().gen_range(0..=variance * 2);
863    std::time::Duration::from_secs(secs.saturating_sub(variance) + jitter)
864}
865
866#[cfg(test)]
867#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
868mod tests {
869    use super::*;
870    use crate::config::NODES_SUBDIR;
871
872    #[test]
873    fn test_build_upgrade_monitor_staged_rollout_enabled() {
874        let config = NodeConfig {
875            upgrade: crate::config::UpgradeConfig {
876                staged_rollout_hours: 24,
877                ..Default::default()
878            },
879            ..Default::default()
880        };
881        let seed = b"node-seed";
882
883        let monitor = NodeBuilder::build_upgrade_monitor(&config, seed);
884        assert!(monitor.has_staged_rollout());
885    }
886
887    #[test]
888    fn test_build_upgrade_monitor_staged_rollout_disabled() {
889        let config = NodeConfig {
890            upgrade: crate::config::UpgradeConfig {
891                staged_rollout_hours: 0,
892                ..Default::default()
893            },
894            ..Default::default()
895        };
896        let seed = b"node-seed";
897
898        let monitor = NodeBuilder::build_upgrade_monitor(&config, seed);
899        assert!(!monitor.has_staged_rollout());
900    }
901
902    #[test]
903    fn test_build_core_config_sets_production_mode() {
904        let config = NodeConfig {
905            network_mode: NetworkMode::Production,
906            ..Default::default()
907        };
908        let core = NodeBuilder::build_core_config(&config).expect("core config");
909        assert!(core.diversity_config.is_some());
910    }
911
912    #[test]
913    fn test_build_core_config_ipv4_only() {
914        let config = NodeConfig {
915            ipv4_only: true,
916            ..Default::default()
917        };
918        let core = NodeBuilder::build_core_config(&config).expect("core config");
919        assert!(!core.ipv6, "ipv4_only should disable IPv6");
920    }
921
922    #[test]
923    fn test_build_core_config_dual_stack_by_default() {
924        let config = NodeConfig::default();
925        let core = NodeBuilder::build_core_config(&config).expect("core config");
926        assert!(core.ipv6, "dual-stack should be the default");
927    }
928
929    #[test]
930    fn test_build_core_config_sets_development_mode_permissive() {
931        let config = NodeConfig {
932            network_mode: NetworkMode::Development,
933            ..Default::default()
934        };
935        let core = NodeBuilder::build_core_config(&config).expect("core config");
936        let diversity = core.diversity_config.expect("diversity");
937        assert_eq!(diversity.max_per_ip, Some(usize::MAX));
938        assert_eq!(diversity.max_per_subnet, Some(usize::MAX));
939    }
940
941    #[test]
942    fn test_scan_identity_dirs_empty_dir() {
943        let tmp = tempfile::tempdir().unwrap();
944        let dirs = NodeBuilder::scan_identity_dirs(tmp.path()).unwrap();
945        assert!(dirs.is_empty());
946    }
947
948    #[test]
949    fn test_scan_identity_dirs_nonexistent_dir() {
950        let tmp = tempfile::tempdir().unwrap();
951        let path = tmp.path().join("nonexistent_identity_dir");
952        let dirs = NodeBuilder::scan_identity_dirs(&path).unwrap();
953        assert!(dirs.is_empty());
954    }
955
956    #[test]
957    fn test_scan_identity_dirs_finds_one() {
958        let tmp = tempfile::tempdir().unwrap();
959        let node_dir = tmp.path().join("abc123");
960        std::fs::create_dir_all(&node_dir).unwrap();
961        std::fs::write(node_dir.join(NODE_IDENTITY_FILENAME), "{}").unwrap();
962
963        let dirs = NodeBuilder::scan_identity_dirs(tmp.path()).unwrap();
964        assert_eq!(dirs.len(), 1);
965        assert_eq!(dirs[0], node_dir);
966    }
967
968    #[test]
969    fn test_scan_identity_dirs_finds_multiple() {
970        let tmp = tempfile::tempdir().unwrap();
971        for name in &["node_a", "node_b"] {
972            let dir = tmp.path().join(name);
973            std::fs::create_dir_all(&dir).unwrap();
974            std::fs::write(dir.join(NODE_IDENTITY_FILENAME), "{}").unwrap();
975        }
976        // A directory without a key file should be ignored
977        std::fs::create_dir_all(tmp.path().join("no_key")).unwrap();
978
979        let dirs = NodeBuilder::scan_identity_dirs(tmp.path()).unwrap();
980        assert_eq!(dirs.len(), 2);
981    }
982
983    #[tokio::test]
984    async fn test_resolve_identity_first_run_creates_identity() {
985        let tmp = tempfile::tempdir().unwrap();
986        let mut config = NodeConfig {
987            root_dir: tmp.path().to_path_buf(),
988            ..Default::default()
989        };
990
991        let identity = NodeBuilder::resolve_identity(&mut config).await.unwrap();
992        // Key file should exist
993        assert!(tmp.path().join(NODE_IDENTITY_FILENAME).exists());
994        // peer_id should be derivable from the identity
995        let peer_id = identity.peer_id().to_hex();
996        assert_eq!(peer_id.len(), 64); // 32 bytes hex-encoded
997    }
998
999    #[tokio::test]
1000    async fn test_resolve_identity_loads_existing() {
1001        let tmp = tempfile::tempdir().unwrap();
1002
1003        // Generate and save an identity
1004        let original = NodeIdentity::generate().unwrap();
1005        original
1006            .save_to_file(&tmp.path().join(NODE_IDENTITY_FILENAME))
1007            .await
1008            .unwrap();
1009
1010        let mut config = NodeConfig {
1011            root_dir: tmp.path().to_path_buf(),
1012            ..Default::default()
1013        };
1014
1015        let loaded = NodeBuilder::resolve_identity(&mut config).await.unwrap();
1016        assert_eq!(loaded.peer_id(), original.peer_id());
1017    }
1018
1019    #[test]
1020    fn test_peer_id_hex_length() {
1021        let id = saorsa_core::identity::PeerId::from_bytes([0x42; 32]);
1022        let hex = id.to_hex();
1023        assert_eq!(hex.len(), 64); // 32 bytes = 64 hex chars
1024    }
1025
1026    /// Simulates a node restart: first run creates identity in a scoped subdir
1027    /// under `nodes/`, second run discovers and reloads it — `peer_id` must be
1028    /// identical and the directory name is the full 64-char hex peer ID.
1029    #[tokio::test]
1030    async fn test_identity_persisted_across_restarts() {
1031        let base_dir = tempfile::tempdir().unwrap();
1032        let nodes_dir = base_dir.path().join(NODES_SUBDIR);
1033
1034        // First "boot": generate identity, save it in nodes/{peer_id}/
1035        let identity1 = NodeIdentity::generate().unwrap();
1036        let peer_id1 = identity1.peer_id().to_hex();
1037        let peer_dir = nodes_dir.join(&peer_id1);
1038        std::fs::create_dir_all(&peer_dir).unwrap();
1039        identity1
1040            .save_to_file(&peer_dir.join(NODE_IDENTITY_FILENAME))
1041            .await
1042            .unwrap();
1043
1044        // Verify directory name is the full 64-char hex peer ID
1045        assert_eq!(peer_id1.len(), 64);
1046        assert_eq!(peer_dir.file_name().unwrap().to_string_lossy(), peer_id1);
1047
1048        // Second "boot": scan should find and reload the same identity
1049        let identity_dirs = NodeBuilder::scan_identity_dirs(&nodes_dir).unwrap();
1050        assert_eq!(identity_dirs.len(), 1);
1051        let loaded = NodeIdentity::load_from_file(&identity_dirs[0].join(NODE_IDENTITY_FILENAME))
1052            .await
1053            .unwrap();
1054        let peer_id2 = loaded.peer_id().to_hex();
1055
1056        assert_eq!(peer_id1, peer_id2, "peer_id must survive restart");
1057        assert_eq!(
1058            identity_dirs[0], peer_dir,
1059            "root_dir must be the same directory"
1060        );
1061    }
1062
1063    /// When two identity subdirs exist under `nodes/`, the scan finds multiple
1064    /// and the resolve path would error asking for `--root-dir`.
1065    #[tokio::test]
1066    async fn test_multiple_identities_errors() {
1067        let base_dir = tempfile::tempdir().unwrap();
1068        let nodes_dir = base_dir.path().join(NODES_SUBDIR);
1069
1070        // Create two identity subdirectories under nodes/
1071        for name in &["aaaa", "bbbb"] {
1072            let dir = nodes_dir.join(name);
1073            std::fs::create_dir_all(&dir).unwrap();
1074            let identity = NodeIdentity::generate().unwrap();
1075            identity
1076                .save_to_file(&dir.join(NODE_IDENTITY_FILENAME))
1077                .await
1078                .unwrap();
1079        }
1080
1081        let identity_dirs = NodeBuilder::scan_identity_dirs(&nodes_dir).unwrap();
1082        assert_eq!(identity_dirs.len(), 2, "should find both identity dirs");
1083    }
1084
1085    /// With a non-default `root_dir` (explicit path), the identity is created on
1086    /// first run and reloaded on subsequent runs from the same directory.
1087    #[tokio::test]
1088    async fn test_explicit_root_dir_persists_across_restarts() {
1089        let tmp = tempfile::tempdir().unwrap();
1090
1091        // First boot — non-default root_dir triggers explicit path
1092        let mut config1 = NodeConfig {
1093            root_dir: tmp.path().to_path_buf(),
1094            ..Default::default()
1095        };
1096        let identity1 = NodeBuilder::resolve_identity(&mut config1).await.unwrap();
1097
1098        // Second boot — same dir
1099        let mut config2 = NodeConfig {
1100            root_dir: tmp.path().to_path_buf(),
1101            ..Default::default()
1102        };
1103        let identity2 = NodeBuilder::resolve_identity(&mut config2).await.unwrap();
1104
1105        assert_eq!(
1106            identity1.peer_id(),
1107            identity2.peer_id(),
1108            "explicit --root-dir must yield stable identity"
1109        );
1110    }
1111}