hopr_transport_network/
network.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
use std::collections::hash_set::HashSet;
use std::time::{Duration, SystemTime};

use futures::StreamExt;
use libp2p_identity::PeerId;

use multiaddr::Multiaddr;
use tracing::debug;

pub use hopr_db_api::peers::{HoprDbPeersOperations, PeerOrigin, PeerSelector, PeerStatus, Stats};
use hopr_platform::time::native::current_time;

use crate::config::NetworkConfig;

#[cfg(all(feature = "prometheus", not(test)))]
use {
    hopr_metrics::metrics::{MultiGauge, SimpleGauge},
    hopr_primitive_types::prelude::*,
};

#[cfg(all(feature = "prometheus", not(test)))]
lazy_static::lazy_static! {
    static ref METRIC_NETWORK_HEALTH: SimpleGauge =
        SimpleGauge::new("hopr_network_health", "Connectivity health indicator").unwrap();
    static ref METRIC_PEERS_BY_QUALITY: MultiGauge =
        MultiGauge::new("hopr_peers_by_quality", "Number different peer types by quality",
            &["type", "quality"],
        ).unwrap();
    static ref METRIC_PEER_COUNT: SimpleGauge =
        SimpleGauge::new("hopr_peer_count", "Number of all peers").unwrap();
    static ref METRIC_NETWORK_HEALTH_TIME_TO_GREEN: SimpleGauge = SimpleGauge::new(
        "hopr_time_to_green_sec",
        "Time it takes for a node to transition to the GREEN network state"
    ).unwrap();
}

/// Network health represented with colors, where green is the best and red
/// is the worst possible observed nework quality.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, strum::Display, strum::EnumString)]
pub enum Health {
    /// Unknown health, on application startup
    Unknown = 0,
    /// No connection, default
    Red = 1,
    /// Low quality connection to at least 1 public relay
    Orange = 2,
    /// High quality connection to at least 1 public relay
    Yellow = 3,
    /// High quality connection to at least 1 public relay and 1 NAT node
    Green = 4,
}

/// Events generated by the [Network] object allowing it
/// to physically interact with external systems,
/// including the transport mechanism.
#[derive(Debug, Clone, PartialEq, strum::Display)]
pub enum NetworkTriggeredEvent {
    CloseConnection(PeerId),
    UpdateQuality(PeerId, f64),
}

/// Calculate the health factor for network from the available stats
fn health_from_stats(stats: &Stats, is_public: bool) -> Health {
    let mut health = Health::Red;

    if stats.bad_quality_public > 0 {
        health = Health::Orange;
    }

    if stats.good_quality_public > 0 {
        health = if is_public || stats.good_quality_non_public > 0 {
            Health::Green
        } else {
            Health::Yellow
        };
    }

    health
}

/// The network object storing information about the running observed state of the network,
/// including peers, connection qualities and updates for other parts of the system.
#[derive(Debug)]
pub struct Network<T>
where
    T: HoprDbPeersOperations + Sync + Send + std::fmt::Debug,
{
    me: PeerId,
    me_addresses: Vec<Multiaddr>,
    am_i_public: bool,
    cfg: NetworkConfig,
    db: T,
    #[cfg(all(feature = "prometheus", not(test)))]
    started_at: Duration,
}

