tox_core 0.1.1

The core of tox
Documentation
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
/*! TCP connections handling

TCP connections provides reliable connection to net_crypto via multiple TCP
relays to a friend. When a Tox client connects to a friend via TCP relay,
normally 3 redundant connections are established. One connection is used for
sending/receiving data, 2 others are backup. In toxcore maximum number of
redundant connections is 6. TCP connection can get into sleep mode. Getting
into sleep mode can occur when UDP connection is established, because Tox
prefers UDP over TCP. When established UDP connection is lost, TCP connections
are awaken.

*/

use tokio::sync::RwLock;

use std::collections::{hash_map, HashMap, HashSet};
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;

use futures::{TryFutureExt, StreamExt};
use futures::channel::mpsc;

use tox_crypto::*;
use tox_packet::dht::packed_node::PackedNode;
use crate::relay::client::client::*;
use tox_packet::relay::*;
use crate::time::*;
use crate::relay::client::errors::*;
use failure::Fail;

/// The amount of maximum connections for each friend.
const MAX_FRIEND_TCP_CONNECTIONS: usize =  6;

/// The amount of recommended connections for each friend.
///   NOTE: Must be at most (MAX_FRIEND_TCP_CONNECTIONS / 2).
const RECOMMENDED_FRIEND_TCP_CONNECTIONS: usize =  MAX_FRIEND_TCP_CONNECTIONS / 2;

/// How many attempts to reconnect to the relay we should make before we
/// consider this relay unreachable and drop it.
const MAX_RECONNECTION_ATTEMPTS: u32 = 1;

const TCP_CONNECTION_ANNOUNCE_TIMEOUT: Duration = Duration::from_secs(10);

/// How often `main_loop` should be run.
const CONNECTIONS_INTERVAL: Duration = Duration::from_secs(1);

/// Connection status shows whether a connection used or not.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum NodeConnectionStatus {
    /// We are not connected to the node directly and need active relays to send
    /// packets to this node.
    TCP,
    /// We are connected to the node directly via UDP so all relays used only
    /// for this node connection can go to sleep.
    UDP,
}

/// Contains info about connection to a node via TCP relays.
#[derive(Debug, PartialEq, Clone)]
struct NodeConnection {
    /// Connection status shows whether a connection used or not.
    status: NodeConnectionStatus,
    /// List of relays we are connected to the node through.
    connections: HashSet<PublicKey>,
}

impl NodeConnection {
    /// Create new `NodeConnection` struct.
    fn new() -> NodeConnection {
        NodeConnection {
            status: NodeConnectionStatus::TCP,
            connections: HashSet::new(),
        }
    }

    /// Get an iterator over connected relays.
    fn clients<'c, 'a: 'c, 'b: 'c>(&'a self, clients: &'b HashMap<PublicKey, Client>) -> impl Iterator<Item = &'b Client> + 'c {
        self.connections
            .iter()
            .flat_map(move |relay_pk| clients.get(relay_pk).into_iter())
    }
}

/// TCP connections provides reliable connection to a friend via multiple TCP
/// relays.
#[derive(Clone)]
pub struct Connections {
    /// DHT `PublicKey`
    dht_pk: PublicKey,
    /// DHT `SecretKey`
    dht_sk: SecretKey,
    /// Sink for packets that should be handled somewhere else. `PublicKey` here
    /// belongs to TCP relay we received packet from.
    incoming_tx: mpsc::UnboundedSender<(PublicKey, IncomingPacket)>,
    /// List of TCP relays we are connected to. Key is a `PublicKey` of TCP
    /// relay.
    clients: Arc<RwLock<HashMap<PublicKey, Client>>>,
    /// List of DHT nodes we are connected to via TCP relays. Key is a
    /// `PublicKey` of DHT node.
    connections: Arc<RwLock<HashMap<PublicKey, NodeConnection>>>,
}

