Skip to main content

hopr_lib/
lib.rs

1//! HOPR library creating a unified [`Hopr`] object that can be used on its own,
2//! as well as integrated into other systems and libraries.
3//!
4//! The [`Hopr`] object is standalone, meaning that once it is constructed and run,
5//! it will perform its functionality autonomously. The API it offers serves as a
6//! high-level integration point for other applications and utilities, but offers
7//! a complete and fully featured HOPR node stripped from top level functionality
8//! such as the REST API, key management...
9//!
10//! The intended way to use hopr_lib is for a specific tool to be built on top of it;
11//! should the default `hoprd` implementation not be acceptable.
12//!
13//! For most of the practical use cases, the `hoprd` application should be a preferable
14//! choice.
15/// Helper functions.
16mod helpers;
17
18/// Builder module for the [`Hopr`] object.
19pub mod builder;
20/// Configuration-related public types
21pub mod config;
22/// Various public constants.
23pub mod constants;
24/// Lists all errors thrown from this library.
25pub mod errors;
26/// Periodic operational state dump: extra sections and the bridge from transport events.
27#[cfg(feature = "state-dump")]
28pub mod state_dump;
29/// Testing utilities: cluster fixtures, node wiring helpers, echo server.
30#[cfg(feature = "testing")]
31pub mod testing;
32/// Utility module with helper types and functionality over hopr-lib behavior.
33pub mod utils;
34
35pub use hopr_api as api;
36
37/// Exports of libraries necessary for API and interface operations.
38///
39/// Use `hopr_lib::api::types::*` for all type access.
40/// This module retains transport and network-specific types not available in `hopr_lib::api`.
41#[doc(hidden)]
42pub mod exports {
43    pub mod network {
44        pub use hopr_utils::network_types as types;
45    }
46
47    pub use hopr_transport as transport;
48}
49
50use std::{
51    sync::{Arc, atomic::Ordering},
52    time::Duration,
53};
54
55use futures::{FutureExt, Stream, StreamExt, TryFutureExt, pin_mut};
56use futures_concurrency::stream::Merge as _;
57use futures_time::future::FutureExt as FuturesTimeFutureExt;
58pub use hopr_api::types::keypair::key_pair::{HoprKeys, IdentityRetrievalModes};
59use hopr_api::{
60    PeerId,
61    chain::*,
62    graph::HoprGraphApi,
63    network::{Health, NetworkStreamControl, NetworkView},
64    node::{
65        ActionableEvent, ActionableEventDiscriminant, AtomicHoprState, ComponentStatus, ComponentStatusReporter,
66        EitherErrExt, EventWaitResult, HasChainApi, HasExitIncentivization, HasGraphView, HasNetworkView,
67        HasTicketManagement, HasTransportApi, HoprNodeOperations, HoprState, NodeOnchainIdentity, PixEvent,
68    },
69    tickets::TicketManagement,
70    types::crypto::prelude::OffchainKeypair,
71};
72/// Maximum user-data payload per HOPR session frame (bytes).
73///
74/// Use this when sizing buffers or computing how many session frames a given
75/// wxHOPR balance can fund (together with the on-chain ticket price).
76pub use hopr_transport::SESSION_MTU;
77/// Packet mixing API, re-exported so a consumer takes the mixer through `hopr-lib` alone instead of
78/// pinning `hopr-transport-mixer` as a separate dependency.
79///
80/// Both `hopr_lib::mixer` and `hopr_lib::exports::transport::mixer` name the same items.
81pub use hopr_transport::mixer;
82use hopr_transport::{ApplicationDataIn, HoprTransport, HoprTransportProcess, OffchainPublicKey};
83#[cfg(feature = "session-client")]
84pub use hopr_transport::{
85    FlowControlConfig, HoprSession, HoprSessionConfigurator, InvalidPixParams, LOCAL_PIX_SUITE, PixParams,
86    SessionCapabilities, SessionCapability, SessionTarget, SurbBalancerConfig,
87};
88use hopr_utils::runtime::prelude::spawn;
89pub use hopr_utils::runtime::{Abortable, AbortableList};
90use tracing::debug;
91
92pub use crate::constants::{MIN_NATIVE_BALANCE, SUGGESTED_NATIVE_BALANCE};
93use crate::errors::HoprLibError;
94
95/// Public routing configuration for session opening in `hopr-lib`.
96///
97/// This intentionally exposes only hop-count based routing.
98#[cfg(feature = "session-client")]
99#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, smart_default::SmartDefault)]
100#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
101pub struct HopRouting(
102    #[default(hopr_api::types::primitive::bounded::BoundedSize::MIN)]
103    hopr_api::types::primitive::bounded::BoundedSize<
104        { hopr_api::types::internal::routing::RoutingOptions::MAX_INTERMEDIATE_HOPS },
105    >,
106);
107
108#[cfg(feature = "session-client")]
109impl HopRouting {
110    /// Maximum number of hops that can be configured.
111    pub const MAX_HOPS: usize = hopr_api::types::internal::routing::RoutingOptions::MAX_INTERMEDIATE_HOPS;
112
113    /// Returns the configured number of hops.
114    pub fn hop_count(self) -> usize {
115        self.0.into()
116    }
117}
118
119#[cfg(feature = "session-client")]
120impl TryFrom<usize> for HopRouting {
121    type Error = hopr_api::types::primitive::errors::GeneralError;
122
123    fn try_from(value: usize) -> Result<Self, Self::Error> {
124        Ok(Self(value.try_into()?))
125    }
126}
127
128#[cfg(feature = "session-client")]
129impl From<HopRouting> for hopr_api::types::internal::routing::RoutingOptions {
130    fn from(value: HopRouting) -> Self {
131        Self::Hops(value.0)
132    }
133}
134
135#[cfg(feature = "session-client")]
136impl std::fmt::Display for HopRouting {
137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        write!(f, "{}-hop routing", self.hop_count())
139    }
140}
141
142/// Session client configuration for `hopr-lib`.
143///
144/// Unlike transport-level configuration, this API intentionally does not expose
145/// explicit intermediate paths.
146#[cfg(feature = "session-client")]
147#[derive(Debug, Clone, PartialEq, smart_default::SmartDefault)]
148pub struct HoprSessionClientConfig {
149    /// Forward route selection policy.
150    pub forward_path: HopRouting,
151    /// Return route selection policy.
152    pub return_path: HopRouting,
153    /// Capabilities offered by the session.
154    #[default(_code = "SessionCapability::Segmentation.into()")]
155    pub capabilities: SessionCapabilities,
156    /// Optional pseudonym used for the session. Mostly useful for testing only.
157    #[default(None)]
158    pub pseudonym: Option<hopr_api::types::internal::protocol::HoprPseudonym>,
159    /// Enable automatic SURB management for the session.
160    #[default(Some(SurbBalancerConfig::default()))]
161    pub surb_management: Option<SurbBalancerConfig>,
162    /// Sets the maximum number of SURBs sent with session data packets.
163    ///
164    /// Higher values add CPU strain, but reduce the workload of the SURB balancer (if configured).
165    /// The value is bounded by the packet size and will saturate there.
166    /// Every finite value follows the balancer's target: packets carry this many SURBs while the
167    /// counterparty is below its target and none once it is at or above it, so a value greater than `1`
168    /// cannot keep the counterparty more than one packet's SURBs above its target. Only `usize::MAX` is
169    /// not gated.
170    /// Setting to 0 will leave all the work to SURB balancer. If in that case no SURB balancer is
171    /// configured, there will be no SURBs produced at all, making the traffic only possible in
172    /// one direction.
173    #[default(1)]
174    pub max_surbs_per_data_packet: usize,
175    /// Opt-in client-side send-window flow control for this session (`None` = unpaced, the default).
176    /// `Some(FlowControlConfig::default())` = the clean profile; `Some(FlowControlConfig::robust())` =
177    /// the tail-tolerance bundle. Only meaningful on a reliable (`RetransmissionAck`) session.
178    #[default(None)]
179    pub flow_control: Option<FlowControlConfig>,
180    /// Abandon the frame due next once the sequence has advanced this far past it, instead of
181    /// holding everything already received for the whole frame timeout.
182    ///
183    /// Head-of-line bound for this session's incoming direction. `None` inherits the node's
184    /// setting, `Some(0)` disables it here, `Some(n)` sets it.
185    ///
186    /// Worth setting per session because the right value tracks reordering depth -- throughput x
187    /// latency spread / frame size -- which is a property of the traffic, not of the node: a bulk
188    /// data session and a control session on the same node differ by orders of magnitude.
189    ///
190    /// Has no effect on a session carrying a retransmission capability, where a missing frame can
191    /// still be recovered and waiting for it is productive.
192    pub max_frames_behind_gap: Option<usize>,
193}
194
195/// Session client configuration for explicit intermediate-path routing.
196#[cfg(all(feature = "session-client", feature = "explicit-path"))]
197#[deprecated(
198    since = "4.0.2-rc.1",
199    note = "temporary compatibility API; remove once the explicit path is not needed anymore."
200)]
201#[derive(Debug, Clone, PartialEq)]
202pub struct HoprSessionClientExplicitPathConfig {
203    /// Explicit forward intermediate path.
204    pub forward_path: Vec<hopr_api::types::internal::NodeId>,
205    /// Explicit return intermediate path.
206    pub return_path: Vec<hopr_api::types::internal::NodeId>,
207    /// Capabilities offered by the session.
208    pub capabilities: SessionCapabilities,
209    /// Optional pseudonym used for the session. Mostly useful for testing only.
210    pub pseudonym: Option<hopr_api::types::internal::protocol::HoprPseudonym>,
211    /// Enable automatic SURB management for the session.
212    pub surb_management: Option<SurbBalancerConfig>,
213    /// Sets the maximum number of possible SURBs which will always be sent with Session data packets (if they fit).
214    pub max_surbs_per_data_packet: usize,
215    /// Opt-in client-side send-window flow control for this session (`None` = unpaced).
216    pub flow_control: Option<FlowControlConfig>,
217    /// As [`HoprSessionClientConfig::max_frames_behind_gap`].
218    pub max_frames_behind_gap: Option<usize>,
219}
220
221#[cfg(all(feature = "session-client", feature = "explicit-path"))]
222#[allow(deprecated)]
223impl Default for HoprSessionClientExplicitPathConfig {
224    fn default() -> Self {
225        Self {
226            forward_path: Vec::default(),
227            return_path: Vec::default(),
228            capabilities: SessionCapability::Segmentation.into(),
229            pseudonym: None,
230            surb_management: Some(SurbBalancerConfig::default()),
231            max_surbs_per_data_packet: 1,
232            flow_control: None,
233            max_frames_behind_gap: None,
234        }
235    }
236}
237
238#[cfg(feature = "session-client")]
239impl From<HoprSessionClientConfig> for hopr_transport::SessionClientConfig {
240    fn from(value: HoprSessionClientConfig) -> Self {
241        Self {
242            forward_path_options: value.forward_path.into(),
243            return_path_options: value.return_path.into(),
244            capabilities: value.capabilities,
245            pseudonym: value.pseudonym,
246            surb_management: value.surb_management,
247            max_surbs_per_data_packet: value.max_surbs_per_data_packet,
248            flow_control: value.flow_control,
249            max_frames_behind_gap: value.max_frames_behind_gap,
250        }
251    }
252}
253
254#[cfg(all(feature = "session-client", feature = "explicit-path"))]
255#[allow(deprecated)]
256impl TryFrom<HoprSessionClientExplicitPathConfig> for hopr_transport::SessionClientConfig {
257    type Error = hopr_api::types::primitive::errors::GeneralError;
258
259    fn try_from(value: HoprSessionClientExplicitPathConfig) -> Result<Self, Self::Error> {
260        let forward =
261            hopr_api::types::internal::routing::RoutingOptions::IntermediatePath(value.forward_path.try_into()?);
262        let ret = hopr_api::types::internal::routing::RoutingOptions::IntermediatePath(value.return_path.try_into()?);
263
264        Ok(Self {
265            forward_path_options: forward,
266            return_path_options: ret,
267            capabilities: value.capabilities,
268            pseudonym: value.pseudonym,
269            surb_management: value.surb_management,
270            max_surbs_per_data_packet: value.max_surbs_per_data_packet,
271            flow_control: value.flow_control,
272            max_frames_behind_gap: value.max_frames_behind_gap,
273        })
274    }
275}
276
277/// Long-running tasks that are spawned by the HOPR node.
278#[derive(Debug, Clone, PartialEq, Eq, Hash, strum::Display, strum::EnumCount)]
279pub(crate) enum HoprLibProcess {
280    #[strum(to_string = "transport: {0}")]
281    Transport(HoprTransportProcess),
282    #[strum(to_string = "session server providing the exit node session stream functionality")]
283    #[allow(dead_code)] // constructed only with feature = "session-server"
284    SessionServer,
285    #[strum(to_string = "session server deciding the terms incoming sessions are admitted on")]
286    #[allow(dead_code)] // constructed only with feature = "session-server"
287    SessionAdmission,
288    #[strum(to_string = "subscription for on-chain channel updates")]
289    ChannelEvents,
290    #[strum(to_string = "on received ticket event (winning or rejected)")]
291    TicketEvents,
292    #[strum(to_string = "neglecting tickets on closed channels")]
293    ChannelClosureNeglect,
294    #[cfg(feature = "state-dump")]
295    #[strum(to_string = "periodic operational state dump")]
296    StateDump,
297}
298
299/// Prepare an optimized version of the tokio runtime setup for hopr-lib specifically.
300///
301/// Divide the available CPU parallelism by 2, since half of the available threads are
302/// to be used for IO-bound and half for CPU-bound tasks.
303#[cfg(feature = "runtime-tokio")]
304pub fn prepare_tokio_runtime(
305    num_cpu_threads: Option<std::num::NonZeroUsize>,
306    num_io_threads: Option<std::num::NonZeroUsize>,
307    thread_stack_size: Option<usize>,
308) -> anyhow::Result<tokio::runtime::Runtime> {
309    let avail_parallelism = std::thread::available_parallelism().ok().map(|v| v.get() / 2);
310
311    hopr_utils::parallelize::cpu::init_thread_pool(
312        num_cpu_threads
313            .map(|v| v.get())
314            .or(avail_parallelism)
315            .ok_or(anyhow::anyhow!(
316                "Could not determine the number of CPU threads to use. Please set the HOPRD_NUM_CPU_THREADS \
317                 environment variable."
318            ))?
319            .max(1),
320    )?;
321
322    Ok(tokio::runtime::Builder::new_multi_thread()
323        .enable_all()
324        .worker_threads(
325            num_io_threads
326                .map(|v| v.get())
327                .or(avail_parallelism)
328                .ok_or(anyhow::anyhow!(
329                    "Could not determine the number of IO threads to use. Please set the HOPRD_NUM_IO_THREADS \
330                     environment variable."
331                ))?
332                .max(1),
333        )
334        .thread_name("hoprd")
335        .thread_stack_size(thread_stack_size.unwrap_or(10 * 1024 * 1024).max(2 * 1024 * 1024))
336        .build()?)
337}
338
339/// Type alias used to send and receive transport data via a running HOPR node.
340pub type HoprTransportIO = hopr_transport::socket::HoprSocket<
341    futures::stream::BoxStream<'static, ApplicationDataIn>,
342    hopr_transport::HoprMessageSender,
343>;
344
345type TicketEvents = (
346    async_broadcast::Sender<hopr_api::node::TicketEvent>,
347    async_broadcast::InactiveReceiver<hopr_api::node::TicketEvent>,
348);
349
350type PixEvents = (
351    async_broadcast::Sender<hopr_api::node::PixEvent>,
352    async_broadcast::InactiveReceiver<hopr_api::node::PixEvent>,
353);
354
355/// Time to wait until the node's keybinding appears on-chain
356const NODE_READY_TIMEOUT: Duration = Duration::from_secs(120);
357
358/// HOPR main object providing the entire HOPR node functionality
359///
360/// Instantiating this object creates all processes and objects necessary for
361/// running the HOPR node. Once created, the node can be started using the
362/// `run()` method.
363///
364/// Externally offered API should be enough to perform all necessary tasks
365/// with the HOPR node manually, but it is advised to create such a configuration
366/// that manual interaction is unnecessary.
367///
368/// As such, the `hopr_lib` serves mainly as an integration point into Rust programs.
369pub struct Hopr<Chain, Graph, Net, TMgr> {
370    pub(crate) transport_id: OffchainKeypair,
371    pub(crate) chain_id: NodeOnchainIdentity,
372    pub(crate) cfg: config::HoprLibConfig,
373    pub(crate) state: Arc<AtomicHoprState>,
374    pub(crate) transport_api: HoprTransport<Chain, Graph, Net>,
375    pub(crate) chain_api: Chain,
376    pub(crate) ticket_event_subscribers: TicketEvents,
377    pub(crate) pix_event_subscribers: PixEvents,
378    pub(crate) ticket_manager: TMgr,
379    #[allow(dead_code)] // Handles must stay alive to keep background tasks running
380    pub(crate) processes: AbortableList<HoprLibProcess>,
381}
382
383impl<Chain, Graph, Net, TMgr> std::fmt::Debug for Hopr<Chain, Graph, Net, TMgr> {
384    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
385        f.debug_struct("Hopr")
386            .field("identity", &self.chain_id)
387            .field("state", &self.state.load(std::sync::atomic::Ordering::Relaxed))
388            .field("config", &self.cfg)
389            .field("processes", &self.processes)
390            .finish_non_exhaustive()
391    }
392}
393
394impl<Chain, Graph, Net, TMgr> Hopr<Chain, Graph, Net, TMgr>
395where
396    Chain: HoprChainApi + Clone + Send + Sync + 'static,
397    Graph: HoprGraphApi<HoprNodeId = OffchainPublicKey> + Clone + Send + Sync + 'static,
398    <Graph as hopr_api::graph::NetworkGraphTraverse>::Observed:
399        hopr_api::graph::traits::EdgeObservableRead + Send + 'static,
400    <Graph as hopr_api::graph::NetworkGraphWrite>::Observed: hopr_api::graph::traits::EdgeObservableWrite + Send,
401    Net: NetworkView + NetworkStreamControl + Send + Sync + Clone + 'static,
402{
403    pub fn config(&self) -> &config::HoprLibConfig {
404        &self.cfg
405    }
406
407    /// Returns a reference to the network graph.
408    pub fn graph(&self) -> &Graph {
409        self.transport_api.graph()
410    }
411
412    #[cfg(feature = "session-client")]
413    fn error_if_not_in_state(&self, state: HoprState, error: String) -> errors::Result<()> {
414        if HoprNodeOperations::status(self) == state {
415            Ok(())
416        } else {
417            Err(HoprLibError::NotReady(state, error))
418        }
419    }
420
421    #[cfg(feature = "session-client")]
422    async fn connect_to_with_transport_config(
423        &self,
424        destination: hopr_api::types::primitive::prelude::Address,
425        target: SessionTarget,
426        cfg: hopr_transport::SessionClientConfig,
427    ) -> Result<(HoprSession, HoprSessionConfigurator), HoprLibError> {
428        self.error_if_not_in_state(HoprState::Running, "Node is not ready for on-chain operations".into())?;
429
430        let backoff = backon::ConstantBuilder::default()
431            .with_max_times(self.cfg.protocol.session.establish_max_retries)
432            .with_delay(self.cfg.protocol.session.establish_retry_timeout)
433            .with_jitter();
434
435        use backon::Retryable;
436
437        Ok((|| {
438            let cfg = cfg.clone();
439            let target = target.clone();
440            async { self.transport_api.new_session(destination, target, cfg).await }
441        })
442        .retry(backoff)
443        .sleep(backon::FuturesTimerSleeper)
444        .await?)
445    }
446
447    /// Opens a session using explicit intermediate paths for forward and return routing.
448    #[cfg(all(feature = "session-client", feature = "explicit-path"))]
449    #[allow(deprecated)]
450    #[deprecated(
451        since = "4.0.2-rc.1",
452        note = "temporary compatibility API; remove once the explicit path is not needed anymore."
453    )]
454    pub async fn connect_to_using_explicit_path(
455        &self,
456        destination: hopr_api::types::primitive::prelude::Address,
457        target: SessionTarget,
458        cfg: HoprSessionClientExplicitPathConfig,
459    ) -> Result<(HoprSession, HoprSessionConfigurator), HoprLibError> {
460        let transport_cfg = hopr_transport::SessionClientConfig::try_from(cfg)
461            .map_err(|error| HoprLibError::GeneralError(error.to_string()))?;
462        self.connect_to_with_transport_config(destination, target, transport_cfg)
463            .await
464    }
465}
466
467#[cfg(feature = "session-client")]
468#[async_trait::async_trait]
469impl<Chain, Graph, Net, TMgr> hopr_api::node::HoprSessionClientOperations for Hopr<Chain, Graph, Net, TMgr>
470where
471    Chain: HoprChainApi + Clone + Send + Sync + 'static,
472    Graph: HoprGraphApi<HoprNodeId = OffchainPublicKey> + Clone + Send + Sync + 'static,
473    <Graph as hopr_api::graph::NetworkGraphTraverse>::Observed:
474        hopr_api::graph::traits::EdgeObservableRead + Send + 'static,
475    <Graph as hopr_api::graph::NetworkGraphWrite>::Observed: hopr_api::graph::traits::EdgeObservableWrite + Send,
476    Net: hopr_api::network::NetworkView + NetworkStreamControl + Send + Sync + Clone + 'static,
477    TMgr: Send + Sync + 'static,
478{
479    type Config = HoprSessionClientConfig;
480    type Error = HoprLibError;
481    type Session = HoprSession;
482    type SessionConfigurator = HoprSessionConfigurator;
483    type Target = SessionTarget;
484
485    async fn connect_to(
486        &self,
487        destination: hopr_api::types::primitive::prelude::Address,
488        target: Self::Target,
489        cfg: Self::Config,
490    ) -> Result<(Self::Session, Self::SessionConfigurator), Self::Error> {
491        self.connect_to_with_transport_config(destination, target, hopr_transport::SessionClientConfig::from(cfg))
492            .await
493    }
494}
495
496// ---------------------------------------------------------------------------
497// Has* accessor trait implementations
498// ---------------------------------------------------------------------------
499
500/// Maps [`Health`] into a [`ComponentStatus`] for a named component.
501fn network_health_to_status(health: Health, component: &str) -> ComponentStatus {
502    match health {
503        Health::Green | Health::Yellow => ComponentStatus::Ready,
504        Health::Orange => ComponentStatus::Degraded(format!("{component}: low connectivity (1 peer)").into()),
505        // Red is returned both for "zero peers" and "network not initialized"
506        Health::Red | Health::Unknown => {
507            ComponentStatus::Unavailable(format!("{component}: no connected peers").into())
508        }
509    }
510}
511
512impl<Chain, Graph, Net, TMgr> HasChainApi for Hopr<Chain, Graph, Net, TMgr>
513where
514    Chain: HoprChainApi + ComponentStatusReporter + Clone + Send + Sync + 'static,
515{
516    type ChainApi = Chain;
517    type ChainError = HoprLibError;
518
519    fn identity(&self) -> &NodeOnchainIdentity {
520        &self.chain_id
521    }
522
523    fn chain_api(&self) -> &Chain {
524        &self.chain_api
525    }
526
527    fn status(&self) -> ComponentStatus {
528        self.chain_api.component_status()
529    }
530
531    fn wait_for_on_chain_event<F>(
532        &self,
533        predicate: F,
534        context: String,
535        timeout: Duration,
536    ) -> EventWaitResult<<Self::ChainApi as HoprChainApi>::ChainError, Self::ChainError>
537    where
538        F: Fn(&ChainEvent) -> bool + Send + Sync + 'static,
539    {
540        debug!(%context, "registering wait for on-chain event");
541
542        // DropAbortable not needed because the stream only generates items when polled
543        let (event_stream, handle) = futures::stream::abortable(
544            self.chain_api
545                .subscribe()?
546                .skip_while(move |event| futures::future::ready(!predicate(event))),
547        );
548
549        let ctx = context.clone();
550
551        Ok((
552            spawn(async move {
553                pin_mut!(event_stream);
554                let res = event_stream
555                    .next()
556                    .timeout(futures_time::time::Duration::from(timeout))
557                    .map_err(|_| {
558                        HoprLibError::Timeout {
559                            context: format!("{ctx} (after {timeout:?})"),
560                        }
561                        .into_right()
562                    })
563                    .await?
564                    .ok_or(
565                        HoprLibError::GeneralError(format!("on-chain event stream for {ctx} ended unexpectedly"))
566                            .into_right(),
567                    );
568                debug!(%ctx, ?res, "on-chain event waiting done");
569                res
570            })
571            .map_err(move |_| {
572                HoprLibError::GeneralError(format!("failed to spawn on-chain event wait for {context}")).into_right()
573            })
574            .and_then(futures::future::ready)
575            .boxed(),
576            handle,
577        ))
578    }
579}
580
581impl<Chain, Graph, Net, TMgr> HasNetworkView for Hopr<Chain, Graph, Net, TMgr>
582where
583    Chain: Send + Sync + 'static,
584    Graph: Send + Sync + 'static,
585    Net: hopr_api::network::NetworkView + Send + Sync + 'static,
586{
587    type NetworkView = HoprTransport<Chain, Graph, Net>;
588
589    fn network_view(&self) -> &Self::NetworkView {
590        &self.transport_api
591    }
592
593    fn status(&self) -> ComponentStatus {
594        network_health_to_status(self.transport_api.health(), "network")
595    }
596}
597
598impl<Chain, Graph, Net, TMgr> HasGraphView for Hopr<Chain, Graph, Net, TMgr>
599where
600    Chain: HoprChainApi + Clone + Send + Sync + 'static,
601    Graph: HoprGraphApi<HoprNodeId = OffchainPublicKey>
602        + hopr_api::graph::NetworkGraphConnectivity<NodeId = OffchainPublicKey>
603        + Clone
604        + Send
605        + Sync
606        + 'static,
607    <Graph as hopr_api::graph::NetworkGraphTraverse>::Observed:
608        hopr_api::graph::traits::EdgeObservableRead + Send + 'static,
609    <Graph as hopr_api::graph::NetworkGraphWrite>::Observed: hopr_api::graph::traits::EdgeObservableWrite + Send,
610    Net: hopr_api::network::NetworkView + NetworkStreamControl + Send + Sync + Clone + 'static,
611{
612    type Graph = Graph;
613
614    fn graph(&self) -> &Graph {
615        self.transport_api.graph()
616    }
617
618    fn status(&self) -> ComponentStatus {
619        ComponentStatus::Ready
620    }
621}
622
623impl<Chain, Graph, Net, TMgr> HasTransportApi for Hopr<Chain, Graph, Net, TMgr>
624where
625    Chain: HoprChainApi + Clone + Send + Sync + 'static,
626    Graph: HoprGraphApi<HoprNodeId = OffchainPublicKey> + Clone + Send + Sync + 'static,
627    <Graph as hopr_api::graph::NetworkGraphTraverse>::Observed:
628        hopr_api::graph::traits::EdgeObservableRead + Send + 'static,
629    <Graph as hopr_api::graph::NetworkGraphWrite>::Observed: hopr_api::graph::traits::EdgeObservableWrite + Send,
630    Net: hopr_api::network::NetworkView + NetworkStreamControl + Send + Sync + Clone + 'static,
631    TMgr: Send + Sync + 'static,
632{
633    type Transport = HoprTransport<Chain, Graph, Net>;
634
635    fn transport(&self) -> &Self::Transport {
636        &self.transport_api
637    }
638
639    fn status(&self) -> ComponentStatus {
640        network_health_to_status(self.transport_api.health(), "transport")
641    }
642}
643
644// Available only on Relay nodes that specify `TMgr` that implements TicketManagement
645impl<Chain, Graph, Net, TMgr> HasTicketManagement for Hopr<Chain, Graph, Net, TMgr>
646where
647    Chain: HoprChainApi + Clone + Send + Sync + 'static,
648    TMgr: TicketManagement + Clone + Send + Sync + 'static,
649{
650    type TicketManager = TMgr;
651
652    fn ticket_management(&self) -> &TMgr {
653        &self.ticket_manager
654    }
655
656    fn subscribe_ticket_events(&self) -> impl Stream<Item = hopr_api::node::TicketEvent> + Send + 'static {
657        self.ticket_event_subscribers.1.activate_cloned()
658    }
659
660    fn status(&self) -> ComponentStatus {
661        ComponentStatus::Ready
662    }
663}
664
665impl<Chain, Graph, Net, TMgr> HasExitIncentivization for Hopr<Chain, Graph, Net, TMgr> {
666    fn subscribe_pix_events(&self) -> impl Stream<Item = PixEvent> + Send + 'static {
667        self.pix_event_subscribers.1.activate_cloned()
668    }
669
670    fn status(&self) -> ComponentStatus {
671        ComponentStatus::Ready
672    }
673}
674
675impl<Chain, Graph, Net, TMgr> hopr_api::node::ActionableEventSource for Hopr<Chain, Graph, Net, TMgr>
676where
677    Chain: HoprChainApi + Send + Sync + 'static,
678    Graph: Send + Sync + 'static,
679    Net: hopr_api::network::NetworkView + Send + Sync + 'static,
680    TMgr: Send + Sync + 'static,
681{
682    fn subscribe_to_actionable_events(
683        &self,
684        filter: Option<&[ActionableEventDiscriminant]>,
685    ) -> Result<futures::stream::BoxStream<'static, ActionableEvent>, String> {
686        let wants = |d: ActionableEventDiscriminant| filter.is_none_or(|f| f.contains(&d));
687
688        let mut streams = Vec::<futures::stream::BoxStream<'static, ActionableEvent>>::new();
689
690        if wants(ActionableEventDiscriminant::Chain) {
691            streams.push(
692                self.chain_api
693                    .subscribe()
694                    .map_err(|e| e.to_string())?
695                    .map(ActionableEvent::Chain)
696                    .boxed(),
697            );
698        }
699
700        if wants(ActionableEventDiscriminant::Network) {
701            streams.push(
702                self.transport_api
703                    .subscribe_network_events()
704                    .map(ActionableEvent::Network)
705                    .boxed(),
706            );
707        }
708
709        if wants(ActionableEventDiscriminant::Ticket) {
710            streams.push(
711                self.ticket_event_subscribers
712                    .1
713                    .activate_cloned()
714                    .map(ActionableEvent::Ticket)
715                    .boxed(),
716            );
717        }
718
719        if wants(ActionableEventDiscriminant::Pix) {
720            streams.push(
721                self.pix_event_subscribers
722                    .1
723                    .activate_cloned()
724                    .map(ActionableEvent::Pix)
725                    .boxed(),
726            );
727        }
728
729        if streams.is_empty() {
730            return Ok(futures::stream::empty().boxed());
731        }
732
733        // `Merge` provides fair polling distribution across active sources.
734        Ok(streams.merge().boxed())
735    }
736}
737
738/// Per-component status report for the HOPR node.
739#[derive(Debug, Clone)]
740pub struct NodeComponentStatuses {
741    /// Overall node lifecycle state.
742    pub node_state: HoprState,
743    /// Chain/blokli connector status.
744    pub chain: ComponentStatus,
745    /// P2P network layer status.
746    pub network: ComponentStatus,
747    /// Transport layer status.
748    pub transport: ComponentStatus,
749}
750
751impl NodeComponentStatuses {
752    /// Worst-case aggregation: the overall status is the worst of any component.
753    pub fn aggregate(&self) -> ComponentStatus {
754        let statuses = [&self.chain, &self.network, &self.transport];
755        if statuses.iter().any(|s| s.is_unavailable()) {
756            ComponentStatus::Unavailable("one or more components unavailable".into())
757        } else if statuses.iter().any(|s| s.is_degraded()) {
758            ComponentStatus::Degraded("one or more components degraded".into())
759        } else if statuses.iter().any(|s| s.is_initializing()) {
760            ComponentStatus::Initializing("one or more components initializing".into())
761        } else {
762            ComponentStatus::Ready
763        }
764    }
765}
766
767impl<Chain, Graph, Net, TMgr> Hopr<Chain, Graph, Net, TMgr>
768where
769    Chain: HoprChainApi + ComponentStatusReporter + Clone + Send + Sync + 'static,
770    Net: hopr_api::network::NetworkView + NetworkStreamControl + Send + Sync + Clone + 'static,
771    Graph: HoprGraphApi<HoprNodeId = OffchainPublicKey>
772        + hopr_api::graph::NetworkGraphConnectivity<NodeId = OffchainPublicKey>
773        + Clone
774        + Send
775        + Sync
776        + 'static,
777    <Graph as hopr_api::graph::NetworkGraphTraverse>::Observed:
778        hopr_api::graph::traits::EdgeObservableRead + Send + 'static,
779    <Graph as hopr_api::graph::NetworkGraphWrite>::Observed: hopr_api::graph::traits::EdgeObservableWrite + Send,
780    TMgr: Send + Sync + 'static,
781{
782    /// Returns per-component health statuses for the node.
783    ///
784    /// When the node has reached `Running`, the aggregate `node_state` is
785    /// derived from component statuses (Running → Degraded → Failed).
786    pub fn component_statuses(&self) -> NodeComponentStatuses {
787        let base = self.state.load(Ordering::Relaxed);
788        let statuses = NodeComponentStatuses {
789            node_state: base,
790            chain: HasChainApi::status(self),
791            network: HasNetworkView::status(self),
792            transport: HasTransportApi::status(self),
793        };
794
795        // Derive aggregate HoprState from component statuses once Running
796        if base == HoprState::Running {
797            NodeComponentStatuses {
798                node_state: match statuses.aggregate() {
799                    ComponentStatus::Unavailable(_) => HoprState::Failed,
800                    ComponentStatus::Degraded(_) | ComponentStatus::Initializing(_) => HoprState::Degraded,
801                    ComponentStatus::Ready => HoprState::Running,
802                },
803                ..statuses
804            }
805        } else {
806            statuses
807        }
808    }
809}
810
811impl<Chain, Graph, Net, TMgr> HoprNodeOperations for Hopr<Chain, Graph, Net, TMgr> {
812    fn status(&self) -> HoprState {
813        self.state.load(Ordering::Relaxed)
814    }
815}
816
817impl<Chain, Graph, Net, TMgr> hopr_api::node::PacketTransport for Hopr<Chain, Graph, Net, TMgr> {
818    fn packet_payload_size() -> usize {
819        hopr_transport::PACKET_PAYLOAD_SIZE
820    }
821}
822
823/// Prometheus-formatted metrics collected by the hopr-lib components.
824///
825/// Only available when compiled with the `telemetry` feature.
826#[cfg(feature = "telemetry")]
827pub fn collect_hopr_metrics() -> errors::Result<String> {
828    hopr_api::types::telemetry::gather_all_metrics().map_err(HoprLibError::other)
829}
830
831/// Converts a PeerId to an OffchainPublicKey.
832///
833/// This is a standalone utility function, not part of the API traits.
834pub fn peer_id_to_offchain_key(peer_id: &PeerId) -> errors::Result<OffchainPublicKey> {
835    Ok(hopr_transport::peer_id_to_public_key(peer_id)?)
836}
837
838#[cfg(test)]
839mod tests {
840    use super::*;
841
842    #[test]
843    fn network_health_green_is_ready() {
844        assert_eq!(network_health_to_status(Health::Green, "test"), ComponentStatus::Ready);
845    }
846
847    #[test]
848    fn network_health_yellow_is_ready() {
849        assert_eq!(network_health_to_status(Health::Yellow, "test"), ComponentStatus::Ready);
850    }
851
852    #[test]
853    fn network_health_orange_is_degraded() {
854        assert!(network_health_to_status(Health::Orange, "network").is_degraded());
855    }
856
857    #[test]
858    fn network_health_red_is_unavailable() {
859        assert!(network_health_to_status(Health::Red, "network").is_unavailable());
860    }
861
862    #[test]
863    fn network_health_unknown_is_unavailable() {
864        assert!(network_health_to_status(Health::Unknown, "network").is_unavailable());
865    }
866
867    #[test]
868    fn aggregate_all_ready() {
869        let statuses = NodeComponentStatuses {
870            node_state: HoprState::Running,
871            chain: ComponentStatus::Ready,
872            network: ComponentStatus::Ready,
873            transport: ComponentStatus::Ready,
874        };
875        assert_eq!(statuses.aggregate(), ComponentStatus::Ready);
876    }
877
878    #[test]
879    fn aggregate_one_degraded() {
880        let statuses = NodeComponentStatuses {
881            node_state: HoprState::Running,
882            chain: ComponentStatus::Ready,
883            network: ComponentStatus::Degraded("low peers".into()),
884            transport: ComponentStatus::Ready,
885        };
886        assert!(statuses.aggregate().is_degraded());
887    }
888
889    #[test]
890    fn aggregate_one_unavailable() {
891        let statuses = NodeComponentStatuses {
892            node_state: HoprState::Running,
893            chain: ComponentStatus::Unavailable("blokli down".into()),
894            network: ComponentStatus::Ready,
895            transport: ComponentStatus::Ready,
896        };
897        assert!(statuses.aggregate().is_unavailable());
898    }
899
900    #[test]
901    fn aggregate_unavailable_wins_over_degraded() {
902        let statuses = NodeComponentStatuses {
903            node_state: HoprState::Running,
904            chain: ComponentStatus::Unavailable("blokli down".into()),
905            network: ComponentStatus::Degraded("low peers".into()),
906            transport: ComponentStatus::Ready,
907        };
908        assert!(statuses.aggregate().is_unavailable());
909    }
910
911    #[test]
912    fn aggregate_one_initializing() {
913        let statuses = NodeComponentStatuses {
914            node_state: HoprState::Running,
915            chain: ComponentStatus::Initializing("starting".into()),
916            network: ComponentStatus::Ready,
917            transport: ComponentStatus::Ready,
918        };
919        assert!(statuses.aggregate().is_initializing());
920    }
921
922    #[test]
923    fn aggregate_degraded_wins_over_initializing() {
924        let statuses = NodeComponentStatuses {
925            node_state: HoprState::Running,
926            chain: ComponentStatus::Initializing("starting".into()),
927            network: ComponentStatus::Degraded("low peers".into()),
928            transport: ComponentStatus::Ready,
929        };
930        assert!(statuses.aggregate().is_degraded());
931    }
932
933    #[test]
934    fn network_health_to_status_includes_component_name() {
935        match network_health_to_status(Health::Orange, "mycomp") {
936            ComponentStatus::Degraded(d) => assert!(d.contains("mycomp"), "detail should contain component name"),
937            other => panic!("expected Degraded, got {other:?}"),
938        }
939    }
940
941    #[test]
942    fn network_health_to_status_red_and_unknown_are_same_variant() {
943        let red = network_health_to_status(Health::Red, "x");
944        let unknown = network_health_to_status(Health::Unknown, "x");
945        assert!(red.is_unavailable());
946        assert!(unknown.is_unavailable());
947    }
948
949    #[cfg(all(feature = "session-client", feature = "explicit-path"))]
950    #[allow(deprecated)]
951    #[test]
952    fn explicit_path_config_converts_into_intermediate_path_routing_options() -> anyhow::Result<()> {
953        use anyhow::Context as _;
954        use hopr_transport::Keypair;
955
956        let k1 = hopr_api::types::internal::NodeId::from(*OffchainKeypair::random().public());
957        let k2 = hopr_api::types::internal::NodeId::from(*OffchainKeypair::random().public());
958        let k3 = hopr_api::types::internal::NodeId::from(*OffchainKeypair::random().public());
959
960        let cfg = hopr_transport::SessionClientConfig::try_from(HoprSessionClientExplicitPathConfig {
961            forward_path: vec![k1, k2],
962            return_path: vec![k3],
963            capabilities: SessionCapability::Segmentation.into(),
964            pseudonym: None,
965            surb_management: None,
966            max_surbs_per_data_packet: 1,
967            flow_control: None,
968            max_frames_behind_gap: Some(8),
969        })
970        .context("explicit path config conversion must succeed")?;
971
972        assert_eq!(
973            cfg.max_frames_behind_gap,
974            Some(8),
975            "the session's head-of-line bound has to survive the conversion, or it silently reverts to the node \
976             default"
977        );
978        assert!(matches!(
979            cfg.forward_path_options,
980            hopr_transport::RoutingOptions::IntermediatePath(_)
981        ));
982        assert!(matches!(
983            cfg.return_path_options,
984            hopr_transport::RoutingOptions::IntermediatePath(_)
985        ));
986        Ok(())
987    }
988}