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
use super::{
    error::NetworkErrors,
    routing::{RoutingBehaviour, RoutingComposedEvent},
    tell::{TellBehaviour, TellBehaviourEvent},
};
use crate::{
    commons::crypto::{KeyMaterial, KeyPair},
    ListenAddr,
};
use crate::{
    message::{Command, NetworkEvent},
    Notification,
};

use futures::StreamExt;
use instant::Duration;
use libp2p::{
    core::{
        either::EitherError,
        muxing::StreamMuxerBox,
        transport::{Boxed, MemoryTransport},
        upgrade,
    },
    dns,
    identity::{ed25519, Keypair},
    kad::{
        AddProviderOk, GetClosestPeersError, GetClosestPeersOk, KademliaEvent, PeerRecord,
        PutRecordOk, QueryResult,
    },
    mplex,
    multiaddr::Protocol,
    noise,
    swarm::{AddressScore, ConnectionHandlerUpgrErr, NetworkBehaviour, SwarmBuilder, SwarmEvent},
    tcp::TokioTcpConfig,
    yamux, Multiaddr, NetworkBehaviour, PeerId, Swarm, Transport,
};
use log::{debug, error, info};
use std::collections::{HashMap, HashSet, VecDeque};
use std::error::Error;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

#[cfg(test)]
use libp2p::kad::{record::Key, QueryId, Quorum, Record};

const LOG_TARGET: &str = "TAPLE_NETWORT::Network";
const RETRY_TIMEOUT: u64 = 30000;

type TapleSwarmEvent = SwarmEvent<
    NetworkComposedEvent,
    EitherError<
        EitherError<std::io::Error, std::io::Error>,
        ConnectionHandlerUpgrErr<std::io::Error>,
    >,
>;

#[allow(dead_code)]
pub enum SendMode {
    RequestResponse,
    Tell,
}

#[derive(NetworkBehaviour)]
#[behaviour(out_event = "NetworkComposedEvent")]
pub struct TapleNetworkBehavior {
    routing: RoutingBehaviour,
    tell: TellBehaviour,
}

#[derive(Debug)]
pub enum NetworkComposedEvent {
    TellBehaviourEvent(TellBehaviourEvent),
    RoutingEvent(RoutingComposedEvent),
}

/// Adapt `IdentifyEvent` to `NetworkComposedEvent`
impl From<TellBehaviourEvent> for NetworkComposedEvent {
    fn from(event: TellBehaviourEvent) -> NetworkComposedEvent {
        NetworkComposedEvent::TellBehaviourEvent(event)
    }
}

/// Adapt `RoutingEvent` to `NetworkComposedEvent`
impl From<RoutingComposedEvent> for NetworkComposedEvent {
    fn from(event: RoutingComposedEvent) -> NetworkComposedEvent {
        NetworkComposedEvent::RoutingEvent(event)
    }
}

impl TapleNetworkBehavior {
    pub fn new(local_key: Keypair, bootstrap_nodes: Vec<(PeerId, Multiaddr)>) -> Self {
        let routing = RoutingBehaviour::new(local_key, bootstrap_nodes);
        let tell = TellBehaviour::new(100000, Duration::from_secs(10), Duration::from_secs(10));
        TapleNetworkBehavior { routing, tell }
    }

    #[cfg(test)]
    pub fn send_message(&mut self, peer: &PeerId, data: &[u8]) {
        self.tell.send_message(peer, data);
    }

    #[cfg(test)]
    pub fn bootstrap(&mut self) {
        self.routing.bootstrap();
    }

    #[cfg(test)]
    pub fn handle_rout_ev(&mut self, ev: RoutingComposedEvent) {
        self.routing.handle_event(ev);
    }

    #[allow(dead_code)]
    #[cfg(test)]
    pub fn put_record(
        &mut self,
        record: Record,
        quorum: Quorum,
    ) -> Result<QueryId, libp2p::kad::record::store::Error> {
        self.routing.put_record(record, quorum)
    }

    #[allow(dead_code)]
    #[cfg(test)]
    pub fn get_record(&mut self, key: Key, quorum: Quorum) -> QueryId {
        self.routing.get_record(key, quorum)
    }
}

