1pub use crate::{
25 discovery::DEFAULT_KADEMLIA_REPLICATION_FACTOR,
26 peer_store::PeerStoreProvider,
27 protocol::{notification_service, NotificationsSink, ProtocolHandlePair},
28 request_responses::{
29 IncomingRequest, OutgoingResponse, ProtocolConfig as RequestResponseConfig,
30 },
31 service::{
32 metrics::NotificationMetrics,
33 traits::{NotificationConfig, NotificationService, PeerStore},
34 },
35 types::ProtocolName,
36};
37
38pub use sc_network_types::{build_multiaddr, ed25519};
39use sc_network_types::{
40 multiaddr::{self, Multiaddr},
41 PeerId,
42};
43
44use crate::{
45 service::{ensure_addresses_consistent_with_transport, traits::NetworkBackend},
46 webrtc,
47};
48use codec::Encode;
49use prometheus_endpoint::Registry;
50use zeroize::Zeroize;
51
52pub use sc_network_common::{
53 role::{Role, Roles},
54 sync::SyncMode,
55 ExHashT,
56};
57
58use sp_runtime::traits::Block as BlockT;
59
60use std::{
61 error::Error,
62 fmt, fs,
63 future::Future,
64 io::{self, Write},
65 iter,
66 net::Ipv4Addr,
67 num::NonZeroUsize,
68 path::{Path, PathBuf},
69 pin::Pin,
70 str::{self, FromStr},
71 sync::Arc,
72 time::Duration,
73};
74
75pub const DEFAULT_IDLE_CONNECTION_TIMEOUT: Duration = Duration::from_secs(10);
79
80pub const KADEMLIA_MAX_PROVIDER_KEYS: usize = 10000;
84
85pub const KADEMLIA_PROVIDER_RECORD_TTL: Duration = Duration::from_secs(10 * 3600);
89
90pub const KADEMLIA_PROVIDER_REPUBLISH_INTERVAL: Duration = Duration::from_secs(12600);
94
95#[derive(Clone, PartialEq, Eq, Hash)]
99pub struct ProtocolId(smallvec::SmallVec<[u8; 6]>);
100
101impl<'a> From<&'a str> for ProtocolId {
102 fn from(bytes: &'a str) -> ProtocolId {
103 Self(bytes.as_bytes().into())
104 }
105}
106
107impl AsRef<str> for ProtocolId {
108 fn as_ref(&self) -> &str {
109 str::from_utf8(&self.0[..])
110 .expect("the only way to build a ProtocolId is through a UTF-8 String; qed")
111 }
112}
113
114impl fmt::Debug for ProtocolId {
115 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
116 fmt::Debug::fmt(self.as_ref(), f)
117 }
118}
119
120pub fn parse_str_addr(addr_str: &str) -> Result<(PeerId, Multiaddr), ParseErr> {
135 let addr: Multiaddr = addr_str.parse()?;
136 parse_addr(addr)
137}
138
139pub fn parse_addr(mut addr: Multiaddr) -> Result<(PeerId, Multiaddr), ParseErr> {
141 let multihash = match addr.pop() {
142 Some(multiaddr::Protocol::P2p(multihash)) => multihash,
143 _ => return Err(ParseErr::PeerIdMissing),
144 };
145 let peer_id = PeerId::from_multihash(multihash).map_err(|_| ParseErr::InvalidPeerId)?;
146
147 Ok((peer_id, addr))
148}
149
150#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
165#[serde(try_from = "String", into = "String")]
166pub struct MultiaddrWithPeerId {
167 pub multiaddr: Multiaddr,
169 pub peer_id: PeerId,
171}
172
173impl MultiaddrWithPeerId {
174 pub fn concat(&self) -> Multiaddr {
176 let mut addr = self.multiaddr.clone();
177 if matches!(addr.iter().last(), Some(multiaddr::Protocol::P2p(_))) {
179 addr.pop();
180 }
181 addr.with(multiaddr::Protocol::P2p(From::from(self.peer_id)))
182 }
183}
184
185impl fmt::Display for MultiaddrWithPeerId {
186 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
187 fmt::Display::fmt(&self.concat(), f)
188 }
189}
190
191impl FromStr for MultiaddrWithPeerId {
192 type Err = ParseErr;
193
194 fn from_str(s: &str) -> Result<Self, Self::Err> {
195 let (peer_id, multiaddr) = parse_str_addr(s)?;
196 Ok(Self { peer_id, multiaddr })
197 }
198}
199
200impl From<MultiaddrWithPeerId> for String {
201 fn from(ma: MultiaddrWithPeerId) -> String {
202 format!("{}", ma)
203 }
204}
205
206impl TryFrom<String> for MultiaddrWithPeerId {
207 type Error = ParseErr;
208 fn try_from(string: String) -> Result<Self, Self::Error> {
209 string.parse()
210 }
211}
212
213#[derive(Debug)]
215pub enum ParseErr {
216 MultiaddrParse(multiaddr::ParseError),
218 InvalidPeerId,
220 PeerIdMissing,
222}
223
224impl fmt::Display for ParseErr {
225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226 match self {
227 Self::MultiaddrParse(err) => write!(f, "{}", err),
228 Self::InvalidPeerId => write!(f, "Peer id at the end of the address is invalid"),
229 Self::PeerIdMissing => write!(f, "Peer id is missing from the address"),
230 }
231 }
232}
233
234impl std::error::Error for ParseErr {
235 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
236 match self {
237 Self::MultiaddrParse(err) => Some(err),
238 Self::InvalidPeerId => None,
239 Self::PeerIdMissing => None,
240 }
241 }
242}
243
244impl From<multiaddr::ParseError> for ParseErr {
245 fn from(err: multiaddr::ParseError) -> ParseErr {
246 Self::MultiaddrParse(err)
247 }
248}
249
250#[derive(Debug, Clone)]
252pub struct NotificationHandshake(Vec<u8>);
253
254impl NotificationHandshake {
255 pub fn new<H: Encode>(handshake: H) -> Self {
257 Self(handshake.encode())
258 }
259
260 pub fn from_bytes(bytes: Vec<u8>) -> Self {
262 Self(bytes)
263 }
264}
265
266impl std::ops::Deref for NotificationHandshake {
267 type Target = Vec<u8>;
268
269 fn deref(&self) -> &Self::Target {
270 &self.0
271 }
272}
273
274#[derive(Clone, Debug)]
276pub enum TransportConfig {
277 Normal {
279 enable_mdns: bool,
282
283 allow_private_ip: bool,
287 },
288
289 MemoryOnly,
292}
293
294#[derive(Clone, Debug, PartialEq, Eq)]
296pub enum NonReservedPeerMode {
297 Accept,
299 Deny,
301}
302
303impl NonReservedPeerMode {
304 pub fn parse(s: &str) -> Option<Self> {
306 match s {
307 "accept" => Some(Self::Accept),
308 "deny" => Some(Self::Deny),
309 _ => None,
310 }
311 }
312
313 pub fn is_reserved_only(&self) -> bool {
315 matches!(self, NonReservedPeerMode::Deny)
316 }
317}
318
319#[derive(Clone, Debug)]
323pub enum NodeKeyConfig {
324 Ed25519(Secret<ed25519::SecretKey>),
326}
327
328impl Default for NodeKeyConfig {
329 fn default() -> NodeKeyConfig {
330 Self::Ed25519(Secret::New)
331 }
332}
333
334pub type Ed25519Secret = Secret<ed25519::SecretKey>;
336
337#[derive(Clone)]
339pub enum Secret<K> {
340 Input(K),
342 File(PathBuf),
348 New,
350}
351
352impl<K> fmt::Debug for Secret<K> {
353 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
354 match self {
355 Self::Input(_) => f.debug_tuple("Secret::Input").finish(),
356 Self::File(path) => f.debug_tuple("Secret::File").field(path).finish(),
357 Self::New => f.debug_tuple("Secret::New").finish(),
358 }
359 }
360}
361
362impl NodeKeyConfig {
363 pub fn into_keypair(self) -> io::Result<ed25519::Keypair> {
374 use NodeKeyConfig::*;
375 match self {
376 Ed25519(Secret::New) => Ok(ed25519::Keypair::generate()),
377
378 Ed25519(Secret::Input(k)) => Ok(ed25519::Keypair::from(k).into()),
379
380 Ed25519(Secret::File(f)) => get_secret(
381 f,
382 |mut b| match String::from_utf8(b.to_vec()).ok().and_then(|s| {
383 if s.len() == 64 {
384 array_bytes::hex2bytes(&s).ok()
385 } else {
386 None
387 }
388 }) {
389 Some(s) => ed25519::SecretKey::try_from_bytes(s),
390 _ => ed25519::SecretKey::try_from_bytes(&mut b),
391 },
392 ed25519::SecretKey::generate,
393 |b| b.as_ref().to_vec(),
394 )
395 .map(ed25519::Keypair::from),
396 }
397 }
398}
399
400fn get_secret<P, F, G, E, W, K>(file: P, parse: F, generate: G, serialize: W) -> io::Result<K>
404where
405 P: AsRef<Path>,
406 F: for<'r> FnOnce(&'r mut [u8]) -> Result<K, E>,
407 G: FnOnce() -> K,
408 E: Error + Send + Sync + 'static,
409 W: Fn(&K) -> Vec<u8>,
410{
411 std::fs::read(&file)
412 .and_then(|mut sk_bytes| {
413 parse(&mut sk_bytes).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
414 })
415 .or_else(|e| {
416 if e.kind() == io::ErrorKind::NotFound {
417 file.as_ref().parent().map_or(Ok(()), fs::create_dir_all)?;
418 let sk = generate();
419 let mut sk_vec = serialize(&sk);
420 write_secret_file(file, &sk_vec)?;
421 sk_vec.zeroize();
422 Ok(sk)
423 } else {
424 Err(e)
425 }
426 })
427}
428
429pub(super) fn write_secret_file<P>(path: P, sk_bytes: &[u8]) -> io::Result<()>
431where
432 P: AsRef<Path>,
433{
434 let mut file = open_secret_file(&path)?;
435 file.write_all(sk_bytes)
436}
437
438#[cfg(unix)]
440fn open_secret_file<P>(path: P) -> io::Result<fs::File>
441where
442 P: AsRef<Path>,
443{
444 use std::os::unix::fs::OpenOptionsExt;
445 fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(path)
446}
447
448#[cfg(not(unix))]
450fn open_secret_file<P>(path: P) -> Result<fs::File, io::Error>
451where
452 P: AsRef<Path>,
453{
454 fs::OpenOptions::new().write(true).create_new(true).open(path)
455}
456
457#[derive(Clone, Debug)]
459pub struct SetConfig {
460 pub in_peers: u32,
462
463 pub out_peers: u32,
465
466 pub reserved_nodes: Vec<MultiaddrWithPeerId>,
468
469 pub non_reserved_mode: NonReservedPeerMode,
472}
473
474impl Default for SetConfig {
475 fn default() -> Self {
476 Self {
477 in_peers: 25,
478 out_peers: 75,
479 reserved_nodes: Vec::new(),
480 non_reserved_mode: NonReservedPeerMode::Accept,
481 }
482 }
483}
484
485#[derive(Debug)]
490pub struct NonDefaultSetConfig {
491 protocol_name: ProtocolName,
497
498 fallback_names: Vec<ProtocolName>,
505
506 handshake: Option<NotificationHandshake>,
512
513 max_notification_size: u64,
515
516 set_config: SetConfig,
518
519 protocol_handle_pair: ProtocolHandlePair,
527}
528
529impl NonDefaultSetConfig {
530 pub fn new(
533 protocol_name: ProtocolName,
534 fallback_names: Vec<ProtocolName>,
535 max_notification_size: u64,
536 handshake: Option<NotificationHandshake>,
537 set_config: SetConfig,
538 ) -> (Self, Box<dyn NotificationService>) {
539 let (protocol_handle_pair, notification_service) =
540 notification_service(protocol_name.clone());
541 (
542 Self {
543 protocol_name,
544 max_notification_size,
545 fallback_names,
546 handshake,
547 set_config,
548 protocol_handle_pair,
549 },
550 notification_service,
551 )
552 }
553
554 pub fn protocol_name(&self) -> &ProtocolName {
556 &self.protocol_name
557 }
558
559 pub fn fallback_names(&self) -> impl Iterator<Item = &ProtocolName> {
561 self.fallback_names.iter()
562 }
563
564 pub fn handshake(&self) -> &Option<NotificationHandshake> {
566 &self.handshake
567 }
568
569 pub fn max_notification_size(&self) -> u64 {
571 self.max_notification_size
572 }
573
574 pub fn set_config(&self) -> &SetConfig {
576 &self.set_config
577 }
578
579 pub fn take_protocol_handle(self) -> ProtocolHandlePair {
581 self.protocol_handle_pair
582 }
583
584 pub fn allow_non_reserved(&mut self, in_peers: u32, out_peers: u32) {
586 self.set_config.in_peers = in_peers;
587 self.set_config.out_peers = out_peers;
588 self.set_config.non_reserved_mode = NonReservedPeerMode::Accept;
589 }
590
591 pub fn add_reserved(&mut self, peer: MultiaddrWithPeerId) {
593 self.set_config.reserved_nodes.push(peer);
594 }
595
596 pub fn add_fallback_names(&mut self, fallback_names: Vec<ProtocolName>) {
600 self.fallback_names.extend(fallback_names);
601 }
602}
603
604impl NotificationConfig for NonDefaultSetConfig {
605 fn set_config(&self) -> &SetConfig {
606 &self.set_config
607 }
608
609 fn protocol_name(&self) -> &ProtocolName {
611 &self.protocol_name
612 }
613}
614
615#[derive(Clone, Debug)]
617pub struct NetworkConfiguration {
618 pub net_config_path: Option<PathBuf>,
620
621 pub listen_addresses: Vec<Multiaddr>,
623
624 pub public_addresses: Vec<Multiaddr>,
626
627 pub boot_nodes: Vec<MultiaddrWithPeerId>,
629
630 pub node_key: NodeKeyConfig,
632
633 pub default_peers_set: SetConfig,
635
636 pub default_peers_set_num_full: u32,
641
642 pub client_version: String,
644
645 pub node_name: String,
647
648 pub transport: TransportConfig,
650
651 pub idle_connection_timeout: Duration,
655
656 pub max_parallel_downloads: u32,
658
659 pub max_blocks_per_request: u32,
661
662 pub min_peers_to_start_warp_sync: Option<usize>,
664
665 pub sync_mode: SyncMode,
667
668 pub enable_dht_random_walk: bool,
672
673 pub allow_non_globals_in_dht: bool,
675
676 pub kademlia_disjoint_query_paths: bool,
679
680 pub kademlia_replication_factor: NonZeroUsize,
685
686 pub ipfs_server: bool,
688
689 pub ipfs_bootnodes: Vec<MultiaddrWithPeerId>,
695
696 pub network_backend: NetworkBackendType,
698}
699
700impl NetworkConfiguration {
701 pub fn new<SN: Into<String>, SV: Into<String>>(
703 node_name: SN,
704 client_version: SV,
705 node_key: NodeKeyConfig,
706 net_config_path: Option<PathBuf>,
707 ) -> Self {
708 let default_peers_set = SetConfig::default();
709 Self {
710 net_config_path,
711 listen_addresses: Vec::new(),
712 public_addresses: Vec::new(),
713 boot_nodes: Vec::new(),
714 node_key,
715 default_peers_set_num_full: default_peers_set.in_peers + default_peers_set.out_peers,
716 default_peers_set,
717 client_version: client_version.into(),
718 node_name: node_name.into(),
719 transport: TransportConfig::Normal { enable_mdns: false, allow_private_ip: true },
720 idle_connection_timeout: DEFAULT_IDLE_CONNECTION_TIMEOUT,
721 max_parallel_downloads: 5,
722 max_blocks_per_request: 64,
723 min_peers_to_start_warp_sync: None,
724 sync_mode: SyncMode::Full,
725 enable_dht_random_walk: true,
726 allow_non_globals_in_dht: false,
727 kademlia_disjoint_query_paths: false,
728 kademlia_replication_factor: NonZeroUsize::new(DEFAULT_KADEMLIA_REPLICATION_FACTOR)
729 .expect("value is a constant; constant is non-zero; qed."),
730 ipfs_server: false,
731 ipfs_bootnodes: Vec::new(),
732 network_backend: NetworkBackendType::Litep2p,
733 }
734 }
735
736 pub fn new_local() -> NetworkConfiguration {
739 let mut config =
740 NetworkConfiguration::new("test-node", "test-client", Default::default(), None);
741
742 config.listen_addresses =
743 vec![iter::once(multiaddr::Protocol::Ip4(Ipv4Addr::new(127, 0, 0, 1)))
744 .chain(iter::once(multiaddr::Protocol::Tcp(0)))
745 .collect()];
746
747 config.allow_non_globals_in_dht = true;
748 config
749 }
750
751 pub fn new_memory() -> NetworkConfiguration {
754 let mut config =
755 NetworkConfiguration::new("test-node", "test-client", Default::default(), None);
756
757 config.listen_addresses =
758 vec![iter::once(multiaddr::Protocol::Ip4(Ipv4Addr::new(127, 0, 0, 1)))
759 .chain(iter::once(multiaddr::Protocol::Tcp(0)))
760 .collect()];
761
762 config.allow_non_globals_in_dht = true;
763 config
764 }
765
766 pub fn validate_and_complete_webrtc_addresses(&mut self) -> Result<(), crate::error::Error> {
773 let has_webrtc_addr = |addrs: &[Multiaddr]| addrs.iter().any(webrtc::is_webrtc_address);
774
775 let listen_webrtc = has_webrtc_addr(&self.listen_addresses);
776 let public_webrtc = has_webrtc_addr(&self.public_addresses);
777
778 if matches!(self.network_backend, NetworkBackendType::Libp2p) {
780 if listen_webrtc || public_webrtc {
781 return Err(crate::error::Error::WebRtcNotSupportedByBackend);
782 }
783 return Ok(());
784 }
785
786 match (listen_webrtc, public_webrtc) {
787 (false, false) => Ok(()),
789 (false, true) => Err(crate::error::Error::WebRtcTransportNotConfigured),
793 (true, _) => {
796 let keypair = self.node_key.clone().into_keypair()?;
797 self.node_key = NodeKeyConfig::Ed25519(Secret::Input(keypair.secret()));
800 let certificate = webrtc::derive_certificate(keypair.secret().into())
801 .map_err(crate::error::Error::Litep2p)?;
802 webrtc::validate_and_complete_addresses(
803 &self.listen_addresses,
804 &mut self.public_addresses,
805 certificate.certhash().into(),
806 )
807 },
808 }
809 }
810
811 pub fn remove_webrtc_addresses(&mut self) {
817 self.listen_addresses.retain(|address| !webrtc::is_webrtc_address(address));
818 self.public_addresses.retain(|address| {
819 let keep = !webrtc::is_webrtc_address(address);
820 if !keep {
821 log::warn!(
822 target: crate::LOG_TARGET,
823 "removing public WebRTC address {address}: no WebRTC listener on this node",
824 );
825 }
826 keep
827 });
828 }
829}
830
831pub struct IpfsConfig<Block: BlockT, H: ExHashT, N: NetworkBackend<Block, H>> {
833 pub bitswap_config: N::BitswapConfig,
835 pub block_provider: Box<dyn crate::IpfsBlockProvider>,
837 pub bootnodes: Vec<MultiaddrWithPeerId>,
839}
840
841pub struct Params<Block: BlockT, H: ExHashT, N: NetworkBackend<Block, H>> {
843 pub role: Role,
845
846 pub executor: Box<dyn Fn(Pin<Box<dyn Future<Output = ()> + Send>>) + Send + Sync>,
848
849 pub network_config: FullNetworkConfiguration<Block, H, N>,
851
852 pub protocol_id: ProtocolId,
854
855 pub genesis_hash: Block::Hash,
857
858 pub fork_id: Option<String>,
861
862 pub metrics_registry: Option<Registry>,
864
865 pub block_announce_config: N::NotificationProtocolConfig,
867
868 pub ipfs_config: Option<IpfsConfig<Block, H, N>>,
870
871 pub notification_metrics: NotificationMetrics,
873}
874
875pub struct FullNetworkConfiguration<B: BlockT + 'static, H: ExHashT, N: NetworkBackend<B, H>> {
877 pub(crate) notification_protocols: Vec<N::NotificationProtocolConfig>,
879
880 pub(crate) request_response_protocols: Vec<N::RequestResponseProtocolConfig>,
882
883 pub network_config: NetworkConfiguration,
885
886 peer_store: Option<N::PeerStore>,
888
889 peer_store_handle: Arc<dyn PeerStoreProvider>,
891
892 pub metrics_registry: Option<Registry>,
894}
895
896impl<B: BlockT + 'static, H: ExHashT, N: NetworkBackend<B, H>> FullNetworkConfiguration<B, H, N> {
897 pub fn new(network_config: &NetworkConfiguration, metrics_registry: Option<Registry>) -> Self {
899 let bootnodes = network_config.boot_nodes.iter().map(|bootnode| bootnode.peer_id).collect();
900 let peer_store = N::peer_store(bootnodes, metrics_registry.clone());
901 let peer_store_handle = peer_store.handle();
902
903 Self {
904 peer_store: Some(peer_store),
905 peer_store_handle,
906 notification_protocols: Vec::new(),
907 request_response_protocols: Vec::new(),
908 network_config: network_config.clone(),
909 metrics_registry,
910 }
911 }
912
913 pub fn add_notification_protocol(&mut self, config: N::NotificationProtocolConfig) {
915 self.notification_protocols.push(config);
916 }
917
918 pub fn notification_protocols(&self) -> &Vec<N::NotificationProtocolConfig> {
920 &self.notification_protocols
921 }
922
923 pub fn add_request_response_protocol(&mut self, config: N::RequestResponseProtocolConfig) {
925 self.request_response_protocols.push(config);
926 }
927
928 pub fn peer_store_handle(&self) -> Arc<dyn PeerStoreProvider> {
930 Arc::clone(&self.peer_store_handle)
931 }
932
933 pub fn take_peer_store(&mut self) -> N::PeerStore {
941 self.peer_store
942 .take()
943 .expect("`PeerStore` can only be taken once when it's started; qed")
944 }
945
946 pub fn sanity_check_addresses(&self) -> Result<(), crate::error::Error> {
948 ensure_addresses_consistent_with_transport(
949 self.network_config.listen_addresses.iter(),
950 &self.network_config.transport,
951 )?;
952 ensure_addresses_consistent_with_transport(
953 self.network_config.boot_nodes.iter().map(|x| &x.multiaddr),
954 &self.network_config.transport,
955 )?;
956 ensure_addresses_consistent_with_transport(
957 self.network_config
958 .default_peers_set
959 .reserved_nodes
960 .iter()
961 .map(|x| &x.multiaddr),
962 &self.network_config.transport,
963 )?;
964
965 for notification_protocol in &self.notification_protocols {
966 ensure_addresses_consistent_with_transport(
967 notification_protocol.set_config().reserved_nodes.iter().map(|x| &x.multiaddr),
968 &self.network_config.transport,
969 )?;
970 }
971 ensure_addresses_consistent_with_transport(
972 self.network_config.public_addresses.iter(),
973 &self.network_config.transport,
974 )?;
975
976 Ok(())
977 }
978
979 pub fn sanity_check_bootnodes(&self) -> Result<(), crate::error::Error> {
981 self.network_config.boot_nodes.iter().try_for_each(|bootnode| {
982 if let Some(other) = self
983 .network_config
984 .boot_nodes
985 .iter()
986 .filter(|o| o.multiaddr == bootnode.multiaddr)
987 .find(|o| o.peer_id != bootnode.peer_id)
988 {
989 Err(crate::error::Error::DuplicateBootnode {
990 address: bootnode.multiaddr.clone().into(),
991 first_id: bootnode.peer_id.into(),
992 second_id: other.peer_id.into(),
993 })
994 } else {
995 Ok(())
996 }
997 })
998 }
999
1000 pub fn known_addresses(&self) -> Vec<(PeerId, Multiaddr)> {
1002 let mut addresses: Vec<_> = self
1003 .network_config
1004 .default_peers_set
1005 .reserved_nodes
1006 .iter()
1007 .map(|reserved| (reserved.peer_id, reserved.multiaddr.clone()))
1008 .chain(self.notification_protocols.iter().flat_map(|protocol| {
1009 protocol
1010 .set_config()
1011 .reserved_nodes
1012 .iter()
1013 .map(|reserved| (reserved.peer_id, reserved.multiaddr.clone()))
1014 }))
1015 .chain(
1016 self.network_config
1017 .boot_nodes
1018 .iter()
1019 .map(|bootnode| (bootnode.peer_id, bootnode.multiaddr.clone())),
1020 )
1021 .collect();
1022
1023 addresses.sort();
1025 addresses.dedup();
1026
1027 addresses
1028 }
1029}
1030
1031#[derive(Debug, Clone, Default, Copy)]
1033pub enum NetworkBackendType {
1034 #[default]
1038 Litep2p,
1039
1040 Libp2p,
1047}
1048
1049#[cfg(test)]
1050mod tests {
1051 use super::*;
1052 use tempfile::TempDir;
1053
1054 fn tempdir_with_prefix(prefix: &str) -> TempDir {
1055 tempfile::Builder::new().prefix(prefix).tempdir().unwrap()
1056 }
1057
1058 fn secret_bytes(kp: ed25519::Keypair) -> Vec<u8> {
1059 kp.secret().to_bytes().into()
1060 }
1061
1062 #[test]
1063 fn test_secret_file() {
1064 let tmp = tempdir_with_prefix("x");
1065 std::fs::remove_dir(tmp.path()).unwrap(); let file = tmp.path().join("x").to_path_buf();
1067 let kp1 = NodeKeyConfig::Ed25519(Secret::File(file.clone())).into_keypair().unwrap();
1068 let kp2 = NodeKeyConfig::Ed25519(Secret::File(file.clone())).into_keypair().unwrap();
1069 assert!(file.is_file() && secret_bytes(kp1) == secret_bytes(kp2))
1070 }
1071
1072 #[test]
1073 fn test_secret_input() {
1074 let sk = ed25519::SecretKey::generate();
1075 let kp1 = NodeKeyConfig::Ed25519(Secret::Input(sk.clone())).into_keypair().unwrap();
1076 let kp2 = NodeKeyConfig::Ed25519(Secret::Input(sk)).into_keypair().unwrap();
1077 assert!(secret_bytes(kp1) == secret_bytes(kp2));
1078 }
1079
1080 #[test]
1081 fn test_secret_new() {
1082 let kp1 = NodeKeyConfig::Ed25519(Secret::New).into_keypair().unwrap();
1083 let kp2 = NodeKeyConfig::Ed25519(Secret::New).into_keypair().unwrap();
1084 assert!(secret_bytes(kp1) != secret_bytes(kp2));
1085 }
1086}