impl Connections {
    /// Create new TCP connections object.
    pub fn new(dht_pk: PublicKey, dht_sk: SecretKey, incoming_tx: mpsc::UnboundedSender<(PublicKey, IncomingPacket)>) -> Self {
        Connections {
            dht_pk,
            dht_sk,
            incoming_tx,
            clients: Arc::new(RwLock::new(HashMap::new())),
            connections: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Add relay we are supposed to be connected to. These relays are necessary
    /// for initial connection so that we are able to find friends and to send
    /// them our relays. Later when more relays are received from our friends
    /// they should be added via `add_relay_connection` method.
    pub async fn add_relay_global(&self, relay_addr: SocketAddr, relay_pk: PublicKey) -> Result<(), ConnectionError> {
        if let hash_map::Entry::Vacant(vacant) = self.clients.write().await.entry(relay_pk) {
            let client = Client::new(relay_pk, relay_addr, self.incoming_tx.clone());
            vacant.insert(client.clone());
            client.spawn(self.dht_sk.clone(), self.dht_pk)
                .map_err(|e| e.context(ConnectionErrorKind::Spawn).into()).await
        } else {
            trace!("Attempt to add relay that already exists: {}", relay_addr);
            Ok(())
        }
    }

    /// Add relay that we received from our friend. This relay can be ignored if
    /// we already connected to this friend via at least
    /// `RECOMMENDED_FRIEND_TCP_CONNECTIONS` relays. Connection to our friend
    /// via this relay will be added as well.
    pub async fn add_relay_connection(&self, relay_addr: SocketAddr, relay_pk: PublicKey, node_pk: PublicKey) -> Result<(), ConnectionError> {
        let mut clients = self.clients.write().await;
        if let Some(client) = clients.get(&relay_pk) {
            self.add_connection_inner(client, node_pk).await
        } else {
            let mut connections = self.connections.write().await;
            let connection = connections.entry(node_pk).or_insert_with(NodeConnection::new);

            let connections_count = connection.connections.len();
            let mut online_connections_count = 0;
            for relay_pk in connection.connections.iter() {
                if let Some(client) = clients.get(relay_pk) {
                    if client.is_connection_online(node_pk).await {
                        online_connections_count += 1;
                    }
                }
            }

            if online_connections_count < RECOMMENDED_FRIEND_TCP_CONNECTIONS && connections_count < MAX_FRIEND_TCP_CONNECTIONS {
                let client = Client::new(relay_pk, relay_addr, self.incoming_tx.clone());
                clients.insert(relay_pk, client.clone());
                connection.connections.insert(relay_pk);
                client.add_connection(node_pk).await;
                client.spawn(self.dht_sk.clone(), self.dht_pk).await
                    .map_err(|e| e.context(ConnectionErrorKind::Spawn).into())
            } else {
                Ok(())
            }
        }
    }

    /// Add a connection to our friend via relay. It means that we will send
    /// `RouteRequest` packet to this relay and wait for the friend to become
    /// connected.
    pub async fn add_connection(&self, relay_pk: PublicKey, node_pk: PublicKey) -> Result<(), ConnectionError> {
        if let Some(client) = self.clients.read().await.get(&relay_pk) {
            self.add_connection_inner(client, node_pk).await
        } else {
            Err(ConnectionErrorKind::NoSuchRelay.into())
        }
    }

    /// Remove connection to a friend via relays.
    pub async fn remove_connection(&self, node_pk: PublicKey) -> Result<(), ConnectionError> {
        if let Some(connection) = self.connections.write().await.remove(&node_pk) {
            let clients = self.clients.read().await;
            for client in connection.clients(&clients) {
                client.remove_connection(node_pk).await.ok();
            }
            Ok(())
        } else {
            // TODO: what if we didn't receive relays from friend and delete him?
            Err(ConnectionErrorKind::NoConnection.into())
        }
    }

    /// Inner function to add a connection to our friend via relay.
    async fn add_connection_inner(&self, client: &Client, node_pk: PublicKey) -> Result<(), ConnectionError> {
        // TODO: check MAX_FRIEND_TCP_CONNECTIONS?
        let mut connections = self.connections.write().await;
        let connection = connections.entry(node_pk).or_insert_with(NodeConnection::new);
        connection.connections.insert(client.pk);

        if connection.status == NodeConnectionStatus::TCP && client.is_sleeping().await {
            // unsleep relay
            client.clone().spawn(self.dht_sk.clone(), self.dht_pk).await
                .map_err(|e| ConnectionError::from(e.context(ConnectionErrorKind::Spawn)))?;
        };

        client.add_connection(node_pk).await;

        Ok(())
    }

    /// Send `Data` packet to a node via one of the relays.
    pub async fn send_data(&self, node_pk: PublicKey, data: DataPayload) -> Result<(), ConnectionError> {
        let connections = self.connections.read().await;

        // send packet to the first relay only that can accept it
        // errors are ignored
        // TODO: return error if stream is exhausted?
        if let Some(connection) = connections.get(&node_pk) {
            let clients = self.clients.read().await;

            for c in connection.clients(&*clients) {
                let res = c.send_data(node_pk, data.clone()).await;

                if res.is_ok() { break }
            }
        }

        // TODO: send as OOB?
        Ok(())
    }

    /// Send `OobSend` packet to a node via relay with specified `PublicKey`.
    pub async fn send_oob(&self, relay_pk: PublicKey, node_pk: PublicKey, data: Vec<u8>) -> Result<(), ConnectionError> {
        let clients = self.clients.read().await;
        if let Some(client) = clients.get(&relay_pk) {
            client.send_oob(node_pk, data).await
                .map_err(|e| e.context(ConnectionErrorKind::SendTo).into())
        } else {
            Err(ConnectionErrorKind::NotConnected.into())
        }
    }

    /// Send `OnionRequest` packet to relay with specified `PublicKey`.
    pub async fn send_onion(&self, relay_pk: PublicKey, onion_request: OnionRequest) -> Result<(), ConnectionError> {
        let clients = self.clients.read().await;
        if let Some(client) = clients.get(&relay_pk) {
            client.send_onion(onion_request).await
                .map_err(|e| e.context(ConnectionErrorKind::SendTo).into())
        } else {
            Err(ConnectionErrorKind::NotConnected.into())
        }
    }

    /// Change status of connection to the node. Connections module need to know
    /// whether connection is used to be able to put to sleep relay connections.
    pub async fn set_connection_status(&self, node_pk: PublicKey, status: NodeConnectionStatus) -> Result<(), ConnectionError> {
        if let Some(connection) = self.connections.write().await.get_mut(&node_pk) {
            if status == NodeConnectionStatus::TCP && connection.status == NodeConnectionStatus::UDP {
                // unsleep clients
                let clients = self.clients.read().await;
                for client in connection.clients(&clients) {
                    client.clone().spawn(self.dht_sk.clone(), self.dht_pk).await
                        .map_err(|e| e.context(ConnectionErrorKind::Spawn))?;
                }
            };
            connection.status = status;
            Ok(())
        } else {
            Err(ConnectionErrorKind::NoSuchRelay.into())
        }
    }

    /// Get a random TCP relay we are connected to.
    pub async fn get_random_relay(&self) -> Option<PackedNode> {
        let mut relays = Vec::new();
        for client in self.clients.read().await.values() {
            if client.is_connected().await {
                relays.push(PackedNode::new(client.addr, &client.pk));
            }
        }

        if relays.is_empty() {
            None
        } else {
            Some(relays[random_limit_usize(relays.len())])
        }
    }

    /// Get up to `count` random TCP relays we are connected to.
    pub async fn get_random_relays(&self, count: u8) -> Vec<PackedNode> {
        let mut relays = Vec::new();
        for client in self.clients.read().await.values() {
            if client.is_connected().await {
                relays.push(PackedNode::new(client.addr, &client.pk));
            }
        }

        if relays.is_empty() {
            return Vec::new();
        }

        // TODO: shuffle relays instead
        let skip = random_limit_usize(relays.len());
        let take = (count as usize).min(relays.len());
        relays.into_iter().cycle().skip(skip).take(take).collect()
    }

    /// Main loop that should be run periodically. It removes unreachable and
    /// redundant relays, reconnects to relays if a connection was lost, puts
    /// relays to sleep if they are not used right now.
    async fn main_loop(&self) -> Result<(), ConnectionError> {
        let mut clients = self.clients.write().await;
        let mut connections = self.connections.write().await;

        // If we have at least one connected relay that means that our network
        // connection is fine. So if we can't connect to some relays we can
        // drop them.
        let mut connected = false;
        for client in clients.values() {
            if client.is_connected().await {
                connected = true;
                break;
            }
        }

        let mut to_remove = Vec::new();
        for (&pk, client) in clients.iter() {
            if client.is_disconnected().await {
                if connected && client.connection_attempts().await > MAX_RECONNECTION_ATTEMPTS {
                    to_remove.push(pk);
                } else {
                    client.clone().spawn(self.dht_sk.clone(), self.dht_pk).await
                        .map_err(|e| e.context(ConnectionErrorKind::Spawn))?;
                }
            }
        }

        for pk in to_remove {
            clients.remove(&pk);
        }

        // find out which relays are used right now
        let used_relays = connections.values()
            .filter(|connection| connection.status == NodeConnectionStatus::TCP)
            .flat_map(|connection| connection.connections.iter().cloned())
            .collect::<HashSet<_>>();

        // send to sleep not used right now relays
        for client in clients.values() {
            // only connected relays have connected_time
            if client.connected_time().await.map_or(
                false,
                |connected_time| clock_elapsed(connected_time) > TCP_CONNECTION_ANNOUNCE_TIMEOUT
            ) && !used_relays.contains(&client.pk) {
                client.sleep().await;
            }
        }

        // remove not used relays
        let mut clients_len = clients.len();
        let mut to_remove = Vec::new();
        for (&pk, client) in clients.iter() {
            if clients_len > RECOMMENDED_FRIEND_TCP_CONNECTIONS && client.connections_count().await == 0 {
                clients_len -= 1;
                client.disconnect().await;
                to_remove.push(pk);
            }
        }

        for pk in to_remove {
            clients.remove(&pk);
        }

        // remove deleted relays from connections
        for connection in connections.values_mut() {
            connection.connections.retain(|relay_pk| clients.contains_key(relay_pk));

            // TODO: remove connections if there are too many?
        }

        Ok(())
    }

    /// Run TCP periodical tasks. Result future will never be completed
    /// successfully.
    pub async fn run(&self) -> Result<(), ConnectionError> {
        let mut wakeups = tokio::time::interval(CONNECTIONS_INTERVAL);

        while wakeups.next().await.is_some() {
            self.main_loop().await?
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tox_binary_io::*;

    use tox_packet::dht::CryptoData;
    use tox_packet::ip_port::*;
    use crate::relay::client::client::tests::*;
    use tox_packet::relay::connection_id::ConnectionId;

    impl Connections {
        pub async fn add_client(&self) -> (mpsc::UnboundedReceiver<(PublicKey, IncomingPacket)>, mpsc::Receiver<Packet>, PublicKey) {
            let (incoming_rx, outgoing_rx, client) = create_client().await;
            let relay_pk = client.pk;
            self.clients.write().await.insert(client.pk, client);
            (incoming_rx, outgoing_rx, relay_pk)
        }

        pub async fn has_relay(&self, relay_pk: &PublicKey) -> bool {
            self.clients.read().await.contains_key(relay_pk)
        }

        pub async fn has_connection(&self, node_pk: &PublicKey) -> bool {
            self.connections.read().await.contains_key(node_pk)
        }
    }

    #[tokio::test]
    async fn add_relay_global() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let addr = "0.0.0.0:12347".parse().unwrap();
        let (relay_pk, _relay_sk) = gen_keypair();

        connections.add_relay_global(addr, relay_pk).await.unwrap();

        assert!(connections.clients.read().await.contains_key(&relay_pk));
    }

    #[tokio::test]
    async fn add_relay_global_exists() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (_incoming_rx, _outgoing_rx, client) = create_client().await;
        let addr = client.addr;
        let relay_pk = client.pk;

        connections.clients.write().await.insert(relay_pk, client);

        // new connection shouldn't be spawned
        connections.add_relay_global(addr, relay_pk).await.unwrap();
    }

    #[tokio::test]
    async fn add_relay_connection() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let addr = "0.0.0.0:12347".parse().unwrap();
        let (relay_pk, _relay_sk) = gen_keypair();
        let (node_pk, _node_sk) = gen_keypair();

        connections.add_relay_connection(addr, relay_pk, node_pk).await.unwrap();

        let clients = connections.clients.read().await;
        let connections = connections.connections.read().await;

        assert!(clients.contains_key(&relay_pk));
        assert!(clients.get(&relay_pk).unwrap().has_connection(node_pk).await);

        assert!(connections.contains_key(&node_pk));
        assert_eq!(connections.get(&node_pk).unwrap().status, NodeConnectionStatus::TCP);
        assert!(connections.get(&node_pk).unwrap().connections.contains(&relay_pk));
    }

    #[tokio::test]
    async fn add_relay_connection_relay_exists() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (_incoming_rx, _outgoing_rx, client) = create_client().await;
        let addr = client.addr;
        let relay_pk = client.pk;

        connections.clients.write().await.insert(relay_pk, client);

        let (node_pk, _node_sk) = gen_keypair();

        // new connection shouldn't be spawned
        connections.add_relay_connection(addr, relay_pk, node_pk).await.unwrap();

        let clients = connections.clients.read().await;
        let connections = connections.connections.read().await;

        assert!(clients.contains_key(&relay_pk));
        assert!(clients.get(&relay_pk).unwrap().has_connection(node_pk).await);

        assert!(connections.contains_key(&node_pk));
        assert_eq!(connections.get(&node_pk).unwrap().status, NodeConnectionStatus::TCP);
        assert!(connections.get(&node_pk).unwrap().connections.contains(&relay_pk));
    }