fn check_listen_addr_integrity(addrs: &Vec<ListenAddr>) -> Result<ListenProtocols, NetworkErrors> {
    let mut has_memory = false;
    let mut has_ip = false;
    for addr in addrs {
        match addr {
            ListenAddr::Memory { .. } => has_memory = true,
            ListenAddr::IP4 { .. } => has_ip = true,
            ListenAddr::IP6 { .. } => has_ip = true,
        }
    }
    if has_memory && has_ip {
        return Err(NetworkErrors::ProtocolConflict);
    }
    if has_ip {
        return Ok(ListenProtocols::IP);
    } else {
        return Ok(ListenProtocols::Memory);
    }
}

/// Network Structure for connect message-sender, message-receiver and LibP2P network stack
pub struct NetworkProcessor {
    addr: Vec<ListenAddr>,
    swarm: Swarm<TapleNetworkBehavior>,
    command_sender: mpsc::Sender<Command>,
    command_receiver: mpsc::Receiver<Command>,
    event_sender: mpsc::Sender<NetworkEvent>,
    pendings: HashMap<PeerId, VecDeque<Vec<u8>>>,
    active_get_querys: HashSet<PeerId>,
    token: CancellationToken,
    notification_tx: tokio::sync::mpsc::Sender<Notification>,
    bootstrap_nodes: Vec<(PeerId, Multiaddr)>,
    pending_bootstrap_nodes: HashMap<PeerId, Multiaddr>,
    bootstrap_retries_steam:
        futures::stream::futures_unordered::FuturesUnordered<tokio::time::Sleep>,
    node_public_key: Vec<u8>,
    external_addresses: Vec<Multiaddr>,
}

enum ListenProtocols {
    Memory,
    IP,
}

impl NetworkProcessor {
    pub fn new(
        addr: Vec<ListenAddr>,
        bootstrap_nodes: Vec<(PeerId, Multiaddr)>,
        event_sender: mpsc::Sender<NetworkEvent>,
        controller_mc: KeyPair,
        token: CancellationToken,
        notification_tx: tokio::sync::mpsc::Sender<Notification>,
        external_addresses: Vec<Multiaddr>,
    ) -> Result<Self, Box<dyn Error>> {
        let transport_protocol = check_listen_addr_integrity(&addr)?;
        let public_key = controller_mc.public_key_bytes();
        let local_key = {
            let sk = ed25519::SecretKey::from_bytes(controller_mc.secret_key_bytes())
                .expect("we always pass 32 bytes");
            Keypair::Ed25519(sk.into())
        };
        // Create a keypair for authenticated encryption of the transport.
        let noise_key: noise::AuthenticKeypair<noise::X25519Spec> =
            noise::Keypair::<noise::X25519Spec>::new()
                .into_authentic(&local_key)
                .expect("Signing libp2p-noise static DH keypair failed.");

        let transport = create_transport_by_protocol(transport_protocol, noise_key);
        let peer_id = local_key.public().to_peer_id();

        // Swarm creation
        let swarm = SwarmBuilder::new(
            transport,
            TapleNetworkBehavior::new(local_key, bootstrap_nodes.clone()),
            peer_id,
        )
        .executor(Box::new(|fut| {
            tokio::spawn(fut);
        }))
        .build();

        // Create channels to communicate events and commands
        let (command_sender, command_receiver) = mpsc::channel(10000);
        let pendings: HashMap<PeerId, VecDeque<Vec<u8>>> = HashMap::new();
        // let controller_to_peer: HashMap<Vec<u8>, PeerId> = HashMap::new();
        // let peer_to_controller: HashMap<PeerId, Vec<u8>> = HashMap::new();
        let active_get_querys: HashSet<PeerId> = HashSet::new();
        Ok(Self {
            node_public_key: public_key,
            addr,
            swarm,
            command_sender,
            command_receiver,
            event_sender,
            // controller_mc,
            pendings,
            // controller_to_peer,
            // peer_to_controller,
            active_get_querys,
            token,
            notification_tx,
            bootstrap_nodes,
            pending_bootstrap_nodes: HashMap::new(),
            bootstrap_retries_steam: futures::stream::futures_unordered::FuturesUnordered::new(),
            external_addresses,
        })
    }

    /// Network client
    pub fn client(&self) -> mpsc::Sender<Command> {
        self.command_sender.clone()
    }