impl<T> Network<T>
where
    T: HoprDbPeersOperations + Sync + Send + std::fmt::Debug,
{
    pub fn new(my_peer_id: PeerId, my_multiaddresses: Vec<Multiaddr>, cfg: NetworkConfig, db: T) -> Self {
        #[cfg(all(feature = "prometheus", not(test)))]
        {
            METRIC_NETWORK_HEALTH.set(0.0);
            METRIC_NETWORK_HEALTH_TIME_TO_GREEN.set(0.0);
            METRIC_PEERS_BY_QUALITY.set(&["public", "high"], 0.0);
            METRIC_PEERS_BY_QUALITY.set(&["public", "low"], 0.0);
            METRIC_PEERS_BY_QUALITY.set(&["nonPublic", "high"], 0.0);
            METRIC_PEERS_BY_QUALITY.set(&["nonPublic", "low"], 0.0);
        }

        Self {
            me: my_peer_id,
            me_addresses: my_multiaddresses,
            am_i_public: true,
            cfg: cfg.clone(),
            db,
            #[cfg(all(feature = "prometheus", not(test)))]
            started_at: current_time().as_unix_timestamp(),
        }
    }

    /// Check whether the PeerId is present in the network
    pub async fn has(&self, peer: &PeerId) -> bool {
        peer == &self.me || self.db.get_network_peer(peer).await.is_ok_and(|p| p.is_some())
    }

    /// Checks if the peer is present in the network, but it is being currently ignored.
    pub async fn is_ignored(&self, peer: &PeerId) -> bool {
        peer != &self.me
            && self
                .get(peer)
                .await
                .is_ok_and(|ps| ps.is_some_and(|p| p.is_ignored(current_time(), self.cfg.ignore_timeframe)))
    }

    /// Add a new peer into the network
    ///
    /// Each peer must have an origin specification.
    pub async fn add(&self, peer: &PeerId, origin: PeerOrigin, mut addrs: Vec<Multiaddr>) -> crate::errors::Result<()> {
        if peer == &self.me {
            return Err(crate::errors::NetworkingError::DisallowedOperationOnOwnPeerIdError);
        }

        if let Some(mut peer_status) = self.db.get_network_peer(peer).await? {
            if !peer_status.is_ignored(current_time(), self.cfg.ignore_timeframe) {
                peer_status.ignored = None;
                peer_status.multiaddresses.append(&mut addrs);
                peer_status.multiaddresses = peer_status
                    .multiaddresses
                    .into_iter()
                    .collect::<HashSet<_>>()
                    .into_iter()
                    .collect::<Vec<_>>();
                self.db.update_network_peer(peer_status).await?;
            }
        } else {
            debug!(%peer, %origin, multiaddresses = ?addrs, "Adding peer to the store");

            self.db
                .add_network_peer(
                    peer,
                    origin,
                    addrs,
                    self.cfg.backoff_exponent,
                    self.cfg.quality_avg_window_size,
                )
                .await?;
        }

        #[cfg(all(feature = "prometheus", not(test)))]
        {
            let stats = self.db.network_peer_stats(self.cfg.quality_bad_threshold).await?;
            self.refresh_metrics(&stats)
        }

        Ok(())
    }

    pub async fn get(&self, peer: &PeerId) -> crate::errors::Result<Option<PeerStatus>> {
        if peer == &self.me {
            Ok(Some({
                let mut ps = PeerStatus::new(*peer, PeerOrigin::Initialization, 0.0f64, 2u32);
                ps.multiaddresses.clone_from(&self.me_addresses);
                ps
            }))
        } else {
            Ok(self.db.get_network_peer(peer).await?)
        }
    }

    /// Remove peer from the network
    pub async fn remove(&self, peer: &PeerId) -> crate::errors::Result<()> {
        if peer == &self.me {
            return Err(crate::errors::NetworkingError::DisallowedOperationOnOwnPeerIdError);
        }

        self.db.remove_network_peer(peer).await?;

        #[cfg(all(feature = "prometheus", not(test)))]
        {
            let stats = self.db.network_peer_stats(self.cfg.quality_bad_threshold).await?;
            self.refresh_metrics(&stats)
        }

        Ok(())
    }

    /// Update the peer record with the observation
    pub async fn update(
        &self,
        peer: &PeerId,
        ping_result: std::result::Result<Duration, ()>,
        version: Option<String>,
    ) -> crate::errors::Result<Option<NetworkTriggeredEvent>> {
        if peer == &self.me {
            return Err(crate::errors::NetworkingError::DisallowedOperationOnOwnPeerIdError);
        }

        if let Some(mut entry) = self.db.get_network_peer(peer).await? {
            if !entry.is_ignored(current_time(), self.cfg.ignore_timeframe) {
                entry.ignored = None;
            }

            entry.heartbeats_sent += 1;
            entry.peer_version = version;

            if let Ok(latency) = ping_result {
                entry.last_seen = current_time();
                entry.last_seen_latency = latency;
                entry.heartbeats_succeeded += 1;
                entry.backoff = self.cfg.backoff_min;
                entry.update_quality(1.0_f64.min(entry.get_quality() + self.cfg.quality_step));
            } else {
                entry.backoff = self.cfg.backoff_max.max(entry.backoff.powf(self.cfg.backoff_exponent));
                entry.update_quality(0.0_f64.max(entry.get_quality() - self.cfg.quality_step));

                let q = entry.get_quality();

                if q < self.cfg.quality_bad_threshold {
                    entry.ignored = Some(current_time());
                }
            }

            let (peer_id, quality) = (entry.id.1, entry.get_quality());
            self.db.update_network_peer(entry).await?;

            #[cfg(all(feature = "prometheus", not(test)))]
            {
                let stats = self.db.network_peer_stats(self.cfg.quality_bad_threshold).await?;
                self.refresh_metrics(&stats)
            }

            if quality <= self.cfg.quality_offline_threshold {
                Ok(Some(NetworkTriggeredEvent::CloseConnection(peer_id)))
            } else {
                Ok(Some(NetworkTriggeredEvent::UpdateQuality(peer_id, quality)))
            }
        } else {
            debug!(%peer, "Ignoring update request for unknown peer");
            Ok(None)
        }
    }

    /// Returns the quality of the network as a network health indicator.
    pub async fn health(&self) -> Health {
        self.db
            .network_peer_stats(self.cfg.quality_bad_threshold)
            .await
            .map(|stats| health_from_stats(&stats, self.am_i_public))
            .unwrap_or(Health::Unknown)
    }

    /// Update the internally perceived network status that is processed to the network health
    #[cfg(all(feature = "prometheus", not(test)))]
    fn refresh_metrics(&self, stats: &Stats) {
        let health = health_from_stats(stats, self.am_i_public);

        if METRIC_NETWORK_HEALTH_TIME_TO_GREEN.get() < 0.5f64 {
            if let Some(ts) = current_time().checked_sub(self.started_at) {
                METRIC_NETWORK_HEALTH_TIME_TO_GREEN.set(ts.as_unix_timestamp().as_secs_f64());
            }
        }
        METRIC_PEER_COUNT.set(stats.all_count() as f64);
        METRIC_PEERS_BY_QUALITY.set(&["public", "high"], stats.good_quality_public as f64);
        METRIC_PEERS_BY_QUALITY.set(&["public", "low"], stats.bad_quality_public as f64);
        METRIC_PEERS_BY_QUALITY.set(&["nonPublic", "high"], stats.good_quality_non_public as f64);
        METRIC_PEERS_BY_QUALITY.set(&["nonPublic", "low"], stats.bad_quality_non_public as f64);
        METRIC_NETWORK_HEALTH.set((health as i32).into());
    }

    pub async fn connected_peers(&self) -> crate::errors::Result<Vec<PeerId>> {
        let minimum_quality = self.cfg.quality_offline_threshold;
        self.peer_filter(|peer| async move { (peer.get_quality() > minimum_quality).then_some(peer.id.1) })
            .await
    }

    // ======
    pub(crate) async fn peer_filter<Fut, V, F>(&self, filter: F) -> crate::errors::Result<Vec<V>>
    where
        F: FnMut(PeerStatus) -> Fut,
        Fut: std::future::Future<Output = Option<V>>,
    {
        let stream = self.db.get_network_peers(Default::default(), false).await?;
        futures::pin_mut!(stream);
        Ok(stream.filter_map(filter).collect().await)
    }

    pub async fn find_peers_to_ping(&self, threshold: SystemTime) -> crate::errors::Result<Vec<PeerId>> {
        let stream = self
            .db
            .get_network_peers(PeerSelector::default().with_last_seen_lte(threshold), false)
            .await?;
        futures::pin_mut!(stream);
        let mut data: Vec<PeerStatus> = stream
            .filter_map(|v| async move {
                if v.id.1 == self.me {
                    return None;
                }

                if let Some(ignore_start) = v.ignored {
                    let should_be_ignored = ignore_start
                        .checked_add(self.cfg.ignore_timeframe)
                        .is_some_and(|v| v > threshold);

                    if should_be_ignored {
                        return None;
                    }
                }

                let backoff = v.backoff.powf(self.cfg.backoff_exponent);
                let delay = std::cmp::min(self.cfg.min_delay * (backoff as u32), self.cfg.max_delay);

                if (v.last_seen + delay) < threshold {
                    Some(v)
                } else {
                    None
                }
            })
            .collect()
            .await;

        data.sort_by(|a, b| {
            if a.last_seen < b.last_seen {
                std::cmp::Ordering::Less
            } else {
                std::cmp::Ordering::Greater
            }
        });

        Ok(data.into_iter().map(|peer| peer.id.1).collect())
    }
}

