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 litep2p::protocol::libp2p::bitswap::BitswapHandle as Litep2pBitswapHandle;
39pub use sc_network_types::{build_multiaddr, ed25519};
40use sc_network_types::{
41 multiaddr::{self, Multiaddr},
42 multihash::Multihash,
43 PeerId,
44};
45
46use crate::{
47 service::{ensure_addresses_consistent_with_transport, traits::NetworkBackend},
48 webrtc,
49};
50use codec::Encode;
51use prometheus_endpoint::Registry;
52use zeroize::Zeroize;
53
54pub use sc_network_common::{
55 role::{Role, Roles},
56 sync::SyncMode,
57 ExHashT,
58};
59
60use sp_runtime::traits::Block as BlockT;
61
62use std::{
63 error::Error,
64 fmt, fs,
65 future::Future,
66 io::{self, Write},
67 iter,
68 net::Ipv4Addr,
69 num::NonZeroUsize,
70 path::{Path, PathBuf},
71 pin::Pin,
72 str::{self, FromStr},
73 sync::Arc,
74 time::Duration,
75};
76
77pub const DEFAULT_IDLE_CONNECTION_TIMEOUT: Duration = Duration::from_secs(10);
81
82pub const KADEMLIA_MAX_PROVIDER_KEYS: usize = 10000;
86
87pub const KADEMLIA_PROVIDER_RECORD_TTL: Duration = Duration::from_secs(10 * 3600);
91
92pub const KADEMLIA_PROVIDER_REPUBLISH_INTERVAL: Duration = Duration::from_secs(12600);
96
97pub const DEFAULT_LIGHT_REQUEST_EXECUTION_TIMEOUT: Duration = Duration::from_secs(3);
99
100pub fn default_light_request_call_workers() -> NonZeroUsize {
103 let cpus = std::thread::available_parallelism().map_or(1, NonZeroUsize::get);
104 NonZeroUsize::new((cpus / 2).clamp(1, 4)).expect("clamped to at least 1; qed")
105}
106
107#[derive(Clone, PartialEq, Eq, Hash)]
111pub struct ProtocolId(smallvec::SmallVec<[u8; 6]>);
112
113impl<'a> From<&'a str> for ProtocolId {
114 fn from(bytes: &'a str) -> ProtocolId {
115 Self(bytes.as_bytes().into())
116 }
117}
118
119impl AsRef<str> for ProtocolId {
120 fn as_ref(&self) -> &str {
121 str::from_utf8(&self.0[..])
122 .expect("the only way to build a ProtocolId is through a UTF-8 String; qed")
123 }
124}
125
126impl fmt::Debug for ProtocolId {
127 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
128 fmt::Debug::fmt(self.as_ref(), f)
129 }
130}
131
132pub fn parse_str_addr(addr_str: &str) -> Result<(PeerId, Multiaddr), ParseErr> {
147 let addr: Multiaddr = addr_str.parse()?;
148 parse_addr(addr)
149}
150
151pub fn parse_addr(mut addr: Multiaddr) -> Result<(PeerId, Multiaddr), ParseErr> {
153 let multihash = match addr.pop() {
154 Some(multiaddr::Protocol::P2p(multihash)) => multihash,
155 _ => return Err(ParseErr::PeerIdMissing),
156 };
157 let peer_id = PeerId::from_multihash(multihash).map_err(|_| ParseErr::InvalidPeerId)?;
158
159 Ok((peer_id, addr))
160}
161
162fn configured_identity(address: &Multiaddr) -> Option<multiaddr::Protocol<'_>> {
164 address.iter().find(|protocol| {
165 matches!(protocol, multiaddr::Protocol::P2p(_) | multiaddr::Protocol::Certhash(_))
166 })
167}
168
169fn check_and_strip_identity(
177 address: &mut Multiaddr,
178 local_peer_id: PeerId,
179 certhash: Option<Multihash>,
180 node_key_origin: &str,
181) -> Result<(), crate::error::Error> {
182 let configured_address = address.clone();
183
184 let configured_peer_id = match address.iter().last() {
186 Some(multiaddr::Protocol::P2p(peer_id)) => {
187 address.pop();
188 Some(peer_id)
189 },
190 _ => None,
192 };
193
194 let configured_certhash = match address.iter().last() {
195 Some(multiaddr::Protocol::Certhash(hash)) => {
196 address.pop();
197 Some(hash)
198 },
199 _ => None,
200 };
201
202 if let Some(identity) = configured_identity(address) {
204 return Err(crate::error::Error::MalformedAddressIdentity {
205 component: identity.to_string(),
206 address: configured_address,
207 });
208 }
209
210 if address.iter().next().is_none() {
212 if let Some(identity) = configured_identity(&configured_address) {
213 return Err(crate::error::Error::MalformedAddressIdentity {
214 component: identity.to_string(),
215 address: configured_address,
216 });
217 }
218 }
219
220 if let Some(configured) = configured_certhash {
222 let expected =
223 certhash.filter(|_| webrtc::is_webrtc_address(address)).ok_or_else(|| {
224 crate::error::Error::InvalidWebRtcAddress { address: configured_address.clone() }
225 })?;
226
227 if configured != expected {
228 return Err(crate::error::Error::MismatchedAddressIdentity {
229 address: configured_address,
230 configured: multiaddr::Protocol::Certhash(configured).to_string(),
231 expected: multiaddr::Protocol::Certhash(expected).to_string(),
232 node_key_origin: node_key_origin.to_string(),
233 });
234 }
235 }
236
237 if let Some(configured) = configured_peer_id {
238 let expected = local_peer_id.into();
239 if configured != expected {
240 return Err(crate::error::Error::MismatchedAddressIdentity {
241 address: configured_address,
242 configured: multiaddr::Protocol::P2p(configured).to_string(),
243 expected: multiaddr::Protocol::P2p(expected).to_string(),
244 node_key_origin: node_key_origin.to_string(),
245 });
246 }
247 }
248
249 Ok(())
250}
251
252#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
267#[serde(try_from = "String", into = "String")]
268pub struct MultiaddrWithPeerId {
269 pub multiaddr: Multiaddr,
271 pub peer_id: PeerId,
273}
274
275impl MultiaddrWithPeerId {
276 pub fn concat(&self) -> Multiaddr {
278 let mut addr = self.multiaddr.clone();
279 if matches!(addr.iter().last(), Some(multiaddr::Protocol::P2p(_))) {
281 addr.pop();
282 }
283 addr.with(multiaddr::Protocol::P2p(From::from(self.peer_id)))
284 }
285}
286
287impl fmt::Display for MultiaddrWithPeerId {
288 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
289 fmt::Display::fmt(&self.concat(), f)
290 }
291}
292
293impl FromStr for MultiaddrWithPeerId {
294 type Err = ParseErr;
295
296 fn from_str(s: &str) -> Result<Self, Self::Err> {
297 let (peer_id, multiaddr) = parse_str_addr(s)?;
298 Ok(Self { peer_id, multiaddr })
299 }
300}
301
302impl From<MultiaddrWithPeerId> for String {
303 fn from(ma: MultiaddrWithPeerId) -> String {
304 format!("{}", ma)
305 }
306}
307
308impl TryFrom<String> for MultiaddrWithPeerId {
309 type Error = ParseErr;
310 fn try_from(string: String) -> Result<Self, Self::Error> {
311 string.parse()
312 }
313}
314
315#[derive(Debug)]
317pub enum ParseErr {
318 MultiaddrParse(multiaddr::ParseError),
320 InvalidPeerId,
322 PeerIdMissing,
324}
325
326impl fmt::Display for ParseErr {
327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328 match self {
329 Self::MultiaddrParse(err) => write!(f, "{}", err),
330 Self::InvalidPeerId => write!(f, "Peer id at the end of the address is invalid"),
331 Self::PeerIdMissing => write!(f, "Peer id is missing from the address"),
332 }
333 }
334}
335
336impl std::error::Error for ParseErr {
337 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
338 match self {
339 Self::MultiaddrParse(err) => Some(err),
340 Self::InvalidPeerId => None,
341 Self::PeerIdMissing => None,
342 }
343 }
344}
345
346impl From<multiaddr::ParseError> for ParseErr {
347 fn from(err: multiaddr::ParseError) -> ParseErr {
348 Self::MultiaddrParse(err)
349 }
350}
351
352#[derive(Debug, Clone)]
354pub struct NotificationHandshake(Vec<u8>);
355
356impl NotificationHandshake {
357 pub fn new<H: Encode>(handshake: H) -> Self {
359 Self(handshake.encode())
360 }
361
362 pub fn from_bytes(bytes: Vec<u8>) -> Self {
364 Self(bytes)
365 }
366}
367
368impl std::ops::Deref for NotificationHandshake {
369 type Target = Vec<u8>;
370
371 fn deref(&self) -> &Self::Target {
372 &self.0
373 }
374}
375
376#[derive(Clone, Debug)]
378pub enum TransportConfig {
379 Normal {
381 enable_mdns: bool,
384
385 allow_private_ip: bool,
389 },
390
391 MemoryOnly,
394}
395
396#[derive(Clone, Debug, PartialEq, Eq)]
398pub enum NonReservedPeerMode {
399 Accept,
401 Deny,
403}
404
405impl NonReservedPeerMode {
406 pub fn parse(s: &str) -> Option<Self> {
408 match s {
409 "accept" => Some(Self::Accept),
410 "deny" => Some(Self::Deny),
411 _ => None,
412 }
413 }
414
415 pub fn is_reserved_only(&self) -> bool {
417 matches!(self, NonReservedPeerMode::Deny)
418 }
419}
420
421#[derive(Clone, Debug)]
425pub enum NodeKeyConfig {
426 Ed25519(Secret<ed25519::SecretKey>),
428}
429
430impl Default for NodeKeyConfig {
431 fn default() -> NodeKeyConfig {
432 Self::Ed25519(Secret::New)
433 }
434}
435
436pub type Ed25519Secret = Secret<ed25519::SecretKey>;
438
439#[derive(Clone)]
441pub enum Secret<K> {
442 Input(K),
444 File(PathBuf),
450 New,
452}
453
454impl<K> fmt::Debug for Secret<K> {
455 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
456 match self {
457 Self::Input(_) => f.debug_tuple("Secret::Input").finish(),
458 Self::File(path) => f.debug_tuple("Secret::File").field(path).finish(),
459 Self::New => f.debug_tuple("Secret::New").finish(),
460 }
461 }
462}
463
464impl NodeKeyConfig {
465 fn source(&self) -> String {
467 match self {
468 Self::Ed25519(Secret::Input(_)) => "the node key given with `--node-key`".into(),
469 Self::Ed25519(Secret::File(path)) => format!("the node key file `{}`", path.display()),
470 Self::Ed25519(Secret::New) => "the node key generated anew on each start".into(),
471 }
472 }
473
474 fn missing(&self) -> bool {
476 match self {
477 Self::Ed25519(Secret::Input(_)) => false,
478 Self::Ed25519(Secret::File(path)) => !path.exists(),
479 Self::Ed25519(Secret::New) => true,
480 }
481 }
482
483 pub fn into_keypair(self) -> io::Result<ed25519::Keypair> {
494 use NodeKeyConfig::*;
495 match self {
496 Ed25519(Secret::New) => Ok(ed25519::Keypair::generate()),
497
498 Ed25519(Secret::Input(k)) => Ok(ed25519::Keypair::from(k).into()),
499
500 Ed25519(Secret::File(f)) => get_secret(
501 f,
502 |mut b| match String::from_utf8(b.to_vec()).ok().and_then(|s| {
503 if s.len() == 64 {
504 array_bytes::hex2bytes(&s).ok()
505 } else {
506 None
507 }
508 }) {
509 Some(s) => ed25519::SecretKey::try_from_bytes(s),
510 _ => ed25519::SecretKey::try_from_bytes(&mut b),
511 },
512 ed25519::SecretKey::generate,
513 |b| b.as_ref().to_vec(),
514 )
515 .map(ed25519::Keypair::from),
516 }
517 }
518}
519
520fn get_secret<P, F, G, E, W, K>(file: P, parse: F, generate: G, serialize: W) -> io::Result<K>
524where
525 P: AsRef<Path>,
526 F: for<'r> FnOnce(&'r mut [u8]) -> Result<K, E>,
527 G: FnOnce() -> K,
528 E: Error + Send + Sync + 'static,
529 W: Fn(&K) -> Vec<u8>,
530{
531 std::fs::read(&file)
532 .and_then(|mut sk_bytes| {
533 parse(&mut sk_bytes).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
534 })
535 .or_else(|e| {
536 if e.kind() == io::ErrorKind::NotFound {
537 file.as_ref().parent().map_or(Ok(()), fs::create_dir_all)?;
538 let sk = generate();
539 let mut sk_vec = serialize(&sk);
540 write_secret_file(file, &sk_vec)?;
541 sk_vec.zeroize();
542 Ok(sk)
543 } else {
544 Err(e)
545 }
546 })
547}
548
549pub(super) fn write_secret_file<P>(path: P, sk_bytes: &[u8]) -> io::Result<()>
551where
552 P: AsRef<Path>,
553{
554 let mut file = open_secret_file(&path)?;
555 file.write_all(sk_bytes)
556}
557
558#[cfg(unix)]
560fn open_secret_file<P>(path: P) -> io::Result<fs::File>
561where
562 P: AsRef<Path>,
563{
564 use std::os::unix::fs::OpenOptionsExt;
565 fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(path)
566}
567
568#[cfg(not(unix))]
570fn open_secret_file<P>(path: P) -> Result<fs::File, io::Error>
571where
572 P: AsRef<Path>,
573{
574 fs::OpenOptions::new().write(true).create_new(true).open(path)
575}
576
577#[derive(Clone, Debug)]
579pub struct SetConfig {
580 pub in_peers: u32,
582
583 pub out_peers: u32,
585
586 pub reserved_nodes: Vec<MultiaddrWithPeerId>,
588
589 pub non_reserved_mode: NonReservedPeerMode,
592}
593
594impl Default for SetConfig {
595 fn default() -> Self {
596 Self {
597 in_peers: 25,
598 out_peers: 75,
599 reserved_nodes: Vec::new(),
600 non_reserved_mode: NonReservedPeerMode::Accept,
601 }
602 }
603}
604
605#[derive(Debug)]
610pub struct NonDefaultSetConfig {
611 protocol_name: ProtocolName,
617
618 fallback_names: Vec<ProtocolName>,
625
626 handshake: Option<NotificationHandshake>,
632
633 max_notification_size: u64,
635
636 set_config: SetConfig,
638
639 protocol_handle_pair: ProtocolHandlePair,
647}
648
649impl NonDefaultSetConfig {
650 pub fn new(
653 protocol_name: ProtocolName,
654 fallback_names: Vec<ProtocolName>,
655 max_notification_size: u64,
656 handshake: Option<NotificationHandshake>,
657 set_config: SetConfig,
658 ) -> (Self, Box<dyn NotificationService>) {
659 let (protocol_handle_pair, notification_service) =
660 notification_service(protocol_name.clone());
661 (
662 Self {
663 protocol_name,
664 max_notification_size,
665 fallback_names,
666 handshake,
667 set_config,
668 protocol_handle_pair,
669 },
670 notification_service,
671 )
672 }
673
674 pub fn protocol_name(&self) -> &ProtocolName {
676 &self.protocol_name
677 }
678
679 pub fn fallback_names(&self) -> impl Iterator<Item = &ProtocolName> {
681 self.fallback_names.iter()
682 }
683
684 pub fn handshake(&self) -> &Option<NotificationHandshake> {
686 &self.handshake
687 }
688
689 pub fn max_notification_size(&self) -> u64 {
691 self.max_notification_size
692 }
693
694 pub fn set_config(&self) -> &SetConfig {
696 &self.set_config
697 }
698
699 pub fn take_protocol_handle(self) -> ProtocolHandlePair {
701 self.protocol_handle_pair
702 }
703
704 pub fn allow_non_reserved(&mut self, in_peers: u32, out_peers: u32) {
706 self.set_config.in_peers = in_peers;
707 self.set_config.out_peers = out_peers;
708 self.set_config.non_reserved_mode = NonReservedPeerMode::Accept;
709 }
710
711 pub fn add_reserved(&mut self, peer: MultiaddrWithPeerId) {
713 self.set_config.reserved_nodes.push(peer);
714 }
715
716 pub fn add_fallback_names(&mut self, fallback_names: Vec<ProtocolName>) {
720 self.fallback_names.extend(fallback_names);
721 }
722}
723
724impl NotificationConfig for NonDefaultSetConfig {
725 fn set_config(&self) -> &SetConfig {
726 &self.set_config
727 }
728
729 fn protocol_name(&self) -> &ProtocolName {
731 &self.protocol_name
732 }
733}
734
735#[derive(Clone, Debug)]
737pub struct NetworkConfiguration {
738 pub net_config_path: Option<PathBuf>,
740
741 pub listen_addresses: Vec<Multiaddr>,
743
744 pub public_addresses: Vec<Multiaddr>,
746
747 pub boot_nodes: Vec<MultiaddrWithPeerId>,
749
750 pub node_key: NodeKeyConfig,
752
753 pub default_peers_set: SetConfig,
755
756 pub default_peers_set_num_full: u32,
761
762 pub client_version: String,
764
765 pub node_name: String,
767
768 pub transport: TransportConfig,
770
771 pub idle_connection_timeout: Duration,
775
776 pub max_parallel_downloads: u32,
778
779 pub max_blocks_per_request: u32,
781
782 pub min_peers_to_start_warp_sync: Option<usize>,
784
785 pub sync_mode: SyncMode,
787
788 pub enable_dht_random_walk: bool,
792
793 pub allow_non_globals_in_dht: bool,
795
796 pub kademlia_disjoint_query_paths: bool,
799
800 pub kademlia_replication_factor: NonZeroUsize,
805
806 pub ipfs_server: bool,
808
809 pub ipfs_bootnodes: Vec<MultiaddrWithPeerId>,
815
816 pub light_request_execution_timeout: Option<Duration>,
819
820 pub light_request_call_workers: NonZeroUsize,
822
823 pub network_backend: NetworkBackendType,
825}
826
827impl NetworkConfiguration {
828 pub fn new<SN: Into<String>, SV: Into<String>>(
830 node_name: SN,
831 client_version: SV,
832 node_key: NodeKeyConfig,
833 net_config_path: Option<PathBuf>,
834 ) -> Self {
835 let default_peers_set = SetConfig::default();
836 Self {
837 net_config_path,
838 listen_addresses: Vec::new(),
839 public_addresses: Vec::new(),
840 boot_nodes: Vec::new(),
841 node_key,
842 default_peers_set_num_full: default_peers_set.in_peers + default_peers_set.out_peers,
843 default_peers_set,
844 client_version: client_version.into(),
845 node_name: node_name.into(),
846 transport: TransportConfig::Normal { enable_mdns: false, allow_private_ip: true },
847 idle_connection_timeout: DEFAULT_IDLE_CONNECTION_TIMEOUT,
848 max_parallel_downloads: 5,
849 max_blocks_per_request: 64,
850 min_peers_to_start_warp_sync: None,
851 sync_mode: SyncMode::Full,
852 enable_dht_random_walk: true,
853 allow_non_globals_in_dht: false,
854 kademlia_disjoint_query_paths: false,
855 kademlia_replication_factor: NonZeroUsize::new(DEFAULT_KADEMLIA_REPLICATION_FACTOR)
856 .expect("value is a constant; constant is non-zero; qed."),
857 ipfs_server: false,
858 ipfs_bootnodes: Vec::new(),
859 light_request_execution_timeout: Some(DEFAULT_LIGHT_REQUEST_EXECUTION_TIMEOUT),
860 light_request_call_workers: default_light_request_call_workers(),
861 network_backend: NetworkBackendType::Litep2p,
862 }
863 }
864
865 pub fn new_local() -> NetworkConfiguration {
868 let mut config =
869 NetworkConfiguration::new("test-node", "test-client", Default::default(), None);
870
871 config.listen_addresses =
872 vec![iter::once(multiaddr::Protocol::Ip4(Ipv4Addr::new(127, 0, 0, 1)))
873 .chain(iter::once(multiaddr::Protocol::Tcp(0)))
874 .collect()];
875
876 config.allow_non_globals_in_dht = true;
877 config
878 }
879
880 pub fn new_memory() -> NetworkConfiguration {
883 let mut config =
884 NetworkConfiguration::new("test-node", "test-client", Default::default(), None);
885
886 config.listen_addresses =
887 vec![iter::once(multiaddr::Protocol::Ip4(Ipv4Addr::new(127, 0, 0, 1)))
888 .chain(iter::once(multiaddr::Protocol::Tcp(0)))
889 .collect()];
890
891 config.allow_non_globals_in_dht = true;
892 config
893 }
894
895 pub fn validate_and_complete_addresses(&mut self) -> Result<(), crate::error::Error> {
901 let listen_webrtc = self.listen_addresses.iter().any(webrtc::is_webrtc_address);
902 let public_webrtc = self.public_addresses.iter().any(webrtc::is_webrtc_address);
903 let addresses = || self.listen_addresses.iter().chain(&self.public_addresses);
904
905 if matches!(self.network_backend, NetworkBackendType::Libp2p) &&
907 (listen_webrtc || public_webrtc)
908 {
909 return Err(crate::error::Error::WebRtcNotSupportedByBackend);
910 }
911
912 if !listen_webrtc && public_webrtc {
915 return Err(crate::error::Error::WebRtcTransportNotConfigured);
916 }
917
918 let has_identity = addresses().any(|address| configured_identity(address).is_some());
919
920 if !listen_webrtc && !has_identity {
923 return Ok(());
924 }
925
926 if has_identity && self.node_key.missing() {
928 return Err(crate::error::Error::AddressIdentityWithoutNodeKey);
929 }
930
931 let node_key_origin = self.node_key.source();
933 let keypair = self.node_key.clone().into_keypair()?;
934 let local_peer_id = keypair.public().to_peer_id();
935
936 let certhash = listen_webrtc
937 .then(|| webrtc::derive_certificate(keypair.secret().into()))
938 .transpose()
939 .map_err(crate::error::Error::Litep2p)?
940 .map(|certificate| certificate.certhash().into());
941
942 self.node_key = NodeKeyConfig::Ed25519(Secret::Input(keypair.secret()));
945
946 for address in self.listen_addresses.iter_mut() {
947 check_and_strip_identity(address, local_peer_id, certhash, &node_key_origin)?;
948 }
949
950 for address in self.public_addresses.iter_mut() {
952 check_and_strip_identity(address, local_peer_id, certhash, &node_key_origin)?;
953 }
954
955 if let Some(certhash) = certhash {
958 webrtc::validate_and_complete_addresses(
959 &self.listen_addresses,
960 &mut self.public_addresses,
961 certhash,
962 )?;
963 }
964
965 Ok(())
966 }
967
968 pub fn remove_webrtc_addresses(&mut self) {
974 self.listen_addresses.retain(|address| !webrtc::is_webrtc_address(address));
975 self.public_addresses.retain(|address| {
976 let keep = !webrtc::is_webrtc_address(address);
977 if !keep {
978 log::warn!(
979 target: crate::LOG_TARGET,
980 "removing public WebRTC address {address}: no WebRTC listener on this node",
981 );
982 }
983 keep
984 });
985 }
986}
987
988pub struct IpfsConfig {
990 pub litep2p_bitswap_config: litep2p::protocol::libp2p::bitswap::Config,
992 pub block_provider: Box<dyn crate::IpfsBlockProvider>,
994 pub bootnodes: Vec<MultiaddrWithPeerId>,
996}
997
998impl IpfsConfig {
999 pub fn new(
1001 block_provider: Box<dyn crate::IpfsBlockProvider>,
1002 bootnodes: Vec<MultiaddrWithPeerId>,
1003 ) -> (Self, Litep2pBitswapHandle) {
1004 let (litep2p_bitswap_config, litep2p_handle) =
1005 litep2p::protocol::libp2p::bitswap::Config::new();
1006 (Self { litep2p_bitswap_config, block_provider, bootnodes }, litep2p_handle)
1007 }
1008}
1009
1010pub struct Params<Block: BlockT, H: ExHashT, N: NetworkBackend<Block, H>> {
1012 pub role: Role,
1014
1015 pub executor: Box<dyn Fn(Pin<Box<dyn Future<Output = ()> + Send>>) + Send + Sync>,
1017
1018 pub network_config: FullNetworkConfiguration<Block, H, N>,
1020
1021 pub protocol_id: ProtocolId,
1023
1024 pub genesis_hash: Block::Hash,
1026
1027 pub fork_id: Option<String>,
1030
1031 pub metrics_registry: Option<Registry>,
1033
1034 pub block_announce_config: N::NotificationProtocolConfig,
1036
1037 pub ipfs_config: Option<IpfsConfig>,
1039
1040 pub notification_metrics: NotificationMetrics,
1042}
1043
1044pub struct FullNetworkConfiguration<B: BlockT + 'static, H: ExHashT, N: NetworkBackend<B, H>> {
1046 pub(crate) notification_protocols: Vec<N::NotificationProtocolConfig>,
1048
1049 pub(crate) request_response_protocols: Vec<N::RequestResponseProtocolConfig>,
1051
1052 pub network_config: NetworkConfiguration,
1054
1055 peer_store: Option<N::PeerStore>,
1057
1058 peer_store_handle: Arc<dyn PeerStoreProvider>,
1060
1061 pub metrics_registry: Option<Registry>,
1063}
1064
1065impl<B: BlockT + 'static, H: ExHashT, N: NetworkBackend<B, H>> FullNetworkConfiguration<B, H, N> {
1066 pub fn new(network_config: &NetworkConfiguration, metrics_registry: Option<Registry>) -> Self {
1068 let bootnodes = network_config.boot_nodes.iter().map(|bootnode| bootnode.peer_id).collect();
1069 let peer_store = N::peer_store(bootnodes, metrics_registry.clone());
1070 let peer_store_handle = peer_store.handle();
1071
1072 Self {
1073 peer_store: Some(peer_store),
1074 peer_store_handle,
1075 notification_protocols: Vec::new(),
1076 request_response_protocols: Vec::new(),
1077 network_config: network_config.clone(),
1078 metrics_registry,
1079 }
1080 }
1081
1082 pub fn add_notification_protocol(&mut self, config: N::NotificationProtocolConfig) {
1084 self.notification_protocols.push(config);
1085 }
1086
1087 pub fn notification_protocols(&self) -> &Vec<N::NotificationProtocolConfig> {
1089 &self.notification_protocols
1090 }
1091
1092 pub fn add_request_response_protocol(&mut self, config: N::RequestResponseProtocolConfig) {
1094 self.request_response_protocols.push(config);
1095 }
1096
1097 pub fn peer_store_handle(&self) -> Arc<dyn PeerStoreProvider> {
1099 Arc::clone(&self.peer_store_handle)
1100 }
1101
1102 pub fn take_peer_store(&mut self) -> N::PeerStore {
1110 self.peer_store
1111 .take()
1112 .expect("`PeerStore` can only be taken once when it's started; qed")
1113 }
1114
1115 pub fn sanity_check_addresses(&self) -> Result<(), crate::error::Error> {
1117 ensure_addresses_consistent_with_transport(
1118 self.network_config.listen_addresses.iter(),
1119 &self.network_config.transport,
1120 )?;
1121 ensure_addresses_consistent_with_transport(
1122 self.network_config.boot_nodes.iter().map(|x| &x.multiaddr),
1123 &self.network_config.transport,
1124 )?;
1125 ensure_addresses_consistent_with_transport(
1126 self.network_config
1127 .default_peers_set
1128 .reserved_nodes
1129 .iter()
1130 .map(|x| &x.multiaddr),
1131 &self.network_config.transport,
1132 )?;
1133
1134 for notification_protocol in &self.notification_protocols {
1135 ensure_addresses_consistent_with_transport(
1136 notification_protocol.set_config().reserved_nodes.iter().map(|x| &x.multiaddr),
1137 &self.network_config.transport,
1138 )?;
1139 }
1140 ensure_addresses_consistent_with_transport(
1141 self.network_config.public_addresses.iter(),
1142 &self.network_config.transport,
1143 )?;
1144
1145 Ok(())
1146 }
1147
1148 pub fn sanity_check_bootnodes(&self) -> Result<(), crate::error::Error> {
1150 self.network_config.boot_nodes.iter().try_for_each(|bootnode| {
1151 if let Some(other) = self
1152 .network_config
1153 .boot_nodes
1154 .iter()
1155 .filter(|o| o.multiaddr == bootnode.multiaddr)
1156 .find(|o| o.peer_id != bootnode.peer_id)
1157 {
1158 Err(crate::error::Error::DuplicateBootnode {
1159 address: bootnode.multiaddr.clone().into(),
1160 first_id: bootnode.peer_id.into(),
1161 second_id: other.peer_id.into(),
1162 })
1163 } else {
1164 Ok(())
1165 }
1166 })
1167 }
1168
1169 pub fn known_addresses(&self) -> Vec<(PeerId, Multiaddr)> {
1171 let mut addresses: Vec<_> = self
1172 .network_config
1173 .default_peers_set
1174 .reserved_nodes
1175 .iter()
1176 .map(|reserved| (reserved.peer_id, reserved.multiaddr.clone()))
1177 .chain(self.notification_protocols.iter().flat_map(|protocol| {
1178 protocol
1179 .set_config()
1180 .reserved_nodes
1181 .iter()
1182 .map(|reserved| (reserved.peer_id, reserved.multiaddr.clone()))
1183 }))
1184 .chain(
1185 self.network_config
1186 .boot_nodes
1187 .iter()
1188 .map(|bootnode| (bootnode.peer_id, bootnode.multiaddr.clone())),
1189 )
1190 .collect();
1191
1192 addresses.sort();
1194 addresses.dedup();
1195
1196 addresses
1197 }
1198}
1199
1200#[derive(Debug, Clone, Default, Copy)]
1202pub enum NetworkBackendType {
1203 #[default]
1207 Litep2p,
1208
1209 Libp2p,
1216}
1217
1218#[cfg(test)]
1219mod tests {
1220 use super::*;
1221 use tempfile::TempDir;
1222
1223 fn tempdir_with_prefix(prefix: &str) -> TempDir {
1224 tempfile::Builder::new().prefix(prefix).tempdir().unwrap()
1225 }
1226
1227 fn secret_bytes(kp: ed25519::Keypair) -> Vec<u8> {
1228 kp.secret().to_bytes().into()
1229 }
1230
1231 #[test]
1232 fn test_secret_file() {
1233 let tmp = tempdir_with_prefix("x");
1234 std::fs::remove_dir(tmp.path()).unwrap(); let file = tmp.path().join("x").to_path_buf();
1236 let kp1 = NodeKeyConfig::Ed25519(Secret::File(file.clone())).into_keypair().unwrap();
1237 let kp2 = NodeKeyConfig::Ed25519(Secret::File(file.clone())).into_keypair().unwrap();
1238 assert!(file.is_file() && secret_bytes(kp1) == secret_bytes(kp2))
1239 }
1240
1241 #[test]
1242 fn test_secret_input() {
1243 let sk = ed25519::SecretKey::generate();
1244 let kp1 = NodeKeyConfig::Ed25519(Secret::Input(sk.clone())).into_keypair().unwrap();
1245 let kp2 = NodeKeyConfig::Ed25519(Secret::Input(sk)).into_keypair().unwrap();
1246 assert!(secret_bytes(kp1) == secret_bytes(kp2));
1247 }
1248
1249 #[test]
1250 fn test_secret_new() {
1251 let kp1 = NodeKeyConfig::Ed25519(Secret::New).into_keypair().unwrap();
1252 let kp2 = NodeKeyConfig::Ed25519(Secret::New).into_keypair().unwrap();
1253 assert!(secret_bytes(kp1) != secret_bytes(kp2));
1254 }
1255}