    /// Run network processor.
    pub async fn run(mut self) {
        debug!("Running network");
        for external_address in self.external_addresses.clone().into_iter() {
            self.swarm
                .add_external_address(external_address, AddressScore::Infinite);
        }
        for addr in self.addr.iter() {
            if let Some(_) = addr.get_port() {
                let multiadd: Multiaddr = addr
                    .to_string()
                    .unwrap()
                    .parse()
                    .expect("String para multiaddress es válida");
                let result = self.swarm.listen_on(multiadd);
                if result.is_err() {
                    error!("Error: {:?}", result.unwrap_err());
                }
            }
        }
        for (_peer_id, addr) in self.bootstrap_nodes.iter() {
            let Ok(()) = self.swarm.dial(addr.to_owned()) else {
                    panic!("Conection with bootstrap failed");
                };
        }
        loop {
            tokio::select! {
                event = self.swarm.next() => self.handle_event(
                    event.expect("Swarm stream to be infinite.")).await,
                command = self.command_receiver.recv() => match command {
                    Some(c) => self.handle_command(c).await,
                    // Command channel closed, thus shutting down the network
                    // event loop.
                    None =>  {return;},
                },
                Some(_) = self.bootstrap_retries_steam.next() => self.connect_to_pending_bootstraps(),
                _ = self.token.cancelled() => {
                    log::debug!("Shutdown received");
                    break;
                }
            }
        }
        self.token.cancel();
        log::info!("Ended");
    }

    fn connect_to_pending_bootstraps(&mut self) {
        let keys: Vec<PeerId> = self.pending_bootstrap_nodes.keys().cloned().collect();
        for peer in keys {
            let addr = self.pending_bootstrap_nodes.remove(&peer).unwrap();
            let Ok(()) = self.swarm.dial(addr.to_owned()) else {
                panic!("Conection with bootstrap failed");
            };
        }
    }