#[cfg(test)]
mod tests {
    use crate::network::{Health, Network, NetworkConfig, NetworkTriggeredEvent, PeerOrigin};
    use anyhow::Context;
    use hopr_crypto_types::keypairs::{ChainKeypair, Keypair, OffchainKeypair};
    use hopr_platform::time::native::current_time;
    use hopr_primitive_types::prelude::AsUnixTimestamp;
    use libp2p_identity::PeerId;
    use std::ops::Add;
    use std::time::Duration;

    #[test]
    fn test_network_health_should_serialize_to_a_proper_string() {
        assert_eq!(format!("{}", Health::Orange), "Orange".to_owned())
    }

    #[test]
    fn test_network_health_should_deserialize_from_proper_string() -> Result<(), Box<dyn std::error::Error>> {
        let parsed: Health = "Orange".parse()?;
        Ok(assert_eq!(parsed, Health::Orange))
    }

    async fn basic_network(my_id: &PeerId) -> anyhow::Result<Network<hopr_db_sql::db::HoprDb>> {
        let mut cfg = NetworkConfig::default();
        cfg.quality_offline_threshold = 0.6;
        Ok(Network::new(
            *my_id,
            vec![],
            cfg,
            hopr_db_sql::db::HoprDb::new_in_memory(ChainKeypair::random()).await?,
        ))
    }

