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
#[cfg(feature = "aproval")]
use crate::approval::manager::{ApprovalAPI, ApprovalManager};
#[cfg(feature = "aproval")]
use crate::approval::{ApprovalMessages, ApprovalResponses};
use crate::authorized_subjecs::manager::{AuthorizedSubjectsAPI, AuthorizedSubjectsManager};
use crate::authorized_subjecs::{AuthorizedSubjectsCommand, AuthorizedSubjectsResponse};
use crate::commons::channel::MpscChannel;
use crate::commons::config::NetworkSettings;
use crate::commons::config::{NodeSettings, TapleSettings};
use crate::commons::crypto::{
    Ed25519KeyPair, KeyGenerator, KeyMaterial, KeyPair, Secp256k1KeyPair,
};
use crate::commons::identifier::derive::KeyDerivator;
use crate::commons::identifier::{Derivable, KeyIdentifier};
use crate::commons::models::notification::Notification;
use crate::commons::self_signature_manager::{SelfSignatureInterface, SelfSignatureManager};
use crate::database::{DatabaseCollection, DatabaseManager, DB};
use crate::distribution::error::DistributionErrorResponses;
use crate::distribution::manager::DistributionManager;
use crate::distribution::DistributionMessagesNew;
#[cfg(feature = "evaluation")]
use crate::evaluator::{EvaluatorManager, EvaluatorMessage, EvaluatorResponse};
use crate::event::manager::{EventAPI, EventManager};
use crate::event::{EventCommand, EventResponse};
use crate::governance::GovernanceAPI;
use crate::governance::{governance::Governance, GovernanceMessage, GovernanceResponse};
use crate::ledger::manager::EventManagerAPI;
use crate::ledger::{manager::LedgerManager, LedgerCommand, LedgerResponse};
use crate::message::{
    MessageContent, MessageReceiver, MessageSender, MessageTaskCommand, MessageTaskManager,
    NetworkEvent,
};
use crate::network::network::{NetworkProcessor, SendMode};
use crate::protocol::protocol_message_manager::{ProtocolManager, TapleMessages};
use crate::signature::Signed;
#[cfg(feature = "validation")]
use crate::validation::manager::ValidationManager;
#[cfg(feature = "validation")]
use crate::validation::{ValidationCommand, ValidationResponse};
use crate::ListenAddr;
use futures::future::BoxFuture;
use futures::FutureExt;
use libp2p::{Multiaddr, PeerId};
use std::marker::PhantomData;
use std::sync::Arc;
use tokio::sync::broadcast::error::{RecvError, TryRecvError};

use crate::api::{APICommands, ApiResponses, NodeAPI, API};
use crate::error::Error;

const BUFFER_SIZE: usize = 1000;

/// Instance a default settings to start a new Taple Node
pub fn get_default_settings() -> TapleSettings {
    TapleSettings {
        network: NetworkSettings {
            listen_addr: vec![ListenAddr::default()],
            known_nodes: Vec::<String>::new(),
            external_address: vec![],
        },
        node: NodeSettings {
            key_derivator: KeyDerivator::Ed25519,
            secret_key: Option::<String>::None,
            digest_derivator:
                crate::commons::identifier::derive::digest::DigestDerivator::Blake3_256,
            replication_factor: 0.25f64,
            timeout: 3000u32,
            passvotation: 0,
            #[cfg(feature = "evaluation")]
            smartcontracts_directory: "./contracts".into(),
        },
    }
}

/// Object that allows receiving [notifications](Notification) of the
/// different events of relevance that a node performs and/or detects.
///
/// These objects can only be obtained through a node that has already been initialized.
/// In case of multiple nodes, the same handler cannot be used to obtain
/// notifications from each of them. Instead, one must be instantiated for each node in the
/// application and they will only be able to receive notifications from that point on,
/// the previous ones being unrecoverable.
pub struct NotificationHandler {
    notification_receiver: tokio::sync::broadcast::Receiver<Notification>,
}