    async fn handle_event(&mut self, event: TapleSwarmEvent) {
        match event {
            SwarmEvent::Dialing(peer_id) => {
                debug!("{}: Dialing to peer: {:?}", LOG_TARGET, peer_id);
            }
            SwarmEvent::NewListenAddr { address, .. } => {
                let local_peer_id = *self.swarm.local_peer_id();
                info!(
                    "listening on {:?}",
                    &address.with(Protocol::P2p(local_peer_id.into()))
                );
                // let addr_with_peer = address.clone().with(Protocol::P2p(local_peer_id.into()));
                // let addr_with_peer_bytes = addr_with_peer.to_vec();
                // let crypto_proof = self
                //     .controller_mc
                //     .sign(Payload::Buffer(addr_with_peer_bytes))
                //     .unwrap();
                // let value = bincode::serialize(&(addr_with_peer, crypto_proof)).unwrap();
                // match self.swarm.behaviour_mut().routing.put_record(
                //     Record {
                //         key: Key::new(&self.controller_mc.public_key_bytes()),
                //         value,
                //         publisher: None,
                //         expires: None,
                //     },
                //     Quorum::One,
                // ) {
                //     Ok(_) => (),
                //     Err(_) => panic!("HOLA"), // No debería fallar, ¿Tirarlo si falla?
                // }
            }
            SwarmEvent::ConnectionEstablished {
                peer_id, endpoint, ..
            } => {
                debug!(
                    "{}: Connected to {} at {}",
                    LOG_TARGET,
                    peer_id,
                    endpoint.get_remote_address()
                );
            }
            SwarmEvent::ConnectionClosed {
                peer_id,
                cause: Some(error),
                ..
            } => {
                debug!(
                    "{}: Disconnected from {} with error {}",
                    LOG_TARGET, peer_id, error
                );
            }
            SwarmEvent::OutgoingConnectionError { error, peer_id } => {
                // Fixme for refused connections
                debug!("{}: Connection error: {}", LOG_TARGET, error);
                if let Some(peer_id) = peer_id {
                    // Delete cache peer id and address for that controller
                    self.swarm.behaviour_mut().tell.remove_route(&peer_id);
                    // Check if the peerID was a bootstrap node
                    if let Some((id, multiaddr)) =
                        self.bootstrap_nodes.iter().find(|(id, _)| *id == peer_id)
                    {
                        self.pending_bootstrap_nodes
                            .insert(*id, multiaddr.to_owned());
                        // Insert new timer if there was not any before
                        if self.bootstrap_retries_steam.len() == 0 {
                            self.bootstrap_retries_steam
                                .push(tokio::time::sleep(Duration::from_millis(RETRY_TIMEOUT)));
                        }
                    }
                    // match self.peer_to_controller.remove(&peer_id) {
                    //     Some(controller) => {
                    //         self.controller_to_peer.remove(&controller);
                    //     }
                    //     None => {}
                    // }
                }
            }
            SwarmEvent::Behaviour(behaviour_event) => match behaviour_event {
                NetworkComposedEvent::TellBehaviourEvent(ev) => match ev {
                    TellBehaviourEvent::RequestSent { peer_id } => {
                        debug!("{}: Request sent to: {}", LOG_TARGET, peer_id);
                        // TODO: Thinking about whether to delete here the pending list for a controller
                    }
                    TellBehaviourEvent::RequestReceived { data, peer_id } => {
                        debug!("{}: Request received from: {}", LOG_TARGET, peer_id);
                        self.event_sender
                            .send(NetworkEvent::MessageReceived { message: data })
                            .await
                            .expect("Event receiver not to be dropped.");
                    }
                    TellBehaviourEvent::RequestFailed { peer_id } => {
                        debug!("{}: Request failed to send to: {}", LOG_TARGET, peer_id);
                        // Delete cache peer id and address for that controller
                        // match self.peer_to_controller.remove(&peer_id) {
                        //     Some(controller) => {
                        //         self.controller_to_peer.remove(&controller);
                        //     }
                        //     None => {}
                        // }
                    }
                },

                NetworkComposedEvent::RoutingEvent(ev) => match ev {
                    RoutingComposedEvent::KademliaEvent(
                        KademliaEvent::OutboundQueryCompleted {
                            id: _,
                            result,
                            stats: _,
                        },
                    ) => match result {
                        QueryResult::GetRecord(Ok(ok)) => {
                            for PeerRecord { record, .. } in ok.records {
                                debug!("Got Record {:?}", record);
                            }
                            // for PeerRecord {
                            //     record:
                            //         Record {
                            //             key,
                            //             value,
                            //             publisher,
                            //             ..
                            //         },
                            //     ..
                            // } in ok.records
                            // {
                            //     let mc_bytes = key.to_vec();
                            //     let mc = Ed25519KeyPair::from_public_key(&mc_bytes);
                            //     match bincode::deserialize::<(Multiaddr, Vec<u8>)>(&value) {
                            //         Ok((addr, crypto_proof)) => {
                            //             // Comprobar la firma
                            //             match mc
                            //                 .verify(Payload::Buffer(addr.to_vec()), &crypto_proof)
                            //             {
                            //                 Ok(_) => {
                            //                     // Si está bien guardar en los hashmaps la info y hacer dial
                            //                     // Obtener el peerId a partir de la addr:
                            //                     let mut peer_id: Option<PeerId> = None;
                            //                     for protocol in addr.clone().iter() {
                            //                         if let Protocol::P2p(peer_id_multihash) =
                            //                             protocol
                            //                         {
                            //                             match PeerId::from_multihash(peer_id_multihash) {
                            //                                 Ok(pid) => {
                            //                                     if let Some(peer_id_publisher) = publisher {
                            //                                         // Comprobación de que el publisher es el propio peerId que buscamos
                            //                                         if pid != peer_id_publisher {
                            //                                             continue;
                            //                                         }
                            //                                     }
                            //                                     peer_id = Some(pid);
                            //                                     break;
                            //                                 },
                            //                                 Err(_) => debug!("Error al parsear multiaddr a peerId en get"),
                            //                             }
                            //                         }
                            //                     }
                            //                     if peer_id.is_none() {
                            //                         continue;
                            //                     }
                            //                     let peer_id = peer_id.unwrap();
                            //                     match self.swarm.dial(addr.clone()) {
                            //                         Ok(_) => {
                            //                             debug!("Success en DIAL");
                            //                             // Si funciona el dial actualizar las estructuras de datos
                            //                             self.routing_cache
                            //                                 .insert(peer_id, vec![addr]);
                            //                             // self.controller_to_peer
                            //                             //     .insert(mc_bytes.clone(), peer_id);
                            //                             // self.peer_to_controller
                            //                             //     .insert(peer_id, mc_bytes.clone());
                            //                             self.active_get_querys.remove(&peer_id);
                            //                             // Mandar mensajes pendientes
                            //                             self.send_pendings(&peer_id);
                            //                         }
                            //                         Err(e) => {
                            //                             debug!("{}", e);
                            //                             continue;
                            //                         }
                            //                     }
                            //                 }
                            //                 Err(_) => {
                            //                     continue;
                            //                 }
                            //             }
                            //         }
                            //         Err(e) => {
                            //             debug!("DESERIALICE VA MAL");
                            //             debug!("Problemas al recuperar la Multiaddr del value del Record: {:?}", e);
                            //         }
                            //     }
                            // }
                        }
                        QueryResult::GetRecord(Err(err)) => {
                            debug!("Failed to get record: {:?}", err);
                            // let mc_bytes = err.key().to_vec();
                            // self.active_get_querys.remove(&mc_bytes);
                        }
                        QueryResult::PutRecord(Ok(PutRecordOk { key })) => {
                            debug!("Successfully put record {:?}", key);
                        }
                        QueryResult::PutRecord(Err(err)) => {
                            debug!("Failed to put record: {:?}", err);
                        }
                        QueryResult::GetProviders(Ok(ok)) => {
                            for peer in ok.providers {
                                debug!("Peer {:?} provides key {:?}", peer, ok.key.as_ref());
                            }
                        }
                        QueryResult::GetProviders(Err(err)) => {
                            debug!("Failed to get providers: {:?}", err);
                        }
                        QueryResult::StartProviding(Ok(AddProviderOk { key })) => {
                            debug!("Successfully put provider record {:?}", key);
                        }
                        QueryResult::StartProviding(Err(err)) => {
                            debug!("Failed to put provider record: {:?}", err);
                        }
                        QueryResult::GetClosestPeers(gcp_res) => match gcp_res {
                            Ok(GetClosestPeersOk { key, .. }) => {
                                debug!("GCP OK: {:?}", key);
                                let peer_id = match PeerId::from_bytes(&key) {
                                    Ok(peer_id) => peer_id,
                                    Err(_) => {
                                        log::error!("Error parsing PeerId from GCP Ok response");
                                        return;
                                    }
                                };
                                self.active_get_querys.remove(&peer_id);
                            }
                            Err(GetClosestPeersError::Timeout { key, .. }) => {
                                debug!("GCP ERR: {:?}", key);
                                let peer_id = match PeerId::from_bytes(&key) {
                                    Ok(peer_id) => peer_id,
                                    Err(_) => {
                                        log::error!("Error parsing PeerId from GCP Err response");
                                        return;
                                    }
                                };
                                self.active_get_querys.remove(&peer_id);
                            }
                        },
                        e => {
                            debug!("Unhandled QueryResult {:?}", e);
                        }
                    },
                    RoutingComposedEvent::KademliaEvent(KademliaEvent::RoutablePeer {
                        peer,
                        address,
                    }) => {
                        debug!(
                            "{}: Routable Peer: {:?}; Address: {:?}.",
                            LOG_TARGET, peer, address,
                        );
                        if self.active_get_querys.contains(&peer) {
                            self.swarm.behaviour_mut().tell.set_route(peer, address);
                            self.active_get_querys.remove(&peer);
                            self.send_pendings(&peer);
                        }
                    }
                    _ => {
                        self.swarm.behaviour_mut().routing.handle_event(ev);
                    }
                },
            },
            other => {
                debug!("{}: Unhandled event {:?}", LOG_TARGET, other);
            }
        }
    }