    #[tokio::test]
    async fn add_connection() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (_incoming_rx, _outgoing_rx, client) = create_client().await;
        let relay_pk = client.pk;

        connections.clients.write().await.insert(relay_pk, client);

        let (node_pk, _node_sk) = gen_keypair();

        // new connection shouldn't be spawned
        connections.add_connection(relay_pk, node_pk).await.unwrap();

        let clients = connections.clients.read().await;
        let connections = connections.connections.read().await;

        assert!(clients.contains_key(&relay_pk));
        assert!(clients.get(&relay_pk).unwrap().has_connection(node_pk).await);

        assert!(connections.contains_key(&node_pk));
        assert_eq!(connections.get(&node_pk).unwrap().status, NodeConnectionStatus::TCP);
        assert!(connections.get(&node_pk).unwrap().connections.contains(&relay_pk));
    }

    #[tokio::test]
    async fn add_connection_no_relay() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (relay_pk, _relay_sk) = gen_keypair();
        let (node_pk, _node_sk) = gen_keypair();

        let error = connections.add_connection(relay_pk, node_pk).await.err().unwrap();
        assert_eq!(*error.kind(), ConnectionErrorKind::NoSuchRelay);
    }

    #[tokio::test]
    async fn remove_connection() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (node_pk, _node_sk) = gen_keypair();

        let (_incoming_rx, _outgoing_rx, client) = create_client().await;
        let relay_pk = client.pk;

        client.add_connection(node_pk).await;

        let mut node_connection = NodeConnection::new();
        node_connection.connections.insert(relay_pk);

        connections.clients.write().await.insert(relay_pk, client);
        connections.connections.write().await.insert(node_pk, node_connection);

        connections.remove_connection(node_pk).await.unwrap();

        let clients = connections.clients.read().await;
        let connections = connections.connections.read().await;

        assert!(!clients.get(&relay_pk).unwrap().has_connection(node_pk).await);

        assert!(!connections.contains_key(&node_pk));
    }

    #[tokio::test]
    async fn remove_connection_no_connection() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (node_pk, _node_sk) = gen_keypair();

        let error = connections.remove_connection(node_pk).await.err().unwrap();
        assert_eq!(*error.kind(), ConnectionErrorKind::NoConnection);
    }

    #[tokio::test]
    async fn send_data() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (_incoming_rx_0, _outgoing_rx_0, relay_0) = create_client().await;
        let (_incoming_rx_1, outgoing_rx_1, relay_1) = create_client().await;
        let (_incoming_rx_2, outgoing_rx_2, relay_2) = create_client().await;

        let (destination_pk, _destination_sk) = gen_keypair();

        // add connection to destination_pk to be able to send data packets
        relay_1.add_connection(destination_pk).await;
        relay_2.add_connection(destination_pk).await;

        // receive route request
        let outgoing_rx_1 = outgoing_rx_1.into_future().await.1;
        let outgoing_rx_2 = outgoing_rx_2.into_future().await.1;

        // make connections online
        relay_1.handle_packet(Packet::RouteResponse(RouteResponse {
            connection_id: ConnectionId::from_index(42),
            pk: destination_pk,
        })).await.unwrap();
        relay_2.handle_packet(Packet::RouteResponse(RouteResponse {
            connection_id: ConnectionId::from_index(42),
            pk: destination_pk,
        })).await.unwrap();
        relay_1.handle_packet(Packet::ConnectNotification(ConnectNotification {
            connection_id: ConnectionId::from_index(42),
        })).await.unwrap();
        relay_2.handle_packet(Packet::ConnectNotification(ConnectNotification {
            connection_id: ConnectionId::from_index(42),
        })).await.unwrap();

        connections.connections.write().await.insert(destination_pk, NodeConnection {
            status: NodeConnectionStatus::TCP,
            connections: [relay_0.pk, relay_1.pk, relay_2.pk].iter().cloned().collect(),
        });
        connections.clients.write().await.insert(relay_0.pk, relay_0);
        connections.clients.write().await.insert(relay_1.pk, relay_1);
        connections.clients.write().await.insert(relay_2.pk, relay_2);

        let data = DataPayload::CryptoData(CryptoData {
            nonce_last_bytes: 42,
            payload: vec![42; 123],
        });

        connections.send_data(destination_pk, data.clone()).await.unwrap();

        // Necessary to drop tx so that rx.collect() can be finished
        drop(connections);

        // data packet should be sent only once
        let packets: Vec<_> = outgoing_rx_1.chain(outgoing_rx_2).collect().await;
        assert_eq!(packets.len(), 1);
        let packet = unpack!(packets[0].clone(), Packet::Data);

        assert_eq!(packet.data, data);
    }

    #[tokio::test]
    async fn send_data_no_connection() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (destination_pk, _destination_sk) = gen_keypair();

        let data = DataPayload::CryptoData(CryptoData {
            nonce_last_bytes: 42,
            payload: vec![42; 123],
        });
        connections.send_data(destination_pk, data).await.unwrap();
    }

    #[tokio::test]
    async fn send_oob() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (destination_pk, _destination_sk) = gen_keypair();

        let (_incoming_rx, outgoing_rx, client) = create_client().await;
        let relay_pk = client.pk;

        connections.clients.write().await.insert(client.pk, client);

        let data = vec![42; 123];

        connections.send_oob(relay_pk, destination_pk, data.clone()).await.unwrap();

        let packet = unpack!(outgoing_rx.into_future().await.0.unwrap(), Packet::OobSend);

        assert_eq!(packet.data, data);
    }

    #[tokio::test]
    async fn send_oob_no_relay() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (destination_pk, _destination_sk) = gen_keypair();
        let (relay_pk, _relay_sk) = gen_keypair();

        let error = connections.send_oob(relay_pk, destination_pk, vec![42; 123]).await.err().unwrap();
        assert_eq!(*error.kind(), ConnectionErrorKind::NotConnected);
    }

    #[tokio::test]
    async fn send_onion() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (_incoming_rx, outgoing_rx, client) = create_client().await;
        let relay_pk = client.pk;

        connections.clients.write().await.insert(client.pk, client);

        let onion_request = OnionRequest {
            nonce: gen_nonce(),
            ip_port: IpPort {
                protocol: ProtocolType::TCP,
                ip_addr: "5.6.7.8".parse().unwrap(),
                port: 12345,
            },
            temporary_pk: gen_keypair().0,
            payload: vec![42; 123],
        };

        connections.send_onion(relay_pk, onion_request.clone()).await.unwrap();

        let packet = unpack!(outgoing_rx.into_future().await.0.unwrap(), Packet::OnionRequest);

        assert_eq!(packet, onion_request);
    }

    #[tokio::test]
    async fn send_onion_no_relay() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (relay_pk, _relay_sk) = gen_keypair();

        let onion_request = OnionRequest {
            nonce: gen_nonce(),
            ip_port: IpPort {
                protocol: ProtocolType::TCP,
                ip_addr: "5.6.7.8".parse().unwrap(),
                port: 12345,
            },
            temporary_pk: gen_keypair().0,
            payload: vec![42; 123],
        };

        let error = connections.send_onion(relay_pk, onion_request.clone()).await.err().unwrap();
        assert_eq!(*error.kind(), ConnectionErrorKind::NotConnected);
    }

    #[tokio::test]
    async fn set_connection_status() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (node_pk, _node_sk) = gen_keypair();

        connections.connections.write().await.insert(node_pk, NodeConnection {
            status: NodeConnectionStatus::TCP,
            connections: HashSet::new(),
        });

        connections.set_connection_status(node_pk, NodeConnectionStatus::UDP).await.unwrap();

        assert_eq!(connections.connections.read().await.get(&node_pk).unwrap().status, NodeConnectionStatus::UDP);
    }

    #[tokio::test]
    async fn set_connection_status_no_connection() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (node_pk, _node_sk) = gen_keypair();

        let error = connections.set_connection_status(node_pk, NodeConnectionStatus::UDP).await.err().unwrap();
        assert_eq!(*error.kind(), ConnectionErrorKind::NoSuchRelay);
    }

    #[tokio::test]
    async fn get_random_relay() {
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (_incoming_rx_1, _outgoing_rx_1, relay_1) = create_client().await;
        let relay_pk_1 = relay_1.pk;

        connections.clients.write().await.insert(relay_pk_1, relay_1);

        // add one more disconnected relay to make sure that it won't be
        // included to `get_random_relays` result
        let relay_pk_2 = gen_keypair().0;
        let relay_addr_2 = "127.0.0.1:33445".parse().unwrap();
        let (incoming_tx_2, _incoming_rx_2) = mpsc::unbounded();
        let relay_2 = Client::new(relay_pk_2, relay_addr_2, incoming_tx_2);

        connections.clients.write().await.insert(relay_pk_2, relay_2);

        let relay = connections.get_random_relay().await.unwrap();
        assert_eq!(relay.pk, relay_pk_1);
    }

    #[tokio::test]
    async fn get_random_relays() {
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (_incoming_rx_1, _outgoing_rx_1, relay_1) = create_client().await;
        let (_incoming_rx_2, _outgoing_rx_2, relay_2) = create_client().await;
        let relay_pk_1 = relay_1.pk;
        let relay_pk_2 = relay_2.pk;

        connections.clients.write().await.insert(relay_pk_1, relay_1);
        connections.clients.write().await.insert(relay_pk_2, relay_2);

        // add one more disconnected relay to make sure that it won't be
        // included to `get_random_relays` result
        let relay_pk_3 = gen_keypair().0;
        let relay_addr_3 = "127.0.0.1:33445".parse().unwrap();
        let (incoming_tx_3, _incoming_rx_3) = mpsc::unbounded();
        let relay_3 = Client::new(relay_pk_3, relay_addr_3, incoming_tx_3);

        connections.clients.write().await.insert(relay_pk_3, relay_3);

        let relays = connections.get_random_relays(1).await;
        assert_eq!(relays.len(), 1);
        let relays = connections.get_random_relays(4).await;
        assert_eq!(relays.len(), 2);
    }

    #[tokio::test]
    async fn get_random_relays_empty() {
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let relays = connections.get_random_relays(1).await;
        assert!(relays.is_empty());
    }

    #[tokio::test]
    async fn main_loop_put_to_sleep() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (_incoming_rx_1, _outgoing_rx_1, relay_1) = create_client().await;
        let (_incoming_rx_2, _outgoing_rx_2, relay_2) = create_client().await;
        let relay_pk_1 = relay_1.pk;
        let relay_pk_2 = relay_2.pk;

        let (node_pk_1, _node_sk_1) = gen_keypair();
        let (node_pk_2, _node_sk_2) = gen_keypair();

        connections.connections.write().await.insert(node_pk_1, NodeConnection {
            status: NodeConnectionStatus::TCP,
            connections: [relay_pk_1].iter().cloned().collect(),
        });
        connections.connections.write().await.insert(node_pk_2, NodeConnection {
            status: NodeConnectionStatus::UDP,
            connections: [relay_pk_2].iter().cloned().collect(),
        });

        connections.clients.write().await.insert(relay_pk_1, relay_1);
        connections.clients.write().await.insert(relay_pk_2, relay_2);

        tokio::time::pause();
        // time when we don't wait for connections to appear
        tokio::time::advance(TCP_CONNECTION_ANNOUNCE_TIMEOUT + Duration::from_secs(1)).await;

        connections.main_loop().await.unwrap();

        let clients = connections.clients.read().await;

        assert!(clients.get(&relay_pk_1).unwrap().is_connected().await);
        assert!(clients.get(&relay_pk_2).unwrap().is_sleeping().await);
    }

    #[tokio::test]
    async fn main_loop_remove_unsuccessful() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (_incoming_rx_0, _outgoing_rx_0, relay_0) = create_client().await;
        let (_incoming_rx_1, _outgoing_rx_1, relay_1) = create_client().await;
        let (_incoming_rx_2, _outgoing_rx_2, relay_2) = create_client().await;
        let relay_pk_0 = relay_0.pk;
        let relay_pk_1 = relay_1.pk;
        let relay_pk_2 = relay_2.pk;

        relay_1.disconnect().await;
        relay_2.disconnect().await;

        set_connection_attempts(&relay_1, MAX_RECONNECTION_ATTEMPTS + 1).await;

        let (node_pk, _node_sk) = gen_keypair();

        connections.connections.write().await.insert(node_pk, NodeConnection {
            status: NodeConnectionStatus::TCP,
            connections: [relay_pk_0, relay_pk_1, relay_pk_2].iter().cloned().collect(),
        });

        connections.clients.write().await.insert(relay_pk_0, relay_0);
        connections.clients.write().await.insert(relay_pk_1, relay_1);
        connections.clients.write().await.insert(relay_pk_2, relay_2);

        connections.main_loop().await.unwrap();

        let clients = connections.clients.read().await;

        assert!(clients.contains_key(&relay_pk_0));
        assert!(!clients.contains_key(&relay_pk_1));
        assert!(clients.contains_key(&relay_pk_2));

        let connections = connections.connections.read().await;
        let connection = connections.get(&node_pk).unwrap();

        assert!(connection.connections.contains(&relay_pk_0));
        assert!(!connection.connections.contains(&relay_pk_1));
        assert!(connection.connections.contains(&relay_pk_2));
    }

    #[tokio::test]
    async fn main_loop_remove_not_used() {
        crypto_init().unwrap();
        let (dht_pk, dht_sk) = gen_keypair();
        let (incoming_tx, _incoming_rx) = mpsc::unbounded();
        let connections = Connections::new(dht_pk, dht_sk, incoming_tx);

        let (_incoming_rx_0, _outgoing_rx_0, relay_0) = create_client().await;
        let (_incoming_rx_1, _outgoing_rx_1, relay_1) = create_client().await;
        let (_incoming_rx_2, _outgoing_rx_2, relay_2) = create_client().await;
        let (_incoming_rx_3, _outgoing_rx_3, relay_3) = create_client().await;
        let relay_0_c = relay_0.clone();
        let relay_pk_0 = relay_0.pk;
        let relay_pk_1 = relay_1.pk;
        let relay_pk_2 = relay_2.pk;
        let relay_pk_3 = relay_3.pk;

        let (node_pk, _node_sk) = gen_keypair();

        relay_1.add_connection(node_pk).await;
        relay_2.add_connection(node_pk).await;
        relay_3.add_connection(node_pk).await;

        connections.connections.write().await.insert(node_pk, NodeConnection {
            status: NodeConnectionStatus::TCP,
            connections: [relay_pk_1, relay_pk_2, relay_pk_3].iter().cloned().collect(),
        });

        connections.clients.write().await.insert(relay_pk_0, relay_0);
        connections.clients.write().await.insert(relay_pk_1, relay_1);
        connections.clients.write().await.insert(relay_pk_2, relay_2);
        connections.clients.write().await.insert(relay_pk_3, relay_3);

        connections.main_loop().await.unwrap();

        let clients = connections.clients.read().await;

        assert!(!clients.contains_key(&relay_pk_0));
        assert!(clients.contains_key(&relay_pk_1));
        assert!(clients.contains_key(&relay_pk_2));
        assert!(clients.contains_key(&relay_pk_3));

        assert!(relay_0_c.is_disconnected().await);
    }
}