impl NotificationHandler {
    /// It forces the object to wait until the arrival of a new notification.
    /// It is important to note that handlers have an internal queue for storing messages.
    /// This queue starts acting from the moment the object is created, allowing the object
    /// to retrieve notifications from that moment until the current one. In this case,
    /// the method returns instantly with the oldest notification.
    ///
    /// An `Error` will only be obtained if it is not possible to receive more notifications
    /// due to a node stop and if there are no messages queued. In such a situation,
    /// the handler becomes useless and its release from memory is recommended.
    pub fn receive<'a>(&'a mut self) -> BoxFuture<'a, Result<Notification, Error>> {
        async move {
            loop {
                match self.notification_receiver.recv().await {
                    Ok(value) => break Ok(value),
                    Err(RecvError::Lagged(_)) => continue,
                    Err(RecvError::Closed) => break Err(Error::CantReceiveNotification),
                }
            }
        }
        .boxed()
    }

    /// The handler tries to get a notification. If there is none, it returns instead of waiting.
    /// Because of this, this method can be used to determine if the notification queue is empty,
    /// since it will report such a possibility with an error.
    ///
    /// # Possible results
    /// • A notification will be obtained only if it exists in the object's queue. <br />
    /// • [Error::CantReceiveNotification] will be obtained if it is not possible to receive more notifications. <br />
    /// • [Error::NoNewNotification] will be obtained if there is no message queued and it is still possible to
    /// continue receiving messages.
    pub fn try_rec(&mut self) -> Result<Notification, Error> {
        loop {
            match self.notification_receiver.try_recv() {
                Ok(value) => break Ok(value),
                Err(TryRecvError::Lagged(_)) => continue,
                Err(TryRecvError::Closed) => break Err(Error::CantReceiveNotification),
                Err(TryRecvError::Empty) => break Err(Error::NoNewNotification),
            }
        }
    }
}

/// Structure that allows a signal to be emitted to stop the TAPLE node.
/// It can also be used to detect internal shutdown signals, which occur when an internal error occurs.
pub struct TapleShutdownManager {
    shutdown_sender: tokio::sync::broadcast::Sender<()>,
    shutdown_receiver: tokio::sync::broadcast::Receiver<()>,
}

impl TapleShutdownManager {
    pub(crate) fn new(sender: tokio::sync::broadcast::Sender<()>) -> Self {
        Self {
            shutdown_receiver: sender.subscribe(),
            shutdown_sender: sender,
        }
    }
    /// Allows to obtain the underlying channel to receive messages
    pub fn get_raw_receiver(&self) -> tokio::sync::broadcast::Receiver<()> {
        self.shutdown_sender.subscribe()
    }

    /// Allows to obtain the underlying channel to send messages
    pub fn get_raw_sender(&self) -> tokio::sync::broadcast::Sender<()> {
        self.shutdown_sender.clone()
    }

    /// Wait until a shutdown signal is received from the node.
    pub async fn wait_for_shutdown(mut self) {
        loop {
            match self.shutdown_receiver.recv().await {
                Err(RecvError::Lagged(_)) => continue,
                _ => break,
            }
        }
    }

    /// It issues a shutdown signal and waits until the node has processed it correctly.
    pub async fn shutdown(mut self) {
        self.shutdown_sender.send(()).unwrap();
        drop(self.shutdown_sender);
        loop {
            match self.shutdown_receiver.recv().await {
                Err(RecvError::Closed) => break,
                _ => continue,
            }
        }
    }
}

/// Structure representing a node of a TAPLE network.
///
/// A node must be instantiated using the [`Taple::new`] method, which requires a set
/// of [configuration](Settings) parameters in order to be properly initialized.
///
#[derive(Debug)]
pub struct Taple<M: DatabaseManager<C>, C: DatabaseCollection> {
    api: NodeAPI,
    peer_id: Option<PeerId>,
    controller_id: Option<String>,
    public_key: Option<Vec<u8>>,
    api_input: Option<MpscChannel<APICommands, ApiResponses>>,
    notification_sender: tokio::sync::broadcast::Sender<Notification>,
    settings: TapleSettings,
    database: Option<M>,
    shutdown_sender: Option<tokio::sync::broadcast::Sender<()>>,
    _shutdown_receiver: tokio::sync::broadcast::Receiver<()>,
    _c: PhantomData<C>,
}