    async fn handle_command(&mut self, command: Command) {
        match command {
            Command::StartProviding { keys } => {
                for key in keys {
                    self.swarm.behaviour_mut().routing.start_providing(&key);
                }
            }
            Command::SendMessage { receptor, message } => {
                // Check if we are the receptor
                if receptor == self.node_public_key {
                    // It is not needed to send the message
                    self.event_sender
                        .send(NetworkEvent::MessageReceived { message })
                        .await
                        .expect("Event receiver not to be dropped.");
                    return;
                }
                debug!("{}: Sending Message", LOG_TARGET);
                // Check if we have the peerId of the controller in cache
                let peer_id = match libp2p::identity::ed25519::PublicKey::decode(&receptor) {
                    Ok(public_key) => {
                        let public_key = libp2p::core::PublicKey::Ed25519(public_key);
                        PeerId::from_public_key(&public_key)
                    }
                    Err(_error) => {
                        log::error!(
                            "Error al tratar de enviar mensaje, el controllerId no es válido"
                        );
                        return;
                    }
                };

                // If we have it check if we have the address (need to fill in with cache addresses)
                let addresses_of_peer = self.swarm.behaviour_mut().addresses_of_peer(&peer_id);
                if !addresses_of_peer.is_empty() {
                    debug!("MANDANDO MENSAJE, TENGO DIRECCIÓN");
                    // If we have an address, send the message
                    self.swarm
                        .behaviour_mut()
                        .tell
                        .send_message(&peer_id, &message);
                    return;
                }

                // Check if we are not already making the same query in the DHT
                if let None = self.active_get_querys.get(&peer_id) {
                    // Make petition if we dont have it's PeerId to store it
                    self.active_get_querys.insert(peer_id.clone());
                    let query_id = self
                        .swarm
                        .behaviour_mut()
                        .routing
                        .get_closest_peers(peer_id.clone());
                    debug!(
                        "Query get_record {:?} para mandar request a {:?}",
                        query_id, peer_id
                    );
                }
                // Store de message in the pendings for that controller
                match self.pendings.get_mut(&peer_id) {
                    Some(pending_list) => {
                        if pending_list.len() >= 100 {
                            pending_list.pop_front();
                        }
                        pending_list.push_back(message);
                    }
                    None => {
                        let mut pendings = VecDeque::new();
                        pendings.push_back(message);
                        self.pendings.insert(peer_id, pendings);
                    }
                }
            }
            Command::Bootstrap => {
                self.swarm.behaviour_mut().routing.bootstrap();
            }
        }
    }