    #[test]
    fn test_network_health_should_be_ordered_numerically_for_hopr_metrics_output() {
        assert_eq!(Health::Unknown as i32, 0);
        assert_eq!(Health::Red as i32, 1);
        assert_eq!(Health::Orange as i32, 2);
        assert_eq!(Health::Yellow as i32, 3);
        assert_eq!(Health::Green as i32, 4);
    }

    #[async_std::test]
    async fn test_network_should_not_be_able_to_add_self_reference() -> anyhow::Result<()> {
        let me = PeerId::random();

        let peers = basic_network(&me).await?;

        assert!(peers.add(&me, PeerOrigin::IncomingConnection, vec![]).await.is_err());

        assert_eq!(
            0,
            peers
                .peer_filter(|peer| async move { Some(peer.id) })
                .await
                .unwrap_or(vec![])
                .len()
        );
        assert!(peers.has(&me).await);

        Ok(())
    }

    #[async_std::test]
    async fn test_network_should_contain_a_registered_peer() -> anyhow::Result<()> {
        let expected: PeerId = OffchainKeypair::random().public().into();
        let me: PeerId = OffchainKeypair::random().public().into();

        let peers = basic_network(&me).await?;

        peers.add(&expected, PeerOrigin::IncomingConnection, vec![]).await?;

        assert_eq!(
            1,
            peers
                .peer_filter(|peer| async move { Some(peer.id) })
                .await
                .unwrap_or(vec![])
                .len()
        );
        assert!(peers.has(&expected).await);

        Ok(())
    }