impl<M: DatabaseManager<C> + 'static, C: DatabaseCollection + 'static> Taple<M, C> {
    /// Returns the [PeerId] of the node is available.
    /// This ID is the identifier of the node at the network level.
    /// **None** can only be get if the node has not been started yet.
    pub fn peer_id(&self) -> Option<PeerId> {
        self.peer_id.clone()
    }

    /// Returns the public key (bytes format) of the node is available.
    /// **None** can only be get if the node has not been started yet.
    pub fn public_key(&self) -> Option<Vec<u8>> {
        self.public_key.clone()
    }

    /// Returns the controller ID of the node is available.
    /// This ID is the identifier of the node at the protocol level.
    /// **None** can only be get if the node has not been started yet.
    pub fn controller_id(&self) -> Option<String> {
        self.controller_id.clone()
    }

    /// This methods allows to get the [API](NodeAPI) of the node. The API can be get
    /// as many time as desired. The API is the only method to interact with a node at the user level.
    pub fn get_api(&self) -> NodeAPI {
        self.api.clone()
    }

    /// This method allows to get an instance of [NotificationHandler].
    /// This component is used by the node to report any important events
    /// that have occurred, for example the creation of new **subjects**.
    /// The component behaves similar to a channel receiver; users only have to call
    /// the [NotificationHandler::receive] method to start receiving notifications.
    pub fn get_notification_handler(&self) -> NotificationHandler {
        NotificationHandler {
            notification_receiver: self.notification_sender.subscribe(),
        }
    }

    /// This method allows to get the receiver of the shutdown channel used by the node.
    /// This can be used by the user/client to detect when the node has emmited the signal to .
    pub fn get_shutdown_manager(&self) -> TapleShutdownManager {
        TapleShutdownManager::new(self.shutdown_sender.as_ref().unwrap().clone())
    }

    /// This method allows the creation of cryptographic material through a
    /// given public key.
    fn generate_mc(&mut self, stored_public_key: Option<String>) -> Result<KeyPair, Error> {
        let kp = Self::create_key_pair(
            &self.settings.node.key_derivator,
            None,
            self.settings.node.secret_key.clone(),
        )?;
        let public_key = kp.public_key_bytes();
        let key_identifier = KeyIdentifier::new(kp.get_key_derivator(), &public_key).to_str();
        if let Some(key) = stored_public_key {
            if key_identifier != key {
                log::error!("Invalid MC specified. There is a previous defined MC in the system");
                return Err(Error::InvalidKeyPairSpecified(key_identifier));
            }
        }
        self.controller_id = Some(key_identifier);
        self.public_key = Some(public_key);
        Ok(kp)
    }

    /// Main and unique method to create an instance of a TAPLE node.
    pub fn new(settings: TapleSettings, database: M) -> Self {
        let (api_input, api_sender) = MpscChannel::new(BUFFER_SIZE);
        let (sender, _) = tokio::sync::broadcast::channel(BUFFER_SIZE);
        // Shutdown channel
        let (bsx, brx) = tokio::sync::broadcast::channel::<()>(10);
        let api = NodeAPI { sender: api_sender };
        Self {
            api,
            peer_id: None,
            public_key: None,
            controller_id: None,
            api_input: Some(api_input),
            notification_sender: sender,
            settings,
            database: Some(database),
            shutdown_sender: Some(bsx),
            _shutdown_receiver: brx,
            _c: PhantomData::default(),
        }
    }

