Skip to main content

hopr_transport_probe/
probe.rs

1use std::sync::Arc;
2
3use futures::{FutureExt, SinkExt, StreamExt};
4use futures_concurrency::stream::StreamExt as _;
5use hopr_api::{
6    ct::{ProbeRouting, ProbingTrafficGeneration},
7    graph::{EdgeTransportTelemetry, NetworkGraphError, NetworkGraphUpdate, NetworkGraphView},
8    types::{
9        crypto::types::OffchainPublicKey, crypto_random::Randomizable, internal::prelude::*,
10        primitive::traits::AsUnixTimestamp,
11    },
12};
13use hopr_protocol_app::{
14    prelude::{ApplicationDataIn, ApplicationDataOut, OutgoingPacketInfo, ReservedTag},
15    v1::Tag,
16};
17use hopr_transport_tag_allocator::{AllocatedTag, TagAllocator};
18use hopr_utils::{platform::time::native::current_time, runtime::AbortableList};
19
20use crate::{
21    HoprProbeProcess,
22    config::ProbeConfig,
23    content::Message,
24    ping::PingQueryReplier,
25    types::{NeighborProbe, NeighborTelemetry, PathTelemetry},
26};
27
28type CacheNeighborKey = (HoprPseudonym, NeighborProbe);
29type CacheNeighborValue = (Box<NodeId>, std::time::Duration, Option<PingQueryReplier>);
30
31/// Result of classifying one incoming message through the probe layer.
32pub enum ProbeDispatch {
33    /// The message was a probe message and has been consumed internally.
34    Consumed,
35    /// The message was not related to probing; caller should route it further.
36    Passthrough(HoprPseudonym, ApplicationDataIn),
37}
38
39/// Shared state used to classify incoming messages as probe or non-probe.
40///
41/// Obtained from [`Probe::continuously_scan`]. Use [`filter_stream`](ProbeClassifierState::filter_stream)
42/// to wrap an incoming stream so that probe messages are consumed internally and non-probe messages
43/// are yielded to the caller.
44#[derive(Clone)]
45pub struct ProbeClassifierState<G> {
46    active_neighbor_probes: moka::future::Cache<CacheNeighborKey, CacheNeighborValue>,
47    active_path_probes: moka::future::Cache<Tag, (PathTelemetry, Arc<AllocatedTag>)>,
48    network_graph: G,
49}
50
51impl<G> ProbeClassifierState<G>
52where
53    G: NetworkGraphUpdate + Clone + Send + Sync + 'static,
54{
55    /// Classify one incoming `(pseudonym, data)` pair.
56    ///
57    /// The `push_to_network` sink is used to send pong replies when the message is a Ping.
58    /// Returns `Consumed` if the message was a probe, or `Passthrough` for all other messages.
59    pub async fn classify<T>(
60        &self,
61        mut push_to_network: T,
62        pseudonym: HoprPseudonym,
63        in_data: ApplicationDataIn,
64    ) -> ProbeDispatch
65    where
66        T: futures::Sink<(DestinationRouting, ApplicationDataOut)> + Unpin + Send + 'static,
67        T::Error: Send,
68    {
69        let tag: Tag = in_data.data.application_tag;
70
71        if let Some((path_telemetry, _allocated_tag)) = self.active_path_probes.remove(&tag).await {
72            tracing::debug!(%tag, "loopback probe successfully received");
73            self.network_graph
74                .record_edge::<NeighborTelemetry, PathTelemetry>(hopr_api::graph::MeasurableEdge::Probe(Ok(
75                    EdgeTransportTelemetry::Loopback(path_telemetry),
76                )));
77        } else if tag == ReservedTag::Ping.into() {
78            let message: anyhow::Result<Message> = in_data
79                .data
80                .try_into()
81                .map_err(|e| anyhow::anyhow!("failed to convert data into message: {e}"));
82
83            match message {
84                Ok(message) => match message {
85                    Message::Telemetry(_) => {
86                        tracing::warn!(%pseudonym, "received telemetry on reserved ping tag, ignoring");
87                    }
88                    Message::Probe(NeighborProbe::Ping(ping)) => {
89                        tracing::debug!(%pseudonym, nonce = const_hex::encode(ping), "received ping");
90                        tracing::trace!(%pseudonym, nonce = const_hex::encode(ping), "wrapping a pong in the found SURB");
91
92                        let message = Message::Probe(NeighborProbe::Pong(ping));
93                        if let Ok(data) = message.try_into() {
94                            let routing = DestinationRouting::Return(pseudonym.into());
95                            let data = ApplicationDataOut::with_no_packet_info(data);
96                            if let Err(_error) = push_to_network.send((routing, data)).await {
97                                tracing::error!(%pseudonym, "failed to send back a pong");
98                            }
99                        } else {
100                            tracing::error!(%pseudonym, "failed to convert pong message into data");
101                        }
102                    }
103                    Message::Probe(NeighborProbe::Pong(pong)) => {
104                        tracing::debug!(%pseudonym, nonce = const_hex::encode(pong), "received pong");
105                        if let Some((peer, start, replier)) = self
106                            .active_neighbor_probes
107                            .remove(&(pseudonym, NeighborProbe::Ping(pong)))
108                            .await
109                        {
110                            let latency = current_time().as_unix_timestamp().saturating_sub(start);
111
112                            if let NodeId::Offchain(opk) = peer.as_ref() {
113                                tracing::debug!(%pseudonym, nonce = const_hex::encode(pong), latency_ms = latency.as_millis(), "probe successful");
114                                self.network_graph.record_edge::<NeighborTelemetry, PathTelemetry>(
115                                    hopr_api::graph::MeasurableEdge::Probe(Ok(EdgeTransportTelemetry::Neighbor(
116                                        NeighborTelemetry {
117                                            peer: *opk,
118                                            rtt: latency,
119                                        },
120                                    ))),
121                                )
122                            } else {
123                                tracing::warn!(%pseudonym, nonce = const_hex::encode(pong), latency_ms = latency.as_millis(), "probe successful to non-offchain peer");
124                            }
125
126                            if let Some(replier) = replier {
127                                replier.notify(Ok(latency));
128                            }
129                        } else {
130                            tracing::warn!(%pseudonym, nonce = const_hex::encode(pong), possible_reasons = "[timeout, adversary]", "received pong for unknown probe");
131                        }
132                    }
133                },
134                Err(error) => tracing::error!(%pseudonym, %error, "cannot deserialize message"),
135            }
136        } else {
137            return ProbeDispatch::Passthrough(pseudonym, in_data);
138        }
139
140        ProbeDispatch::Consumed
141    }
142
143    /// Wraps `stream` as an in-place filter: probe messages are handled internally (telemetry,
144    /// pong replies via `push_to_network`), non-probe messages are yielded.
145    pub fn filter_stream<T, S>(
146        self,
147        push_to_network: T,
148        stream: S,
149    ) -> impl futures::Stream<Item = (HoprPseudonym, ApplicationDataIn)>
150    where
151        T: futures::Sink<(DestinationRouting, ApplicationDataOut)> + Clone + Unpin + Send + Sync + 'static,
152        T::Error: Send,
153        S: futures::Stream<Item = (HoprPseudonym, ApplicationDataIn)>,
154    {
155        use futures::StreamExt;
156        stream.filter_map(move |(pseudonym, data)| {
157            let state = self.clone();
158            let push = push_to_network.clone();
159            async move {
160                match state.classify(push, pseudonym, data).await {
161                    ProbeDispatch::Consumed => None,
162                    ProbeDispatch::Passthrough(ps, d) => Some((ps, d)),
163                }
164            }
165        })
166    }
167}
168
169/// Probe functionality builder.
170///
171/// The builder holds information about this node's own addresses and the configuration for the probing process. It is
172/// then used to construct the probing process itself.
173pub struct Probe {
174    /// Probe configuration.
175    cfg: ProbeConfig,
176    /// Tag allocator for probing telemetry tags.
177    tag_allocator: Arc<dyn TagAllocator + Send + Sync>,
178}
179
180impl Probe {
181    pub fn new(cfg: ProbeConfig, tag_allocator: Arc<dyn TagAllocator + Send + Sync>) -> Self {
182        Self { cfg, tag_allocator }
183    }
184
185    /// The main function that assembles and starts the probing process.
186    ///
187    /// Returns the abortable list of background tasks (probe emission) and a
188    /// [`ProbeClassifierState`] for inline classification of incoming messages.
189    /// Use [`ProbeClassifierState::filter_stream`] to wrap the incoming stream.
190    pub async fn continuously_scan<T, V, Tr, G>(
191        self,
192        api_out: T,       // lower tx channel for sending outgoing probes and pong replies
193        manual_events: V, // explicit requests from the API
194        probing_traffic_generator: Tr,
195        network_graph: G,
196    ) -> (AbortableList<HoprProbeProcess>, ProbeClassifierState<G>)
197    where
198        T: futures::Sink<(DestinationRouting, ApplicationDataOut)> + Clone + Send + Sync + Unpin + 'static,
199        T::Error: Send,
200        V: futures::Stream<Item = (OffchainPublicKey, PingQueryReplier)> + Send + 'static,
201        Tr: ProbingTrafficGeneration + Send + Sync + 'static,
202        G: NetworkGraphView + NetworkGraphUpdate + Clone + Send + Sync + 'static,
203    {
204        let max_parallel_probes = self.cfg.max_parallel_probes;
205
206        let probing_routes = probing_traffic_generator.build();
207
208        // Currently active probes
209        let network_graph_internal_neighbor = network_graph.clone();
210        let network_graph_internal_path = network_graph.clone();
211        let timeout = self.cfg.timeout;
212        let active_neighbor_probes: moka::future::Cache<CacheNeighborKey, CacheNeighborValue> =
213            moka::future::Cache::builder()
214                .time_to_live(timeout)
215                .max_capacity(100_000)
216                .async_eviction_listener(
217                    move |k: Arc<CacheNeighborKey>,
218                          v: CacheNeighborValue,
219                          cause|
220                          -> moka::notification::ListenerFuture {
221                        if matches!(cause, moka::notification::RemovalCause::Expired) {
222                            // If the eviction cause is expiration => record as a failed probe
223                            let store = network_graph_internal_neighbor.clone();
224                            let (peer, _start, notifier) = v;
225
226                            tracing::debug!(%peer, pseudonym = %k.0, probe = %k.1, reason = "timeout", "neighbor probe failed");
227                            if let Some(replier) = notifier {
228                                if matches!(peer.as_ref(), NodeId::Offchain(_)) {
229                                    replier.notify(Err(()));
230                                } else {
231                                    tracing::warn!(
232                                        reason = "non-offchain peer",
233                                        "cannot notify timeout for non-offchain peer"
234                                    );
235                                }
236                            };
237
238                            if let NodeId::Offchain(opk) = peer.as_ref() {
239                                let opk: OffchainPublicKey = *opk;
240                                store
241                                    .record_edge::<NeighborTelemetry, PathTelemetry>(
242                                        hopr_api::graph::MeasurableEdge::Probe(Err(
243                                            NetworkGraphError::ProbeNeighborTimeout(Box::new(opk)),
244                                        )),
245                                    );
246                                futures::FutureExt::boxed(futures::future::ready(()))
247
248                            } else {
249                                futures::FutureExt::boxed(futures::future::ready(()))
250                            }
251                        } else {
252                            // If the eviction cause is not expiration, nothing needs to be done
253                            futures::FutureExt::boxed(futures::future::ready(()))
254                        }
255                    },
256                )
257                .build();
258
259        let active_path_probes: moka::future::Cache<Tag, (PathTelemetry, Arc<AllocatedTag>)> =
260            moka::future::Cache::builder()
261                .time_to_live(timeout)
262                .max_capacity(100_000)
263                .async_eviction_listener(
264                    move |tag: Arc<Tag>,
265                          (path, _allocated_tag): (PathTelemetry, Arc<AllocatedTag>),
266                          cause|
267                          -> moka::notification::ListenerFuture {
268                        if matches!(cause, moka::notification::RemovalCause::Expired) {
269                            // If the eviction cause is expiration => record as a failed probe
270                            let store = network_graph_internal_path.clone();
271
272                            tracing::debug!(%tag, reason = "timeout", "loopback probe failed");
273
274                            store.record_edge::<NeighborTelemetry, PathTelemetry>(
275                                hopr_api::graph::MeasurableEdge::Probe(Err(NetworkGraphError::ProbeLoopbackTimeout(
276                                    path,
277                                ))),
278                            );
279                            futures::FutureExt::boxed(futures::future::ready(()))
280                        } else {
281                            // If the eviction cause is not expiration, nothing needs to be done
282                            futures::FutureExt::boxed(futures::future::ready(()))
283                        }
284                    },
285                )
286                .build();
287
288        let push_to_network = api_out.clone();
289
290        let mut processes = AbortableList::default();
291
292        // -- Emit probes --
293        let direct_neighbors =
294            probing_routes
295                .map(|peer| (peer, None))
296                .merge(manual_events.filter_map(|(peer, notifier)| async move {
297                    let routing = DestinationRouting::Forward {
298                        destination: Box::new(peer.into()),
299                        pseudonym: Some(HoprPseudonym::random()),
300                        forward_options: RoutingOptions::Hops(0.try_into().expect("0 is a valid u8")),
301                        return_options: Some(RoutingOptions::Hops(0.try_into().expect("0 is a valid u8"))),
302                    };
303                    Some((ProbeRouting::Neighbor(routing), Some(notifier)))
304                }));
305
306        let tag_allocator = self.tag_allocator.clone();
307        let classifier_neighbor_probes = active_neighbor_probes.clone();
308        let classifier_path_probes = active_path_probes.clone();
309        let emit_diag = hopr_utils::runtime::diagnostics::ConcurrentDiagnostics::new(
310            "probe_emit_for_each_concurrent",
311            module_path!(),
312            file!(),
313            line!(),
314        );
315        processes.insert(
316            HoprProbeProcess::Emit,
317            hopr_utils::spawn_as_abortable_named!("probe_emit", async move {
318                direct_neighbors
319                    .for_each_concurrent(max_parallel_probes, move |(peer, notifier)| {
320                        let active_neighbor_probes = active_neighbor_probes.clone();
321                        let active_path_probes = active_path_probes.clone();
322                        let push_to_network = push_to_network.clone();
323                        let tag_allocator = tag_allocator.clone();
324                        let emit_diag = emit_diag.clone();
325
326                        emit_diag.wrap(|| async move {
327                            match peer {
328                                ProbeRouting::Neighbor(DestinationRouting::Forward {
329                                    destination,
330                                    pseudonym,
331                                    forward_options,
332                                    return_options,
333                                }) => {
334                                    let nonce = NeighborProbe::random_nonce();
335
336                                    let message = Message::Probe(nonce);
337
338                                    if let Ok(data) = message.try_into() {
339                                        let routing = DestinationRouting::Forward {
340                                            destination: destination.clone(),
341                                            pseudonym,
342                                            forward_options,
343                                            return_options,
344                                        };
345                                        // Neighbor probes are sent to a direct neighbor and returned via a zero-hop
346                                        // return path: only 1 SURB is ever consumed. See hoprnet/hoprnet#7972.
347                                        let data = ApplicationDataOut {
348                                            data,
349                                            packet_info: Some(OutgoingPacketInfo {
350                                                max_surbs_in_packet: 1,
351                                                ..Default::default()
352                                            }),
353                                        };
354                                        let mut push_to_network = push_to_network.clone();
355
356                                        if let Err(_error) = push_to_network.send((routing, data)).await {
357                                            tracing::error!("failed to send out a ping");
358                                        } else {
359                                            active_neighbor_probes
360                                                .insert(
361                                                    (
362                                                        pseudonym
363                                                            .expect("the pseudonym must be present in Forward routing"),
364                                                        nonce,
365                                                    ),
366                                                    (destination, current_time().as_unix_timestamp(), notifier),
367                                                )
368                                                .await;
369                                        }
370                                    } else {
371                                        tracing::error!("failed to convert ping message into data");
372                                    }
373                                }
374                                ProbeRouting::Neighbor(DestinationRouting::Return(_surb_matcher)) => tracing::error!(
375                                    error = "logical error",
376                                    "resolved transport routing is not forward"
377                                ),
378                                ProbeRouting::Looping((routing, path_id)) => {
379                                    let message = Message::Telemetry(PathTelemetry {
380                                        id: hopr_api::types::crypto_random::random_bytes(),
381                                        path: std::array::from_fn(|i| path_id[i / 8].to_le_bytes()[i % 8]),
382                                        timestamp: std::time::SystemTime::now()
383                                            .duration_since(std::time::UNIX_EPOCH)
384                                            .unwrap_or_default()
385                                            .as_millis(),
386                                    });
387
388                                    if let Some(allocated_tag) = tag_allocator.allocate() {
389                                        let tag_value = allocated_tag.value();
390
391                                        if let Ok(packet) = hopr_protocol_app::prelude::ApplicationData::new(
392                                            tag_value,
393                                            message.to_bytes().as_ref(),
394                                        ) {
395                                            let mut push_to_network = push_to_network.clone();
396
397                                            // Loopback telemetry probes are self-routed and never replied to via
398                                            // SURB, so no SURBs should be bundled. See hoprnet/hoprnet#7972.
399                                            if let Err(_error) = push_to_network
400                                                .send((
401                                                    routing,
402                                                    ApplicationDataOut {
403                                                        data: packet,
404                                                        packet_info: Some(OutgoingPacketInfo {
405                                                            max_surbs_in_packet: 0,
406                                                            ..Default::default()
407                                                        }),
408                                                    },
409                                                ))
410                                                .await
411                                            {
412                                                tracing::error!("failed to send out a ping");
413                                            } else {
414                                                // the object is constructed above, so will always match
415                                                if let Message::Telemetry(telemetry) = message {
416                                                    active_path_probes
417                                                        .insert(tag_value.into(), (telemetry, Arc::new(allocated_tag)))
418                                                        .await;
419                                                }
420                                            }
421                                        } else {
422                                            tracing::error!("failed to construct data for path telemetry")
423                                        }
424                                    } else {
425                                        tracing::warn!("probing telemetry tag pool exhausted, skipping loopback probe");
426                                    }
427                                }
428                            }
429                        })
430                    })
431                    .inspect(|_| {
432                        tracing::warn!(
433                            task = "transport (probe - generate outgoing)",
434                            "long-running background task finished"
435                        )
436                    })
437                    .await;
438            }),
439        );
440
441        let classifier = ProbeClassifierState {
442            active_neighbor_probes: classifier_neighbor_probes,
443            active_path_probes: classifier_path_probes,
444            network_graph,
445        };
446
447        (processes, classifier)
448    }
449}
450
451#[cfg(test)]
452mod tests {
453    use std::{collections::VecDeque, sync::RwLock, time::Duration};
454
455    use async_trait::async_trait;
456    use futures::future::BoxFuture;
457    use hopr_api::{
458        graph::{
459            EdgeLinkObservable, MeasurableEdge, NetworkGraphError,
460            traits::{EdgeNetworkObservableRead, EdgeObservableRead, EdgeObservableWrite, EdgeProtocolObservable},
461        },
462        types::crypto::keypairs::{ChainKeypair, Keypair, OffchainKeypair},
463    };
464    use hopr_protocol_app::prelude::{ApplicationData, ReservedTag, Tag};
465
466    use super::*;
467    use crate::errors::ProbeError;
468
469    lazy_static::lazy_static!(
470        static ref OFFCHAIN_KEYPAIR: OffchainKeypair = OffchainKeypair::random();
471        static ref ONCHAIN_KEYPAIR: ChainKeypair = ChainKeypair::random();
472        static ref NEIGHBOURS: Vec<OffchainPublicKey> = vec![
473            *OffchainKeypair::random().public(),
474            *OffchainKeypair::random().public(),
475            *OffchainKeypair::random().public(),
476            *OffchainKeypair::random().public(),
477        ];
478    );
479
480    /// Test stub implementation of Observable.
481    #[derive(Debug, Clone, Copy, Default)]
482    pub struct TestEdgeTransportObservations;
483
484    impl EdgeLinkObservable for TestEdgeTransportObservations {
485        fn record(&mut self, _latency: std::result::Result<Duration, ()>) {}
486
487        fn average_latency(&self) -> Option<Duration> {
488            None
489        }
490
491        fn average_probe_rate(&self) -> f64 {
492            1.0
493        }
494
495        fn score(&self) -> f64 {
496            1.0
497        }
498    }
499
500    impl EdgeNetworkObservableRead for TestEdgeTransportObservations {
501        fn is_connected(&self) -> bool {
502            true
503        }
504    }
505
506    impl EdgeProtocolObservable for TestEdgeTransportObservations {
507        fn capacity(&self) -> Option<u128> {
508            None
509        }
510    }
511
512    impl hopr_api::graph::EdgeImmediateProtocolObservable for TestEdgeTransportObservations {
513        fn ack_rate(&self) -> Option<f64> {
514            None
515        }
516    }
517
518    #[derive(Debug, Clone, Copy, Default)]
519    pub struct TestEdgeObservations;
520
521    impl EdgeObservableWrite for TestEdgeObservations {
522        fn record(&mut self, _measurement: hopr_api::graph::traits::EdgeWeightType) {}
523    }
524
525    impl EdgeObservableRead for TestEdgeObservations {
526        type ImmediateMeasurement = TestEdgeTransportObservations;
527        type IntermediateMeasurement = TestEdgeTransportObservations;
528
529        fn last_update(&self) -> std::time::Duration {
530            std::time::SystemTime::now()
531                .duration_since(std::time::UNIX_EPOCH)
532                .unwrap_or_default()
533        }
534
535        fn immediate_qos(&self) -> Option<&Self::ImmediateMeasurement> {
536            None
537        }
538
539        fn intermediate_qos(&self) -> Option<&Self::IntermediateMeasurement> {
540            None
541        }
542
543        fn score(&self) -> f64 {
544            1.0
545        }
546    }
547
548    #[derive(Debug, Clone)]
549    pub struct PeerStore {
550        me: OffchainPublicKey,
551        get_peers: Arc<RwLock<VecDeque<Vec<OffchainPublicKey>>>>,
552        #[allow(clippy::type_complexity)]
553        on_finished: Arc<RwLock<Vec<(OffchainPublicKey, crate::errors::Result<Duration>)>>>,
554    }
555
556    impl NetworkGraphUpdate for PeerStore {
557        fn record_edge<N, P>(&self, telemetry: MeasurableEdge<N, P>)
558        where
559            N: hopr_api::graph::MeasurablePeer + Send + Clone,
560            P: hopr_api::graph::MeasurablePath + Send + Clone,
561        {
562            let mut on_finished = self.on_finished.write().unwrap();
563
564            match telemetry {
565                hopr_api::graph::MeasurableEdge::Probe(Ok(EdgeTransportTelemetry::Neighbor(neighbor_telemetry))) => {
566                    let peer: OffchainPublicKey = *neighbor_telemetry.peer();
567                    let duration = neighbor_telemetry.rtt();
568                    on_finished.push((peer, Ok(duration)));
569                }
570                hopr_api::graph::MeasurableEdge::Probe(Err(NetworkGraphError::ProbeNeighborTimeout(peer))) => {
571                    on_finished.push((
572                        *peer.as_ref(),
573                        Err(ProbeError::TrafficError(NetworkGraphError::ProbeNeighborTimeout(peer))),
574                    ));
575                }
576                _ => panic!("unexpected telemetry type, unimplemented"),
577            }
578        }
579
580        fn record_node<N>(&self, _node: N)
581        where
582            N: hopr_api::graph::MeasurableNode + Send + Clone,
583        {
584            unimplemented!()
585        }
586    }
587
588    #[async_trait]
589    impl NetworkGraphView for PeerStore {
590        type NodeId = OffchainPublicKey;
591        type Observed = TestEdgeObservations;
592
593        fn identity(&self) -> &OffchainPublicKey {
594            &self.me
595        }
596
597        fn node_count(&self) -> usize {
598            self.get_peers.read().unwrap().front().map_or(0, |v| v.len())
599        }
600
601        fn contains_node(&self, _key: &OffchainPublicKey) -> bool {
602            false
603        }
604
605        /// Returns a stream of all known nodes in the network graph.
606        fn nodes(&self) -> futures::stream::BoxStream<'static, OffchainPublicKey> {
607            let mut get_peers = self.get_peers.write().unwrap();
608            Box::pin(futures::stream::iter(get_peers.pop_front().unwrap_or_default()))
609        }
610
611        fn edge(&self, _src: &OffchainPublicKey, _dest: &OffchainPublicKey) -> Option<TestEdgeObservations> {
612            Some(TestEdgeObservations)
613        }
614    }
615
616    type TestClassifier = ProbeClassifierState<PeerStore>;
617
618    struct TestInterface {
619        probe_classifier: TestClassifier,
620        from_probing_to_network_rx: futures::channel::mpsc::Receiver<(DestinationRouting, ApplicationDataOut)>,
621        from_probing_to_network_tx: futures::channel::mpsc::Sender<(DestinationRouting, ApplicationDataOut)>,
622        manual_probe_tx: futures::channel::mpsc::Sender<(OffchainPublicKey, PingQueryReplier)>,
623    }
624
625    async fn test_with_probing<F, Fut>(cfg: ProbeConfig, store: PeerStore, test: F) -> anyhow::Result<()>
626    where
627        Fut: std::future::Future<Output = anyhow::Result<()>>,
628        F: Fn(TestInterface) -> Fut + Send + Sync + 'static,
629    {
630        let tag_allocators = hopr_transport_tag_allocator::create_allocators(
631            ReservedTag::range().end..u16::MAX as u64 + 1,
632            [
633                (hopr_transport_tag_allocator::Usage::Session, 2048),
634                (hopr_transport_tag_allocator::Usage::SessionTerminalTelemetry, 4000),
635                (hopr_transport_tag_allocator::Usage::ProvingTelemetry, 10000),
636            ],
637        )
638        .expect("tag allocators should be created");
639        let probing_allocator = tag_allocators
640            .into_iter()
641            .find_map(|(u, alloc)| matches!(u, hopr_transport_tag_allocator::Usage::ProvingTelemetry).then_some(alloc))
642            .expect("probing allocator should exist");
643
644        let probe = Probe::new(cfg, probing_allocator);
645
646        let (from_probing_to_network_tx, from_probing_to_network_rx) =
647            futures::channel::mpsc::channel::<(DestinationRouting, ApplicationDataOut)>(100);
648
649        let (manual_probe_tx, manual_probe_rx) =
650            futures::channel::mpsc::channel::<(OffchainPublicKey, PingQueryReplier)>(100);
651
652        let (jhs, probe_classifier) = probe
653            .continuously_scan(
654                from_probing_to_network_tx.clone(),
655                manual_probe_rx,
656                TestProbeStrategy::ImmediateNeighbor { store: store.clone() },
657                store,
658            )
659            .await;
660
661        let interface = TestInterface {
662            probe_classifier,
663            from_probing_to_network_rx,
664            from_probing_to_network_tx,
665            manual_probe_tx,
666        };
667
668        let result = test(interface).await;
669
670        jhs.abort_all();
671
672        result
673    }
674
675    const NO_PROBE_PASSES: f64 = 0.0;
676    const ALL_PROBES_PASS: f64 = 1.0;
677
678    /// Simulates the network: receives outgoing probe packets and feeds pong responses back
679    /// through the classifier (mirroring what the remote peer + packet pipeline would do).
680    fn concurrent_classify(
681        delay: Option<std::time::Duration>,
682        pass_rate: f64,
683        classifier: TestClassifier,
684        push_to_network: futures::channel::mpsc::Sender<(DestinationRouting, ApplicationDataOut)>,
685    ) -> impl Fn((DestinationRouting, ApplicationDataOut)) -> BoxFuture<'static, ()> {
686        debug_assert!(
687            (NO_PROBE_PASSES..=ALL_PROBES_PASS).contains(&pass_rate),
688            "Pass rate must be between {NO_PROBE_PASSES} and {ALL_PROBES_PASS}"
689        );
690
691        move |(path, data_out): (DestinationRouting, ApplicationDataOut)| -> BoxFuture<'static, ()> {
692            let classifier = classifier.clone();
693            let push_to_network = push_to_network.clone();
694
695            Box::pin(async move {
696                if let DestinationRouting::Forward { pseudonym, .. } = path {
697                    let message: Message = data_out.data.try_into().expect("failed to convert data into message");
698                    if let Message::Probe(NeighborProbe::Ping(ping)) = message {
699                        let pong_message = Message::Probe(NeighborProbe::Pong(ping));
700
701                        if let Some(delay) = delay {
702                            tokio::time::sleep(delay).await;
703                        }
704
705                        if rand::random_range(NO_PROBE_PASSES..=ALL_PROBES_PASS) < pass_rate {
706                            let pseudonym = pseudonym.expect("the pseudonym is always known from cache");
707                            classifier
708                                .classify(
709                                    push_to_network,
710                                    pseudonym,
711                                    ApplicationDataIn {
712                                        data: pong_message
713                                            .try_into()
714                                            .expect("failed to convert pong message into data"),
715                                        packet_info: Default::default(),
716                                    },
717                                )
718                                .await;
719                        }
720                    }
721                };
722            })
723        }
724    }
725
726    #[tokio::test]
727    // #[tracing_test::traced_test]
728    async fn probe_should_record_value_for_manual_neighbor_probe() -> anyhow::Result<()> {
729        let cfg = ProbeConfig {
730            timeout: std::time::Duration::from_millis(5),
731            interval: std::time::Duration::from_secs(0),
732            ..Default::default()
733        };
734
735        let store = PeerStore {
736            me: *OFFCHAIN_KEYPAIR.public(),
737            get_peers: Arc::new(RwLock::new(VecDeque::new())),
738            on_finished: Arc::new(RwLock::new(Vec::new())),
739        };
740
741        test_with_probing(cfg, store, move |iface: TestInterface| async move {
742            let mut manual_probe_tx = iface.manual_probe_tx;
743            let from_probing_to_network_rx = iface.from_probing_to_network_rx;
744            let from_probing_to_network_tx = iface.from_probing_to_network_tx;
745            let probe_classifier = iface.probe_classifier;
746
747            let (tx, mut rx) = futures::channel::mpsc::channel::<std::result::Result<Duration, ()>>(128);
748            manual_probe_tx.send((NEIGHBOURS[0], PingQueryReplier::new(tx))).await?;
749
750            let _jh: hopr_utils::runtime::prelude::JoinHandle<()> = tokio::spawn(async move {
751                from_probing_to_network_rx
752                    .for_each_concurrent(
753                        cfg.max_parallel_probes + 1,
754                        concurrent_classify(None, ALL_PROBES_PASS, probe_classifier, from_probing_to_network_tx),
755                    )
756                    .await;
757            });
758
759            let _duration = tokio::time::timeout(std::time::Duration::from_secs(1), rx.next())
760                .await?
761                .ok_or_else(|| anyhow::anyhow!("Probe did not return a result in time"))?
762                .map_err(|_| anyhow::anyhow!("Probe failed"))?;
763
764            Ok(())
765        })
766        .await
767    }
768
769    #[tokio::test]
770    // #[tracing_test::traced_test]
771    async fn probe_should_record_failure_on_manual_fail() -> anyhow::Result<()> {
772        let cfg = ProbeConfig {
773            timeout: std::time::Duration::from_millis(5),
774            interval: std::time::Duration::from_secs(0),
775            ..Default::default()
776        };
777
778        let store = PeerStore {
779            me: *OFFCHAIN_KEYPAIR.public(),
780            get_peers: Arc::new(RwLock::new(VecDeque::new())),
781            on_finished: Arc::new(RwLock::new(Vec::new())),
782        };
783
784        test_with_probing(cfg, store, move |iface: TestInterface| async move {
785            let mut manual_probe_tx = iface.manual_probe_tx;
786            let from_probing_to_network_rx = iface.from_probing_to_network_rx;
787            let from_probing_to_network_tx = iface.from_probing_to_network_tx;
788            let probe_classifier = iface.probe_classifier;
789
790            let (tx, mut rx) = futures::channel::mpsc::channel::<std::result::Result<Duration, ()>>(128);
791            manual_probe_tx.send((NEIGHBOURS[0], PingQueryReplier::new(tx))).await?;
792
793            let _jh: hopr_utils::runtime::prelude::JoinHandle<()> = tokio::spawn(async move {
794                from_probing_to_network_rx
795                    .for_each_concurrent(
796                        cfg.max_parallel_probes + 1,
797                        concurrent_classify(None, NO_PROBE_PASSES, probe_classifier, from_probing_to_network_tx),
798                    )
799                    .await;
800            });
801
802            assert!(tokio::time::timeout(cfg.timeout * 2, rx.next()).await.is_err());
803
804            Ok(())
805        })
806        .await
807    }
808
809    #[tokio::test]
810    // #[tracing_test::traced_test]
811    async fn probe_should_record_results_of_successful_automatically_generated_probes() -> anyhow::Result<()> {
812        let cfg = ProbeConfig {
813            timeout: std::time::Duration::from_millis(20),
814            max_parallel_probes: NEIGHBOURS.len(),
815            interval: std::time::Duration::from_secs(0),
816            ..Default::default()
817        };
818
819        let store = PeerStore {
820            me: *OFFCHAIN_KEYPAIR.public(),
821            get_peers: Arc::new(RwLock::new({
822                let mut neighbors = VecDeque::new();
823                neighbors.push_back(NEIGHBOURS.clone());
824                neighbors
825            })),
826            on_finished: Arc::new(RwLock::new(Vec::new())),
827        };
828
829        test_with_probing(cfg, store.clone(), move |iface: TestInterface| async move {
830            let from_probing_to_network_rx = iface.from_probing_to_network_rx;
831            let from_probing_to_network_tx = iface.from_probing_to_network_tx;
832            let probe_classifier = iface.probe_classifier;
833
834            let _jh: hopr_utils::runtime::prelude::JoinHandle<()> = tokio::spawn(async move {
835                from_probing_to_network_rx
836                    .for_each_concurrent(
837                        cfg.max_parallel_probes + 1,
838                        concurrent_classify(None, ALL_PROBES_PASS, probe_classifier, from_probing_to_network_tx),
839                    )
840                    .await;
841            });
842
843            // Wait for the full probe lifecycle: emit → network round trip → process.
844            // Must exceed cfg.timeout (the cache TTL) to avoid probes being evicted
845            // as timeouts before the pong response is processed.
846            tokio::time::sleep(cfg.timeout * 3).await;
847
848            Ok(())
849        })
850        .await?;
851
852        assert_eq!(
853            store
854                .on_finished
855                .read()
856                .expect("should be lockable")
857                .iter()
858                .filter(|(_peer, result)| result.is_ok())
859                .count(),
860            NEIGHBOURS.len()
861        );
862
863        Ok(())
864    }
865
866    #[tokio::test]
867    // #[tracing_test::traced_test]
868    async fn probe_should_record_results_of_timed_out_automatically_generated_probes() -> anyhow::Result<()> {
869        let cfg = ProbeConfig {
870            timeout: std::time::Duration::from_millis(10),
871            max_parallel_probes: NEIGHBOURS.len(),
872            interval: std::time::Duration::from_secs(0),
873            ..Default::default()
874        };
875
876        let store = PeerStore {
877            me: *OFFCHAIN_KEYPAIR.public(),
878            get_peers: Arc::new(RwLock::new({
879                let mut neighbors = VecDeque::new();
880                neighbors.push_back(NEIGHBOURS.clone());
881                neighbors
882            })),
883            on_finished: Arc::new(RwLock::new(Vec::new())),
884        };
885
886        let timeout = cfg.timeout * 2;
887
888        test_with_probing(cfg, store.clone(), move |iface: TestInterface| async move {
889            let from_probing_to_network_rx = iface.from_probing_to_network_rx;
890            let from_probing_to_network_tx = iface.from_probing_to_network_tx;
891            let probe_classifier = iface.probe_classifier;
892
893            let _jh: hopr_utils::runtime::prelude::JoinHandle<()> = tokio::spawn(async move {
894                from_probing_to_network_rx
895                    .for_each_concurrent(
896                        cfg.max_parallel_probes + 1,
897                        concurrent_classify(
898                            Some(timeout),
899                            ALL_PROBES_PASS,
900                            probe_classifier,
901                            from_probing_to_network_tx,
902                        ),
903                    )
904                    .await;
905            });
906
907            // wait for the probes to start and finish
908            tokio::time::sleep(timeout * 2).await;
909
910            Ok(())
911        })
912        .await?;
913
914        assert_eq!(
915            store
916                .on_finished
917                .read()
918                .expect("should be lockable")
919                .iter()
920                .filter(|(_peer, result)| result.is_err())
921                .count(),
922            NEIGHBOURS.len()
923        );
924
925        Ok(())
926    }
927
928    #[tokio::test]
929    async fn probe_should_reply_with_pong_when_receiving_ping() -> anyhow::Result<()> {
930        use anyhow::Context;
931
932        let cfg = ProbeConfig {
933            timeout: std::time::Duration::from_millis(100),
934            interval: std::time::Duration::from_secs(10),
935            ..Default::default()
936        };
937
938        let store = PeerStore {
939            me: *OFFCHAIN_KEYPAIR.public(),
940            get_peers: Arc::new(RwLock::new(VecDeque::new())),
941            on_finished: Arc::new(RwLock::new(Vec::new())),
942        };
943
944        test_with_probing(cfg, store, move |iface: TestInterface| async move {
945            let probe_classifier = iface.probe_classifier;
946            let from_probing_to_network_tx = iface.from_probing_to_network_tx;
947            let mut from_probing_to_network_rx = iface.from_probing_to_network_rx;
948
949            // Build a Ping message with the reserved Ping tag
950            let ping = NeighborProbe::random_nonce();
951            let ping_nonce = match ping {
952                NeighborProbe::Ping(n) => n,
953                _ => unreachable!(),
954            };
955            let ping_msg = Message::Probe(ping);
956            let app_data: ApplicationData = ping_msg.try_into().context("converting ping to ApplicationData")?;
957
958            // Classify the ping directly — the classifier sends the pong reply to push_to_network
959            let result = probe_classifier
960                .classify(
961                    from_probing_to_network_tx,
962                    HoprPseudonym::random(),
963                    ApplicationDataIn {
964                        data: app_data,
965                        packet_info: Default::default(),
966                    },
967                )
968                .await;
969            anyhow::ensure!(matches!(result, ProbeDispatch::Consumed), "ping should be consumed");
970
971            // The probe should reply with a Pong on the network channel
972            let (routing, data_out) = tokio::time::timeout(Duration::from_secs(2), from_probing_to_network_rx.next())
973                .await
974                .context("timeout waiting for pong")?
975                .context("probe should send pong reply")?;
976
977            // Verify it's a Return routing (SURB-based reply)
978            anyhow::ensure!(
979                matches!(routing, DestinationRouting::Return(_)),
980                "pong should use Return routing, got: {routing:?}"
981            );
982
983            // Verify the payload is a Pong with the same nonce
984            let response_msg: Message = data_out.data.try_into().context("converting response to Message")?;
985            anyhow::ensure!(
986                matches!(response_msg, Message::Probe(NeighborProbe::Pong(n)) if n == ping_nonce),
987                "response should be Pong with matching nonce"
988            );
989
990            Ok(())
991        })
992        .await
993    }
994
995    #[tokio::test]
996    // #[tracing_test::traced_test]
997    async fn probe_should_pass_through_non_associated_tags() -> anyhow::Result<()> {
998        let cfg = ProbeConfig {
999            timeout: std::time::Duration::from_millis(20),
1000            interval: std::time::Duration::from_secs(0),
1001            ..Default::default()
1002        };
1003
1004        let store = PeerStore {
1005            me: *OFFCHAIN_KEYPAIR.public(),
1006            get_peers: Arc::new(RwLock::new({
1007                let mut neighbors = VecDeque::new();
1008                neighbors.push_back(NEIGHBOURS.clone());
1009                neighbors
1010            })),
1011            on_finished: Arc::new(RwLock::new(Vec::new())),
1012        };
1013
1014        test_with_probing(cfg, store.clone(), move |iface: TestInterface| async move {
1015            let probe_classifier = iface.probe_classifier;
1016            let from_probing_to_network_tx = iface.from_probing_to_network_tx;
1017
1018            let expected_data = ApplicationData::new(Tag::MAX, b"Hello, this is a test message!")?;
1019
1020            let result = probe_classifier
1021                .classify(
1022                    from_probing_to_network_tx,
1023                    HoprPseudonym::random(),
1024                    ApplicationDataIn {
1025                        data: expected_data.clone(),
1026                        packet_info: Default::default(),
1027                    },
1028                )
1029                .await;
1030
1031            match result {
1032                ProbeDispatch::Passthrough(_, actual) => assert_eq!(actual.data, expected_data),
1033                ProbeDispatch::Consumed => anyhow::bail!("expected Passthrough, got Consumed"),
1034            }
1035
1036            Ok(())
1037        })
1038        .await
1039    }
1040
1041    /// How a probe gets triggered inside the test: either via the manual ping channel
1042    /// (for neighbor probes) or by injecting a single [`ProbeRouting::Looping`] into the
1043    /// probing traffic generator (for loopback probes).
1044    #[derive(Clone)]
1045    enum TestProbeStrategy {
1046        ManualNeighbor,
1047        ImmediateNeighbor {
1048            store: PeerStore,
1049        },
1050        OneShotLoopback {
1051            routing: DestinationRouting,
1052            path_id: hopr_api::types::internal::routing::PathId,
1053        },
1054    }
1055
1056    impl hopr_api::ct::ProbingTrafficGeneration for TestProbeStrategy {
1057        fn build(&self) -> futures::stream::BoxStream<'static, hopr_api::ct::ProbeRouting> {
1058            match self {
1059                Self::ManualNeighbor => Box::pin(futures::stream::pending()),
1060                Self::ImmediateNeighbor { store } => {
1061                    let peers: Vec<OffchainPublicKey> =
1062                        store.get_peers.write().unwrap().pop_front().unwrap_or_default();
1063                    Box::pin(futures::StreamExt::chain(
1064                        futures::stream::iter(peers.into_iter().map(|peer| {
1065                            ProbeRouting::Neighbor(DestinationRouting::Forward {
1066                                destination: Box::new(peer.into()),
1067                                pseudonym: Some(HoprPseudonym::random()),
1068                                forward_options: RoutingOptions::Hops(0.try_into().expect("0 is a valid u8")),
1069                                return_options: Some(RoutingOptions::Hops(0.try_into().expect("0 is a valid u8"))),
1070                            })
1071                        })),
1072                        futures::stream::pending(),
1073                    ))
1074                }
1075                Self::OneShotLoopback { routing, path_id } => {
1076                    let probe = hopr_api::ct::ProbeRouting::Looping((routing.clone(), *path_id));
1077                    Box::pin(futures::StreamExt::chain(
1078                        futures::stream::iter(std::iter::once(probe)),
1079                        futures::stream::pending(),
1080                    ))
1081                }
1082            }
1083        }
1084    }
1085
1086    /// Regression test for hoprnet/hoprnet#7972: each probe type must be emitted with the
1087    /// exact SURB count it actually consumes — no more, no less — so the path planner does
1088    /// not resolve (and the SURB store does not accumulate) unused return paths.
1089    ///
1090    /// - Neighbor probe: 1 SURB (zero-hop pong return).
1091    /// - Loopback probe: 0 SURBs (self-routed, never replied to).
1092    #[rstest::rstest]
1093    #[case::neighbor_probe_requests_one_surb(TestProbeStrategy::ManualNeighbor, 1)]
1094    #[case::loopback_probe_requests_zero_surbs(
1095        TestProbeStrategy::OneShotLoopback {
1096            routing: DestinationRouting::Forward {
1097                destination: Box::new((*OFFCHAIN_KEYPAIR.public()).into()),
1098                pseudonym: Some(HoprPseudonym::random()),
1099                forward_options: RoutingOptions::Hops(1.try_into().expect("1 is a valid u8")),
1100                return_options: None,
1101            },
1102            path_id: [1, 2, 3, 4, 5],
1103        },
1104        0,
1105    )]
1106    #[tokio::test]
1107    async fn probe_should_emit_with_expected_surb_count(
1108        #[case] strategy: TestProbeStrategy,
1109        #[case] expected_max_surbs: usize,
1110    ) -> anyhow::Result<()> {
1111        let cfg = ProbeConfig {
1112            timeout: std::time::Duration::from_secs(1),
1113            interval: std::time::Duration::from_secs(0),
1114            ..Default::default()
1115        };
1116
1117        // Wire up a full probing harness with the parameterized strategy injected as the
1118        // traffic generator. Mirrors `test_with_probing` but allows arbitrary `ProbingTrafficGeneration`.
1119        let tag_allocators = hopr_transport_tag_allocator::create_allocators(
1120            ReservedTag::range().end..u16::MAX as u64 + 1,
1121            [
1122                (hopr_transport_tag_allocator::Usage::Session, 2048),
1123                (hopr_transport_tag_allocator::Usage::SessionTerminalTelemetry, 4000),
1124                (hopr_transport_tag_allocator::Usage::ProvingTelemetry, 10000),
1125            ],
1126        )
1127        .expect("tag allocators should be created");
1128        let probing_allocator = tag_allocators
1129            .into_iter()
1130            .find_map(|(u, alloc)| matches!(u, hopr_transport_tag_allocator::Usage::ProvingTelemetry).then_some(alloc))
1131            .expect("probing allocator should exist");
1132
1133        let probe = Probe::new(cfg, probing_allocator);
1134
1135        let (from_probing_to_network_tx, mut from_probing_to_network_rx) =
1136            futures::channel::mpsc::channel::<(DestinationRouting, ApplicationDataOut)>(100);
1137        let (mut manual_probe_tx, manual_probe_rx) =
1138            futures::channel::mpsc::channel::<(OffchainPublicKey, PingQueryReplier)>(100);
1139
1140        let store = PeerStore {
1141            me: *OFFCHAIN_KEYPAIR.public(),
1142            get_peers: Arc::new(RwLock::new(VecDeque::new())),
1143            on_finished: Arc::new(RwLock::new(Vec::new())),
1144        };
1145
1146        // Kick off the probing process before triggering — the strategy's stream drives
1147        // the loopback case, and we push to `manual_probe_tx` below for the neighbor case.
1148        let is_manual = matches!(strategy, TestProbeStrategy::ManualNeighbor);
1149        let (jhs, _probe_classifier) = probe
1150            .continuously_scan(from_probing_to_network_tx, manual_probe_rx, strategy, store)
1151            .await;
1152
1153        if is_manual {
1154            let (tx, _rx) = futures::channel::mpsc::channel::<std::result::Result<Duration, ()>>(128);
1155            manual_probe_tx.send((NEIGHBOURS[0], PingQueryReplier::new(tx))).await?;
1156        }
1157
1158        let (_routing, data_out) =
1159            tokio::time::timeout(std::time::Duration::from_secs(1), from_probing_to_network_rx.next())
1160                .await?
1161                .ok_or_else(|| anyhow::anyhow!("no probe emitted"))?;
1162
1163        jhs.abort_all();
1164
1165        let packet_info = data_out
1166            .packet_info
1167            .ok_or_else(|| anyhow::anyhow!("probe must carry explicit OutgoingPacketInfo"))?;
1168        assert_eq!(
1169            packet_info.max_surbs_in_packet, expected_max_surbs,
1170            "probe must request exactly {expected_max_surbs} SURB(s)"
1171        );
1172
1173        Ok(())
1174    }
1175}