    #[async_std::test]
    async fn test_network_should_remove_a_peer_on_unregistration() -> anyhow::Result<()> {
        let peer: PeerId = OffchainKeypair::random().public().into();
        let me: PeerId = OffchainKeypair::random().public().into();

        let peers = basic_network(&me).await?;

        peers.add(&peer, PeerOrigin::IncomingConnection, vec![]).await?;

        peers.remove(&peer).await?;

        assert_eq!(
            0,
            peers
                .peer_filter(|peer| async move { Some(peer.id) })
                .await
                .unwrap_or(vec![])
                .len()
        );
        assert!(!peers.has(&peer).await);

        Ok(())
    }

    #[async_std::test]
    async fn test_network_should_ignore_heartbeat_updates_for_peers_that_were_not_registered() -> anyhow::Result<()> {
        let peer: PeerId = OffchainKeypair::random().public().into();
        let me: PeerId = OffchainKeypair::random().public().into();

        let peers = basic_network(&me).await?;

        peers
            .update(&peer, Ok(current_time().as_unix_timestamp()), None)
            .await?;

        assert_eq!(
            0,
            peers
                .peer_filter(|peer| async move { Some(peer.id) })
                .await
                .unwrap_or(vec![])
                .len()
        );
        assert!(!peers.has(&peer).await);

        Ok(())
    }

    #[async_std::test]
    async fn test_network_should_be_able_to_register_a_succeeded_heartbeat_result() -> anyhow::Result<()> {
        let peer: PeerId = OffchainKeypair::random().public().into();
        let me: PeerId = OffchainKeypair::random().public().into();

        let peers = basic_network(&me).await?;

        peers.add(&peer, PeerOrigin::IncomingConnection, vec![]).await?;

        let latency = 123u64;

        peers
            .update(&peer, Ok(std::time::Duration::from_millis(latency)), None)
            .await?;

        let actual = peers.get(&peer).await?.expect("peer record should be present");

        assert_eq!(actual.heartbeats_sent, 1);
        assert_eq!(actual.heartbeats_succeeded, 1);
        assert_eq!(actual.last_seen_latency, std::time::Duration::from_millis(latency));

        Ok(())
    }

    #[async_std::test]
    async fn test_network_update_should_merge_metadata() -> anyhow::Result<()> {
        let peer: PeerId = OffchainKeypair::random().public().into();
        let me: PeerId = OffchainKeypair::random().public().into();

        let peers = basic_network(&me).await?;

        let expected_version = Some("1.2.4".to_string());

        {
            peers.add(&peer, PeerOrigin::IncomingConnection, vec![]).await?;
            peers
                .update(&peer, Ok(current_time().as_unix_timestamp()), expected_version.clone())
                .await?;

            let status = peers.get(&peer).await?.context("peer should be present")?;

            assert_eq!(status.peer_version, expected_version);
        }

        let ts = current_time().as_unix_timestamp();

        {
            let expected_version = Some("2.0.0".to_string());

            peers.update(&peer, Ok(ts), expected_version.clone()).await?;

            let status = peers.get(&peer).await?.context("peer should be present")?;

            assert_eq!(status.peer_version, expected_version);
        }

        Ok(())
    }

    #[async_std::test]
    async fn test_network_should_ignore_a_peer_that_has_reached_lower_thresholds_a_specified_amount_of_time(
    ) -> anyhow::Result<()> {
        let peer: PeerId = OffchainKeypair::random().public().into();
        let me: PeerId = OffchainKeypair::random().public().into();

        let peers = basic_network(&me).await?;

        peers.add(&peer, PeerOrigin::IncomingConnection, vec![]).await?;

        peers
            .update(&peer, Ok(current_time().as_unix_timestamp()), None)
            .await?;
        peers
            .update(&peer, Ok(current_time().as_unix_timestamp()), None)
            .await?;
        peers.update(&peer, Err(()), None).await?; // should drop to ignored

        peers.update(&peer, Err(()), None).await.expect("no error should occur"); // should drop from network

        assert!(peers.is_ignored(&peer).await);

        // peer should remain ignored and not be added
        peers.add(&peer, PeerOrigin::IncomingConnection, vec![]).await?;

        assert!(peers.is_ignored(&peer).await);

        Ok(())
    }