    /// This method initializes a TAPLE node, generating each of its internal components
    /// and allowing subsequent interaction with the node. Each of the aforementioned
    /// components is executed in its own Tokyo task, allowing the method to return the
    /// control flow once its execution is finished.
    /// # Possible results
    /// If the process is successful, the method will return `Ok(())`.
    /// An error will be returned only if it has not been possible to generate the necessary data
    /// for the initialization of the components, mainly due to problems in the initial [configuration](Settings).
    /// # Panics
    /// This method panics if it has not been possible to generate the network layer.
    pub async fn start(&mut self) -> Result<(), Error> {
        // Create channels
        let shutdown_sender = self.shutdown_sender.take().unwrap();
        // Channels for network
        let (sender_network, receiver_network): (
            tokio::sync::mpsc::Sender<NetworkEvent>,
            tokio::sync::mpsc::Receiver<NetworkEvent>,
        ) = tokio::sync::mpsc::channel(BUFFER_SIZE);
        let (event_receiver, event_sender) =
            MpscChannel::<EventCommand, EventResponse>::new(BUFFER_SIZE);
        // Receiver and sender of commands
        let (ledger_receiver, ledger_sender) =
            MpscChannel::<LedgerCommand, LedgerResponse>::new(BUFFER_SIZE);
        // Receiver and sender of commands AS
        let (as_receiver, as_sender) =
            MpscChannel::<AuthorizedSubjectsCommand, AuthorizedSubjectsResponse>::new(BUFFER_SIZE);
        // Receiver and sender of governance messages
        let (governance_receiver, governance_sender) =
            MpscChannel::<GovernanceMessage, GovernanceResponse>::new(BUFFER_SIZE);
        // Governance notification channel
        let (governance_update_sx, governance_update_rx) =
            tokio::sync::broadcast::channel(BUFFER_SIZE);
        // Receiver and sender of ledger message
        // Receiver and sender of taskManager requests
        let (task_receiver, task_sender) =
            MpscChannel::<MessageTaskCommand<TapleMessages>, ()>::new(BUFFER_SIZE);
        // Receiver and sender of protocol messages
        let (protocol_receiver, protocol_sender) =
            MpscChannel::<Signed<MessageContent<TapleMessages>>, ()>::new(BUFFER_SIZE);
        // Receiver and sender of distribution messages
        let (distribution_receiver, distribution_sender) = MpscChannel::<
            DistributionMessagesNew,
            Result<(), DistributionErrorResponses>,
        >::new(BUFFER_SIZE);
        // Receiver and sender of approval messages
        #[cfg(feature = "aproval")]
        let (approval_receiver, approval_sender) =
            MpscChannel::<ApprovalMessages, ApprovalResponses>::new(BUFFER_SIZE);
        // Receiver and sender of evaluation messages
        #[cfg(feature = "evaluation")]
        let (evaluation_receiver, evaluation_sender) =
            MpscChannel::<EvaluatorMessage, EvaluatorResponse>::new(BUFFER_SIZE);
        // Receiver and sender of validation messages
        #[cfg(feature = "validation")]
        let (validation_receiver, validation_sender) =
            MpscChannel::<ValidationCommand, ValidationResponse>::new(BUFFER_SIZE);
        // Creation Watch Channel
        let (wath_sender, _watch_receiver): (
            tokio::sync::watch::Sender<TapleSettings>,
            tokio::sync::watch::Receiver<TapleSettings>,
        ) = tokio::sync::watch::channel(self.settings.clone());
        // Creation BBDD
        let db = self.database.take().unwrap();
        let db = Arc::new(db);
        let db_access = DB::new(db.clone());
        // Creation of cryptographic material
        let stored_public_key = db_access.get_controller_id().ok();
        let kp = self.generate_mc(stored_public_key)?;
        // Store controller_id in database
        db_access
            .set_controller_id(self.controller_id().unwrap())
            .map_err(|e| Error::DatabaseError(e.to_string()))?;
        let public_key = kp.public_key_bytes();
        let key_identifier = KeyIdentifier::new(kp.get_key_derivator(), &public_key);
        // Creation Network
        let network_manager = NetworkProcessor::new(
            self.settings.network.listen_addr.clone(),
            network_access_points(&self.settings.network.known_nodes)?, // TODO: Provide Bootraps nodes per configuration
            sender_network,
            kp.clone(),
            shutdown_sender.subscribe(),
            external_addresses(&self.settings.network.external_address)?,
        )
        .await
        .expect("Error en creación de la capa de red");
        self.peer_id = Some(network_manager.local_peer_id().to_owned());
        // Creation Signature Manager
        let signature_manager = SelfSignatureManager::new(kp.clone(), &self.settings);
        // Creation NetworkReceiver
        let network_receiver = MessageReceiver::new(
            receiver_network,
            protocol_sender,
            shutdown_sender.subscribe(),
            signature_manager.get_own_identifier(),
        );
        // Creation NetworkSender
        let network_sender = MessageSender::new(
            network_manager.client(),
            key_identifier.clone(),
            signature_manager.clone(),
        );
        // Creation TaskManager
        let mut task_manager = MessageTaskManager::new(
            network_sender.clone(),
            task_receiver,
            shutdown_sender.clone(),
            shutdown_sender.subscribe(),
        );
        // Creation ProtocolManager
        let protocol_manager = ProtocolManager::new(
            protocol_receiver,
            distribution_sender.clone(),
            #[cfg(feature = "evaluation")]
            evaluation_sender.clone(),
            #[cfg(feature = "validation")]
            validation_sender.clone(),
            event_sender.clone(),
            #[cfg(feature = "aproval")]
            approval_sender.clone(),
            ledger_sender.clone(),
            shutdown_sender.clone(),
        );
        // Creation Governance
        let mut governance_manager = Governance::<M, C>::new(
            governance_receiver,
            shutdown_sender.clone(),
            shutdown_sender.subscribe(),
            DB::new(db.clone()),
            governance_update_sx.clone(),
        );
        // Creation EventManager
        let event_manager = EventManager::new(
            event_receiver,
            governance_update_rx,
            GovernanceAPI::new(governance_sender.clone()),
            DB::new(db.clone()),
            shutdown_sender.clone(),
            shutdown_sender.subscribe(),
            task_sender.clone(),
            self.notification_sender.clone(),
            ledger_sender.clone(),
            signature_manager.get_own_identifier(),
            signature_manager.clone(),
        );
        // Creation LedgerManager
        let ledger_manager = LedgerManager::new(
            ledger_receiver,
            shutdown_sender.clone(),
            shutdown_sender.subscribe(),
            self.notification_sender.clone(),
            GovernanceAPI::new(governance_sender.clone()),
            DB::new(db.clone()),
            task_sender.clone(),
            distribution_sender,
            key_identifier.clone(),
        );
        // Creation AuthorizedSubjectsManager
        let as_manager = AuthorizedSubjectsManager::new(
            as_receiver,
            DB::new(db.clone()),
            task_sender.clone(),
            key_identifier.clone(),
            shutdown_sender.clone(),
            shutdown_sender.subscribe(),
        );
        // Creation API module
        let api = API::new(
            self.api_input.take().unwrap(),
            EventAPI::new(event_sender),
            #[cfg(feature = "aproval")]
            ApprovalAPI::new(approval_sender),
            AuthorizedSubjectsAPI::new(as_sender),
            EventManagerAPI::new(ledger_sender),
            wath_sender,
            shutdown_sender.clone(),
            shutdown_sender.subscribe(),
            DB::new(db.clone()),
        );
        #[cfg(feature = "evaluation")]
        // Creation EvaluatorManager
        let evaluator_manager = EvaluatorManager::new(
            evaluation_receiver,
            db.clone(),
            signature_manager.clone(),
            governance_update_sx.subscribe(),
            shutdown_sender.clone(),
            shutdown_sender.subscribe(),
            GovernanceAPI::new(governance_sender.clone()),
            self.settings.node.smartcontracts_directory.clone(),
            task_sender.clone(),
        );
        // Creation ApprovalManager
        #[cfg(feature = "aproval")]
        let approval_manager = ApprovalManager::new(
            GovernanceAPI::new(governance_sender.clone()),
            approval_receiver,
            shutdown_sender.clone(),
            shutdown_sender.subscribe(),
            task_sender.clone(),
            governance_update_sx.subscribe(),
            signature_manager.clone(),
            self.notification_sender.clone(),
            self.settings.clone(),
            DB::new(db.clone()),
        );
        // Creation DistributionManager
        let distribution_manager = DistributionManager::new(
            distribution_receiver,
            governance_update_sx.subscribe(),
            shutdown_sender.clone(),
            shutdown_sender.subscribe(),
            task_sender.clone(),
            GovernanceAPI::new(governance_sender.clone()),
            signature_manager.clone(),
            self.settings.clone(),
            DB::new(db.clone()),
        );
        #[cfg(feature = "validation")]
        let validation_manager = ValidationManager::new(
            validation_receiver,
            GovernanceAPI::new(governance_sender),
            DB::new(db.clone()),
            signature_manager,
            shutdown_sender.clone(),
            shutdown_sender.subscribe(),
            task_sender,
        );
        // Module initialization
        tokio::spawn(async move {
            governance_manager.start().await;
        });
        tokio::spawn(async move {
            ledger_manager.start().await;
        });
        tokio::spawn(async move {
            event_manager.start().await;
        });
        tokio::spawn(async move {
            task_manager.start().await;
        });
        tokio::spawn(async move {
            protocol_manager.start().await;
        });
        tokio::spawn(async move {
            network_receiver.run().await;
        });
        #[cfg(feature = "evaluation")]
        tokio::spawn(async move {
            evaluator_manager.start().await;
        });
        #[cfg(feature = "validation")]
        tokio::spawn(async move {
            validation_manager.start().await;
        });
        tokio::spawn(async move {
            distribution_manager.start().await;
        });
        #[cfg(feature = "aproval")]
        tokio::spawn(async move {
            approval_manager.start().await;
        });
        tokio::spawn(async move {
            as_manager.start().await;
        });
        tokio::spawn(network_manager.run());
        // API Initialization
        tokio::spawn(async move {
            api.start().await;
        });
        Ok(())
    }

