Skip to main content

subspace_networking/
constructor.rs

1pub(crate) mod temporary_bans;
2mod transport;
3
4use crate::behavior::persistent_parameters::{KnownPeersRegistry, StubNetworkingParametersManager};
5use crate::behavior::{Behavior, BehaviorConfig};
6use crate::constructor::temporary_bans::TemporaryBans;
7use crate::constructor::transport::build_transport;
8use crate::node::Node;
9use crate::node_runner::{NodeRunner, NodeRunnerConfig};
10use crate::protocols::autonat_wrapper::Config as AutonatWrapperConfig;
11use crate::protocols::request_response::request_response_factory::RequestHandler;
12use crate::protocols::reserved_peers::Config as ReservedPeersConfig;
13use crate::shared::Shared;
14use crate::utils::rate_limiter::RateLimiter;
15use crate::utils::{SubspaceMetrics, strip_peer_id};
16use backon::ExponentialBuilder;
17use futures::channel::mpsc;
18use libp2p::autonat::Config as AutonatConfig;
19use libp2p::connection_limits::ConnectionLimits;
20use libp2p::identify::Config as IdentifyConfig;
21use libp2p::kad::store::RecordStore;
22use libp2p::kad::{
23    BucketInserts, Config as KademliaConfig, Mode, ProviderRecord, Record, RecordKey, StoreInserts,
24    store,
25};
26use libp2p::metrics::Metrics;
27use libp2p::multiaddr::Protocol;
28use libp2p::yamux::Config as YamuxConfig;
29use libp2p::{Multiaddr, PeerId, StreamProtocol, SwarmBuilder, TransportError, identity};
30use parking_lot::Mutex;
31use prometheus_client::registry::Registry;
32use std::borrow::Cow;
33use std::iter::Empty;
34use std::sync::Arc;
35use std::time::Duration;
36use std::{fmt, io, iter};
37use subspace_core_primitives::pieces::Piece;
38use thiserror::Error;
39use tracing::{debug, info};
40
41const DEFAULT_NETWORK_PROTOCOL_VERSION: &str = "dev";
42const KADEMLIA_PROTOCOL: &str = "/subspace/kad/0.1.0";
43
44/// Defines max_negotiating_inbound_streams constant for the swarm.
45/// It must be set for large plots.
46const SWARM_MAX_NEGOTIATING_INBOUND_STREAMS: usize = 100000;
47/// How long will connection be allowed to be open without any usage
48const IDLE_CONNECTION_TIMEOUT: Duration = Duration::from_secs(3);
49/// The default maximum established incoming connection number for the swarm.
50const SWARM_MAX_ESTABLISHED_INCOMING_CONNECTIONS: u32 = 100;
51/// The default maximum established incoming connection number for the swarm.
52const SWARM_MAX_ESTABLISHED_OUTGOING_CONNECTIONS: u32 = 100;
53/// The default maximum pending incoming connection number for the swarm.
54const SWARM_MAX_PENDING_INCOMING_CONNECTIONS: u32 = 80;
55/// The default maximum pending incoming connection number for the swarm.
56const SWARM_MAX_PENDING_OUTGOING_CONNECTIONS: u32 = 80;
57const KADEMLIA_QUERY_TIMEOUT: Duration = Duration::from_secs(40);
58const SWARM_MAX_ESTABLISHED_CONNECTIONS_PER_PEER: u32 = 3;
59const MAX_CONCURRENT_STREAMS_PER_CONNECTION: usize = 10;
60
61const TEMPORARY_BANS_CACHE_SIZE: u32 = 10_000;
62const TEMPORARY_BANS_DEFAULT_BACKOFF_INITIAL_INTERVAL: Duration = Duration::from_secs(5);
63const TEMPORARY_BANS_DEFAULT_BACKOFF_MULTIPLIER: f64 = 1.5;
64const TEMPORARY_BANS_DEFAULT_MAX_INTERVAL: Duration = Duration::from_secs(30 * 60);
65
66/// We pause between reserved peers dialing otherwise we could do multiple dials to offline peers
67/// wasting resources and producing a ton of log records.
68const DIALING_INTERVAL_IN_SECS: Duration = Duration::from_secs(1);
69
70/// Max confidence for autonat protocol. Could affect Kademlia mode change.
71pub(crate) const AUTONAT_MAX_CONFIDENCE: usize = 3;
72/// We set a very long pause before autonat initialization (Duration::Max panics).
73const AUTONAT_SERVER_PROBE_DELAY: Duration = Duration::from_secs(3600 * 24 * 365);
74
75/// Defines Kademlia mode
76#[derive(Clone, Debug)]
77pub enum KademliaMode {
78    /// The Kademlia mode is static for the duration of the application.
79    Static(Mode),
80    /// Kademlia mode will be changed using Autonat protocol when max confidence reached.
81    Dynamic,
82}
83
84impl KademliaMode {
85    /// Returns true if the mode is Dynamic.
86    pub fn is_dynamic(&self) -> bool {
87        matches!(self, Self::Dynamic)
88    }
89
90    /// Returns true if the mode is Static.
91    pub fn is_static(&self) -> bool {
92        matches!(self, Self::Static(..))
93    }
94}
95
96pub(crate) struct DummyRecordStore;
97
98impl RecordStore for DummyRecordStore {
99    type RecordsIter<'a>
100        = Empty<Cow<'a, Record>>
101    where
102        Self: 'a;
103    type ProvidedIter<'a>
104        = Empty<Cow<'a, ProviderRecord>>
105    where
106        Self: 'a;
107
108    #[inline]
109    fn get(&self, _key: &RecordKey) -> Option<Cow<'_, Record>> {
110        // Not supported
111        None
112    }
113
114    #[inline]
115    fn put(&mut self, _record: Record) -> store::Result<()> {
116        // Not supported
117        Ok(())
118    }
119
120    #[inline]
121    fn remove(&mut self, _key: &RecordKey) {
122        // Not supported
123    }
124
125    #[inline]
126    fn records(&self) -> Self::RecordsIter<'_> {
127        // Not supported
128        iter::empty()
129    }
130
131    #[inline]
132    fn add_provider(&mut self, _record: ProviderRecord) -> store::Result<()> {
133        // Not supported
134        Ok(())
135    }
136
137    #[inline]
138    fn providers(&self, _key: &RecordKey) -> Vec<ProviderRecord> {
139        // Not supported
140        Vec::new()
141    }
142
143    #[inline]
144    fn provided(&self) -> Self::ProvidedIter<'_> {
145        // Not supported
146        iter::empty()
147    }
148
149    #[inline]
150    fn remove_provider(&mut self, _key: &RecordKey, _provider: &PeerId) {
151        // Not supported
152    }
153}
154
155/// [`Node`] configuration.
156pub struct Config {
157    /// Identity keypair of a node used for authenticated connections.
158    pub keypair: identity::Keypair,
159    /// List of [`Multiaddr`] on which to listen for incoming connections.
160    pub listen_on: Vec<Multiaddr>,
161    /// Fallback to random port if specified (or default) port is already occupied.
162    pub listen_on_fallback_to_random_port: bool,
163    /// Adds a timeout to the setup and protocol upgrade process for all inbound and outbound
164    /// connections established through the transport.
165    pub timeout: Duration,
166    /// The configuration for the Identify behaviour.
167    pub identify: IdentifyConfig,
168    /// The configuration for the Kademlia behaviour.
169    pub kademlia: KademliaConfig,
170    /// Yamux multiplexing configuration.
171    pub yamux_config: YamuxConfig,
172    /// Should non-global addresses be added to the DHT?
173    pub allow_non_global_addresses_in_dht: bool,
174    /// How frequently should random queries be done using Kademlia DHT to populate routing table.
175    pub initial_random_query_interval: Duration,
176    /// A reference to the `NetworkingParametersRegistry` implementation.
177    pub known_peers_registry: Box<dyn KnownPeersRegistry>,
178    /// The configuration for the `RequestResponsesBehaviour` protocol.
179    pub request_response_protocols: Vec<Box<dyn RequestHandler>>,
180    /// Defines set of peers with a permanent connection (and reconnection if necessary).
181    pub reserved_peers: Vec<Multiaddr>,
182    /// Established incoming swarm connection limit.
183    pub max_established_incoming_connections: u32,
184    /// Established outgoing swarm connection limit.
185    pub max_established_outgoing_connections: u32,
186    /// Pending incoming swarm connection limit.
187    pub max_pending_incoming_connections: u32,
188    /// Pending outgoing swarm connection limit.
189    pub max_pending_outgoing_connections: u32,
190    /// How many temporarily banned unreachable peers to keep in memory.
191    pub temporary_bans_cache_size: u32,
192    /// Backoff policy for temporary banning of unreachable peers.
193    pub temporary_ban_backoff: ExponentialBuilder,
194    /// Optional libp2p prometheus metrics. None will disable metrics gathering.
195    pub libp2p_metrics: Option<Metrics>,
196    /// Internal prometheus metrics. None will disable metrics gathering.
197    pub metrics: Option<SubspaceMetrics>,
198    /// Defines protocol version for the network peers. Affects network partition.
199    pub protocol_version: String,
200    /// Addresses to bootstrap Kademlia network
201    pub bootstrap_addresses: Vec<Multiaddr>,
202    /// Kademlia mode. The default value is set to Static(Client). The peer won't add its address
203    /// to other peers` Kademlia routing table. Changing this behaviour implies that a peer can
204    /// provide pieces to others.
205    pub kademlia_mode: KademliaMode,
206    /// Known external addresses to the local peer. The addresses will be added on the swarm start
207    /// and enable peer to notify others about its reachable address.
208    pub external_addresses: Vec<Multiaddr>,
209}
210
211impl fmt::Debug for Config {
212    #[inline]
213    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214        f.debug_struct("Config").finish()
215    }
216}
217
218/// This default can only be used for `dev` networks.
219/// Other networks should use `Config::new()` to apply the correct prefix to the protocol version.
220impl Default for Config {
221    #[inline]
222    fn default() -> Self {
223        let ed25519_keypair = identity::ed25519::Keypair::generate();
224        let keypair = identity::Keypair::from(ed25519_keypair);
225
226        Self::new(DEFAULT_NETWORK_PROTOCOL_VERSION.to_string(), keypair, None)
227    }
228}
229
230impl Config {
231    /// Creates a new [`Config`].
232    /// Applies a subspace-specific version prefix to the `protocol_version`.
233    pub fn new(
234        protocol_version: String,
235        keypair: identity::Keypair,
236        prometheus_registry: Option<&mut Registry>,
237    ) -> Self {
238        let (libp2p_metrics, metrics) = prometheus_registry
239            .map(|registry| {
240                (
241                    Some(Metrics::new(registry)),
242                    Some(SubspaceMetrics::new(registry)),
243                )
244            })
245            .unwrap_or((None, None));
246
247        let mut kademlia = KademliaConfig::new(
248            StreamProtocol::try_from_owned(KADEMLIA_PROTOCOL.to_owned())
249                .expect("Manual protocol name creation."),
250        );
251        kademlia
252            .set_query_timeout(KADEMLIA_QUERY_TIMEOUT)
253            .disjoint_query_paths(true)
254            .set_max_packet_size(2 * Piece::SIZE)
255            .set_kbucket_inserts(BucketInserts::Manual)
256            .set_record_filtering(StoreInserts::FilterBoth)
257            // We don't use records and providers publication.
258            .set_provider_record_ttl(None)
259            .set_provider_publication_interval(None)
260            .set_record_ttl(None)
261            .set_replication_interval(None);
262
263        // NOTE: Do not call deprecated setters like `set_max_num_streams()` on this config.
264        // They silently downgrade from yamux 0.13 to 0.12, which has a remote DoS vulnerability.
265        let yamux_config = YamuxConfig::default();
266
267        let protocol_version = format!("/subspace/2/{protocol_version}");
268        let identify = IdentifyConfig::new(protocol_version.clone(), keypair.public());
269
270        let temporary_ban_backoff = ExponentialBuilder::default()
271            .with_factor(TEMPORARY_BANS_DEFAULT_BACKOFF_MULTIPLIER as f32)
272            .with_min_delay(TEMPORARY_BANS_DEFAULT_BACKOFF_INITIAL_INTERVAL)
273            .with_max_delay(TEMPORARY_BANS_DEFAULT_MAX_INTERVAL)
274            .without_max_times();
275
276        Self {
277            keypair,
278            listen_on: vec![],
279            listen_on_fallback_to_random_port: true,
280            timeout: Duration::from_secs(10),
281            identify,
282            kademlia,
283            allow_non_global_addresses_in_dht: false,
284            initial_random_query_interval: Duration::from_secs(1),
285            known_peers_registry: StubNetworkingParametersManager.boxed(),
286            request_response_protocols: Vec::new(),
287            yamux_config,
288            reserved_peers: Vec::new(),
289            max_established_incoming_connections: SWARM_MAX_ESTABLISHED_INCOMING_CONNECTIONS,
290            max_established_outgoing_connections: SWARM_MAX_ESTABLISHED_OUTGOING_CONNECTIONS,
291            max_pending_incoming_connections: SWARM_MAX_PENDING_INCOMING_CONNECTIONS,
292            max_pending_outgoing_connections: SWARM_MAX_PENDING_OUTGOING_CONNECTIONS,
293            temporary_bans_cache_size: TEMPORARY_BANS_CACHE_SIZE,
294            temporary_ban_backoff,
295            libp2p_metrics,
296            metrics,
297            protocol_version,
298            bootstrap_addresses: Vec::new(),
299            kademlia_mode: KademliaMode::Static(Mode::Client),
300            external_addresses: Vec::new(),
301        }
302    }
303}
304
305/// Errors that might happen during network creation.
306#[derive(Debug, Error)]
307pub enum CreationError {
308    /// Circuit relay client error.
309    #[error("Expected relay server node.")]
310    RelayServerExpected,
311    /// I/O error.
312    #[error("I/O error: {0}")]
313    Io(#[from] io::Error),
314    /// Transport creation error.
315    #[error("Transport creation error: {0}")]
316    // TODO: Restore `#[from] TransportError` once https://github.com/libp2p/rust-libp2p/issues/4824
317    //  is resolved
318    TransportCreationError(Box<dyn std::error::Error + Send + Sync>),
319    /// Transport error when attempting to listen on multiaddr.
320    #[error("Transport error when attempting to listen on multiaddr: {0}")]
321    TransportError(#[from] TransportError<io::Error>),
322}
323
324/// Converts public key from keypair to PeerId.
325/// It serves as the shared PeerId generating algorithm.
326pub fn peer_id(keypair: &identity::Keypair) -> PeerId {
327    keypair.public().to_peer_id()
328}
329
330/// Create a new network node and node runner instances.
331pub fn construct(config: Config) -> Result<(Node, NodeRunner), CreationError> {
332    let Config {
333        keypair,
334        listen_on,
335        listen_on_fallback_to_random_port,
336        timeout,
337        identify,
338        kademlia,
339        yamux_config,
340        allow_non_global_addresses_in_dht,
341        initial_random_query_interval,
342        known_peers_registry,
343        request_response_protocols,
344        reserved_peers,
345        max_established_incoming_connections,
346        max_established_outgoing_connections,
347        max_pending_incoming_connections,
348        max_pending_outgoing_connections,
349        temporary_bans_cache_size,
350        temporary_ban_backoff,
351        libp2p_metrics,
352        metrics,
353        protocol_version,
354        bootstrap_addresses,
355        kademlia_mode,
356        external_addresses,
357    } = config;
358    let local_peer_id = peer_id(&keypair);
359
360    info!(
361        %allow_non_global_addresses_in_dht,
362        peer_id = %local_peer_id,
363        %protocol_version,
364        "DSN instance configured."
365    );
366
367    let connection_limits = ConnectionLimits::default()
368        .with_max_established_per_peer(Some(SWARM_MAX_ESTABLISHED_CONNECTIONS_PER_PEER))
369        .with_max_pending_incoming(Some(max_pending_incoming_connections))
370        .with_max_pending_outgoing(Some(max_pending_outgoing_connections))
371        .with_max_established_incoming(Some(max_established_incoming_connections))
372        .with_max_established_outgoing(Some(max_established_outgoing_connections));
373
374    debug!(?connection_limits, "DSN connection limits set.");
375
376    let autonat_boot_delay = if kademlia_mode.is_static() || !external_addresses.is_empty() {
377        AUTONAT_SERVER_PROBE_DELAY
378    } else {
379        AutonatConfig::default().boot_delay
380    };
381
382    debug!(
383        ?autonat_boot_delay,
384        ?kademlia_mode,
385        ?external_addresses,
386        "Autonat boot delay set."
387    );
388
389    let mut behaviour = Behavior::new(BehaviorConfig {
390        peer_id: local_peer_id,
391        identify,
392        kademlia,
393        request_response_protocols,
394        request_response_max_concurrent_streams: {
395            let max_num_connections = max_established_incoming_connections as usize
396                + max_established_outgoing_connections as usize;
397            max_num_connections * MAX_CONCURRENT_STREAMS_PER_CONNECTION
398        },
399        connection_limits,
400        reserved_peers: ReservedPeersConfig {
401            reserved_peers: reserved_peers.clone(),
402            dialing_interval: DIALING_INTERVAL_IN_SECS,
403        },
404        autonat: AutonatWrapperConfig {
405            inner_config: AutonatConfig {
406                use_connected: true,
407                only_global_ips: !config.allow_non_global_addresses_in_dht,
408                confidence_max: AUTONAT_MAX_CONFIDENCE,
409                boot_delay: autonat_boot_delay,
410                ..Default::default()
411            },
412            local_peer_id,
413            servers: bootstrap_addresses.clone(),
414        },
415    });
416
417    match (kademlia_mode, external_addresses.is_empty()) {
418        (KademliaMode::Static(mode), _) => {
419            behaviour.kademlia.set_mode(Some(mode));
420        }
421        (KademliaMode::Dynamic, false) => {
422            behaviour.kademlia.set_mode(Some(Mode::Server));
423        }
424        _ => {
425            // Autonat will figure it out
426        }
427    };
428
429    let temporary_bans = Arc::new(Mutex::new(TemporaryBans::new(
430        temporary_bans_cache_size,
431        temporary_ban_backoff,
432    )));
433
434    let mut swarm = SwarmBuilder::with_existing_identity(keypair)
435        .with_tokio()
436        .with_other_transport(|keypair| {
437            Ok(build_transport(
438                allow_non_global_addresses_in_dht,
439                keypair,
440                Arc::clone(&temporary_bans),
441                timeout,
442                yamux_config,
443            )?)
444        })
445        .map_err(|error| CreationError::TransportCreationError(error.into()))?
446        .with_behaviour(move |_keypair| Ok(behaviour))
447        .expect("Not fallible; qed")
448        .with_swarm_config(|config| {
449            config
450                .with_max_negotiating_inbound_streams(SWARM_MAX_NEGOTIATING_INBOUND_STREAMS)
451                .with_idle_connection_timeout(IDLE_CONNECTION_TIMEOUT)
452        })
453        .build();
454
455    let is_listening = !listen_on.is_empty();
456
457    // Setup listen_on addresses
458    for mut addr in listen_on {
459        if let Err(error) = swarm.listen_on(addr.clone()) {
460            if !listen_on_fallback_to_random_port {
461                return Err(error.into());
462            }
463
464            let addr_string = addr.to_string();
465            // Listen on random port if specified is already occupied
466            if let Some(Protocol::Tcp(_port)) = addr.pop() {
467                info!("Failed to listen on {addr_string} ({error}), falling back to random port");
468                addr.push(Protocol::Tcp(0));
469                swarm.listen_on(addr)?;
470            }
471        }
472    }
473
474    // Setup external addresses
475    for addr in external_addresses.iter().cloned() {
476        info!("DSN external address added: {addr}");
477        swarm.add_external_address(addr);
478    }
479
480    // Create final structs
481    let (command_sender, command_receiver) = mpsc::channel(1);
482
483    let rate_limiter = RateLimiter::new(
484        max_established_outgoing_connections,
485        max_pending_outgoing_connections,
486    );
487
488    let shared = Arc::new(Shared::new(local_peer_id, command_sender, rate_limiter));
489    let shared_weak = Arc::downgrade(&shared);
490
491    let node = Node::new(shared);
492    let node_runner = NodeRunner::new(NodeRunnerConfig {
493        allow_non_global_addresses_in_dht,
494        is_listening,
495        command_receiver,
496        swarm,
497        shared_weak,
498        next_random_query_interval: initial_random_query_interval,
499        known_peers_registry,
500        reserved_peers: strip_peer_id(reserved_peers).into_iter().collect(),
501        temporary_bans,
502        libp2p_metrics,
503        metrics,
504        protocol_version,
505        bootstrap_addresses,
506    });
507
508    Ok((node, node_runner))
509}