    #[async_std::test]
    async fn test_network_should_be_able_to_register_a_failed_heartbeat_result() -> anyhow::Result<()> {
        let peer: PeerId = OffchainKeypair::random().public().into();
        let me: PeerId = OffchainKeypair::random().public().into();

        let peers = basic_network(&me).await?;

        peers.add(&peer, PeerOrigin::IncomingConnection, vec![]).await?;

        // Needs to do 3 pings, so we get over the ignore threshold limit
        // when doing the 4th failed ping
        peers
            .update(&peer, Ok(std::time::Duration::from_millis(123_u64)), None)
            .await?;
        peers
            .update(&peer, Ok(std::time::Duration::from_millis(200_u64)), None)
            .await?;
        peers
            .update(&peer, Ok(std::time::Duration::from_millis(200_u64)), None)
            .await?;

        peers.update(&peer, Err(()), None).await?;

        let actual = peers.get(&peer).await?.expect("the peer record should be present");

        assert_eq!(actual.heartbeats_succeeded, 3);
        assert_eq!(actual.backoff, 300f64);

        Ok(())
    }

    #[async_std::test]
    async fn test_network_peer_should_be_listed_for_the_ping_if_last_recorded_later_than_reference(
    ) -> anyhow::Result<()> {
        let first: PeerId = OffchainKeypair::random().public().into();
        let second: PeerId = OffchainKeypair::random().public().into();
        let me: PeerId = OffchainKeypair::random().public().into();

        let peers = basic_network(&me).await?;

        peers.add(&first, PeerOrigin::IncomingConnection, vec![]).await?;
        peers.add(&second, PeerOrigin::IncomingConnection, vec![]).await?;

        let latency = 77_u64;

        let mut expected = vec![first, second];
        expected.sort();

        peers
            .update(&first, Ok(std::time::Duration::from_millis(latency)), None)
            .await?;
        peers
            .update(&second, Ok(std::time::Duration::from_millis(latency)), None)
            .await?;

        // assert_eq!(
        //     format!(
        //         "{:?}",
        //         peers.should_still_be_ignored(&peers.get(&first).await.unwrap().unwrap())
        //     ),
        //     ""
        // );
        // assert_eq!(format!("{:?}", peers.get(&first).await), "");

        let mut actual = peers
            .find_peers_to_ping(current_time().add(Duration::from_secs(2u64)))
            .await?;
        actual.sort();

        assert_eq!(actual, expected);

        Ok(())
    }

    #[async_std::test]
    async fn test_network_should_have_red_health_without_any_registered_peers() -> anyhow::Result<()> {
        let me: PeerId = OffchainKeypair::random().public().into();

        let peers = basic_network(&me).await?;

        assert_eq!(peers.health().await, Health::Red);

        Ok(())
    }

    #[async_std::test]
    async fn test_network_should_be_unhealthy_without_any_heartbeat_updates() -> anyhow::Result<()> {
        let peer: PeerId = OffchainKeypair::random().public().into();
        let me: PeerId = OffchainKeypair::random().public().into();

        let peers = basic_network(&me).await?;

        peers.add(&peer, PeerOrigin::IncomingConnection, vec![]).await?;

        // all peers are public
        assert_eq!(peers.health().await, Health::Orange);

        Ok(())
    }

    #[async_std::test]
    async fn test_network_should_be_unhealthy_without_any_peers_once_the_health_was_known() -> anyhow::Result<()> {
        let peer: PeerId = OffchainKeypair::random().public().into();
        let me: PeerId = OffchainKeypair::random().public().into();

        let peers = basic_network(&me).await?;

        peers.add(&peer, PeerOrigin::IncomingConnection, vec![]).await?;
        let _ = peers.health();
        peers.remove(&peer).await?;

        assert_eq!(peers.health().await, Health::Red);

        Ok(())
    }