    fn create_key_pair(
        derivator: &KeyDerivator,
        seed: Option<String>,
        current_key: Option<String>,
    ) -> Result<KeyPair, Error> {
        let mut counter: u32 = 0;
        if seed.is_some() {
            counter += 1
        };
        if current_key.is_some() {
            counter += 2
        };
        if counter == 2 {
            let str_key = current_key.unwrap();
            match derivator {
                KeyDerivator::Ed25519 => Ok(KeyPair::Ed25519(Ed25519KeyPair::from_secret_key(
                    &hex::decode(str_key).map_err(|_| Error::InvalidHexString)?,
                ))),
                KeyDerivator::Secp256k1 => {
                    Ok(KeyPair::Secp256k1(Secp256k1KeyPair::from_secret_key(
                        &hex::decode(str_key).map_err(|_| Error::InvalidHexString)?,
                    )))
                }
            }
        } else if counter == 1 {
            match derivator {
                KeyDerivator::Ed25519 => Ok(KeyPair::Ed25519(
                    crate::commons::crypto::Ed25519KeyPair::from_seed(seed.unwrap().as_bytes()),
                )),
                KeyDerivator::Secp256k1 => Ok(KeyPair::Secp256k1(
                    crate::commons::crypto::Secp256k1KeyPair::from_seed(seed.unwrap().as_bytes()),
                )),
            }
        } else if counter == 3 {
            Err(Error::PkConflict)
        } else {
            Err(Error::NoMCAvailable)
        }
    }
}