    /// Send all the pending messages to the specified controller
    fn send_pendings(&mut self, peer_id: &PeerId) {
        let pending_messages = self.pendings.remove(peer_id);
        if let Some(pending_messages) = pending_messages {
            for message in pending_messages.into_iter() {
                debug!("MANDANDO MENSAJE");
                self.swarm
                    .behaviour_mut()
                    .tell
                    .send_message(&peer_id, &message);
            }
        }
    }

    pub fn local_peer_id(&self) -> &PeerId {
        self.swarm.local_peer_id()
    }
}

fn create_ip4_ip6_transport(
    noise_key: noise::AuthenticKeypair<noise::X25519Spec>,
) -> Boxed<(PeerId, StreamMuxerBox)> {
    let transport = TokioTcpConfig::new()
        .nodelay(true)
        .upgrade(upgrade::Version::V1)
        .authenticate(noise::NoiseConfig::xx(noise_key.clone()).into_authenticated())
        .multiplex(mplex::MplexConfig::new())
        .boxed();
    // DNS
    match dns::GenDnsConfig::system(transport) {
        Ok(t) => t.boxed(),
        Err(_) => {
            // TODO: vuelvo a crear el transporte porque no tiene clone, quizás sería interesante poner una variable de entorno que diga si estamos en android y hacer lo segundo directamente en ese caso
            let transport = TokioTcpConfig::new()
                .nodelay(true)
                .upgrade(upgrade::Version::V1)
                .authenticate(noise::NoiseConfig::xx(noise_key.clone()).into_authenticated())
                .multiplex(mplex::MplexConfig::new())
                .boxed();
            // TODO: Lo mismo aquí
            match dns::GenDnsConfig::custom(
                transport,
                dns::ResolverConfig::cloudflare(),
                dns::ResolverOpts::default(),
            ) {
                Ok(t) => t.boxed(),
                Err(_) => TokioTcpConfig::new()
                    .nodelay(true)
                    .upgrade(upgrade::Version::V1)
                    .authenticate(noise::NoiseConfig::xx(noise_key.clone()).into_authenticated())
                    .multiplex(mplex::MplexConfig::new())
                    .boxed(),
            }
        }
    }
}

fn create_transport_by_protocol(
    protocol: ListenProtocols,
    noise_key: noise::AuthenticKeypair<noise::X25519Spec>,
) -> Boxed<(PeerId, StreamMuxerBox)> {
    match protocol {
        ListenProtocols::IP => create_ip4_ip6_transport(noise_key),
        ListenProtocols::Memory => MemoryTransport
            .upgrade(upgrade::Version::V1)
            .authenticate(noise::NoiseConfig::xx(noise_key.clone()).into_authenticated())
            .multiplex(yamux::YamuxConfig::default())
            .boxed(),
    }
}