    #[async_std::test]
    async fn test_network_should_be_healthy_when_a_public_peer_is_pingable_with_low_quality() -> anyhow::Result<()> {
        let peer: PeerId = OffchainKeypair::random().public().into();
        let me: PeerId = OffchainKeypair::random().public().into();

        let mut cfg = NetworkConfig::default();
        cfg.quality_offline_threshold = 0.6;

        let peers = Network::new(
            me,
            vec![],
            cfg,
            hopr_db_sql::db::HoprDb::new_in_memory(ChainKeypair::random()).await?,
        );

        peers.add(&peer, PeerOrigin::IncomingConnection, vec![]).await?;

        peers
            .update(&peer, Ok(current_time().as_unix_timestamp()), None)
            .await?;

        assert_eq!(peers.health().await, Health::Orange);

        Ok(())
    }

    #[async_std::test]
    async fn test_network_should_close_connection_to_peer_once_it_reaches_the_lowest_possible_quality(
    ) -> anyhow::Result<()> {
        let peer: PeerId = OffchainKeypair::random().public().into();
        let public = peer;
        let me: PeerId = OffchainKeypair::random().public().into();

        let mut cfg = NetworkConfig::default();
        cfg.quality_offline_threshold = 0.6;

        let peers = Network::new(
            me,
            vec![],
            cfg,
            hopr_db_sql::db::HoprDb::new_in_memory(ChainKeypair::random()).await?,
        );

        peers.add(&peer, PeerOrigin::IncomingConnection, vec![]).await?;

        assert_eq!(
            peers.update(&peer, Err(()), None).await?,
            Some(NetworkTriggeredEvent::CloseConnection(peer))
        );

        assert!(peers.is_ignored(&public).await);

        Ok(())
    }

    #[async_std::test]
    async fn test_network_should_be_healthy_when_a_public_peer_is_pingable_with_high_quality_and_i_am_public(
    ) -> anyhow::Result<()> {
        let me: PeerId = OffchainKeypair::random().public().into();
        let peer: PeerId = OffchainKeypair::random().public().into();

        let mut cfg = NetworkConfig::default();
        cfg.quality_offline_threshold = 0.3;

        let peers = Network::new(
            me,
            vec![],
            cfg,
            hopr_db_sql::db::HoprDb::new_in_memory(ChainKeypair::random()).await?,
        );

        peers.add(&peer, PeerOrigin::IncomingConnection, vec![]).await?;

        for _ in 0..3 {
            peers
                .update(&peer, Ok(current_time().as_unix_timestamp()), None)
                .await?;
        }

        assert_eq!(peers.health().await, Health::Green);

        Ok(())
    }

    #[async_std::test]
    async fn test_network_should_be_healthy_when_a_public_peer_is_pingable_with_high_quality_and_another_high_quality_non_public(
    ) -> anyhow::Result<()> {
        let peer: PeerId = OffchainKeypair::random().public().into();
        let peer2: PeerId = OffchainKeypair::random().public().into();

        let mut cfg = NetworkConfig::default();
        cfg.quality_offline_threshold = 0.3;

        let peers = Network::new(
            OffchainKeypair::random().public().into(),
            vec![],
            cfg,
            hopr_db_sql::db::HoprDb::new_in_memory(ChainKeypair::random()).await?,
        );

        peers.add(&peer, PeerOrigin::IncomingConnection, vec![]).await?;
        peers.add(&peer2, PeerOrigin::IncomingConnection, vec![]).await?;

        for _ in 0..3 {
            peers
                .update(&peer2, Ok(current_time().as_unix_timestamp()), None)
                .await?;
            peers
                .update(&peer, Ok(current_time().as_unix_timestamp()), None)
                .await?;
        }

        assert_eq!(peers.health().await, Health::Green);

        Ok(())
    }
}