fn network_access_points(points: &[String]) -> Result<Vec<(PeerId, Multiaddr)>, Error> {
    let mut access_points: Vec<(PeerId, Multiaddr)> = Vec::new();
    for point in points {
        let data: Vec<&str> = point.split("/p2p/").collect();
        if data.len() != 2 {
            return Err(Error::AcessPointError(point.to_string()));
        }
        if let Some(value) = multiaddr(point) {
            if let Ok(id) = data[1].parse::<PeerId>() {
                access_points.push((id, value));
            } else {
                return Err(Error::AcessPointError(format!(
                    "Invalid PeerId conversion: {}",
                    point
                )));
            }
        } else {
            return Err(Error::AcessPointError(format!(
                "Invalid MultiAddress conversion: {}",
                point
            )));
        }
    }
    Ok(access_points)
}

fn external_addresses(addresses: &[String]) -> Result<Vec<Multiaddr>, Error> {
    let mut external_addresses: Vec<Multiaddr> = Vec::new();
    for address in addresses {
        if let Some(value) = multiaddr(address) {
            external_addresses.push(value);
        } else {
            return Err(Error::AcessPointError(format!(
                "Invalid MultiAddress conversion in External Address: {}",
                address
            )));
        }
    }
    Ok(external_addresses)
}

fn multiaddr(addr: &str) -> Option<Multiaddr> {
    match addr.parse::<Multiaddr>() {
        Ok(a) => Some(a),
        Err(_) => None,
    }
}