1mod helpers;
17
18pub mod builder;
20pub mod config;
22pub mod constants;
24pub mod errors;
26#[cfg(feature = "state-dump")]
28pub mod state_dump;
29#[cfg(feature = "testing")]
31pub mod testing;
32pub mod utils;
34
35pub use hopr_api as api;
36
37#[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};
72pub use hopr_transport::SESSION_MTU;
77pub 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#[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 pub const MAX_HOPS: usize = hopr_api::types::internal::routing::RoutingOptions::MAX_INTERMEDIATE_HOPS;
112
113 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#[cfg(feature = "session-client")]
147#[derive(Debug, Clone, PartialEq, smart_default::SmartDefault)]
148pub struct HoprSessionClientConfig {
149 pub forward_path: HopRouting,
151 pub return_path: HopRouting,
153 #[default(_code = "SessionCapability::Segmentation.into()")]
155 pub capabilities: SessionCapabilities,
156 #[default(None)]
158 pub pseudonym: Option<hopr_api::types::internal::protocol::HoprPseudonym>,
159 #[default(Some(SurbBalancerConfig::default()))]
161 pub surb_management: Option<SurbBalancerConfig>,
162 #[default(1)]
174 pub max_surbs_per_data_packet: usize,
175 #[default(None)]
179 pub flow_control: Option<FlowControlConfig>,
180 pub max_frames_behind_gap: Option<usize>,
193}
194
195#[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 pub forward_path: Vec<hopr_api::types::internal::NodeId>,
205 pub return_path: Vec<hopr_api::types::internal::NodeId>,
207 pub capabilities: SessionCapabilities,
209 pub pseudonym: Option<hopr_api::types::internal::protocol::HoprPseudonym>,
211 pub surb_management: Option<SurbBalancerConfig>,
213 pub max_surbs_per_data_packet: usize,
215 pub flow_control: Option<FlowControlConfig>,
217 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#[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)] SessionServer,
285 #[strum(to_string = "session server deciding the terms incoming sessions are admitted on")]
286 #[allow(dead_code)] 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#[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
339pub 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
355const NODE_READY_TIMEOUT: Duration = Duration::from_secs(120);
357
358pub 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)] 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 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 #[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
496fn 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 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 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
644impl<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 Ok(streams.merge().boxed())
735 }
736}
737
738#[derive(Debug, Clone)]
740pub struct NodeComponentStatuses {
741 pub node_state: HoprState,
743 pub chain: ComponentStatus,
745 pub network: ComponentStatus,
747 pub transport: ComponentStatus,
749}
750
751impl NodeComponentStatuses {
752 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 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 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#[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
831pub 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}