Skip to main content

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