Skip to content

Commit

Permalink
Merge pull request #1713 from eqlabs/sistemd/refactor-p2p-config
Browse files Browse the repository at this point in the history
refactor: more logical `Config` struct for `p2p`
  • Loading branch information
sistemd authored Jan 31, 2024
2 parents 0c8949f + 9688e0e commit 2306dbf
Show file tree
Hide file tree
Showing 6 changed files with 93 additions and 160 deletions.
22 changes: 11 additions & 11 deletions crates/p2p/src/behaviour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::time::Duration;

use crate::recent_peers::RecentPeers;
use crate::sync::codec;
use crate::LimitsConfig;
use crate::Config;
use anyhow::anyhow;
use libp2p::core::Endpoint;
use libp2p::dcutr;
Expand Down Expand Up @@ -39,7 +39,7 @@ pub fn kademlia_protocol_name(chain_id: ChainId) -> String {
}

pub struct Behaviour {
limits: LimitsConfig,
cfg: Config,
/// Recent peers that have connected to us directly (not over a relay).
///
/// The distinction is important because different limits apply to direct and relayed peers.
Expand Down Expand Up @@ -91,15 +91,15 @@ impl NetworkBehaviour for Behaviour {
// Limit the number of inbound peer connections. Different limits apply to direct peers
// and peers connecting over a relay.
if is_relay {
if self.inbound_relay_peers >= self.limits.max_inbound_relay_peers {
if self.inbound_relay_peers >= self.cfg.max_inbound_relay_peers {
tracing::debug!(%connection_id, "Too many inbound relay peers, closing");
return Err(ConnectionDenied::new(anyhow!(
"too many inbound relay peers"
)));
}
self.inbound_relay_peers += 1;
} else {
if self.inbound_direct_peers >= self.limits.max_inbound_direct_peers {
if self.inbound_direct_peers >= self.cfg.max_inbound_direct_peers {
tracing::debug!(%connection_id, "Too many inbound direct peers, closing");
return Err(ConnectionDenied::new(anyhow!(
"too many inbound direct peers"
Expand Down Expand Up @@ -184,7 +184,7 @@ impl NetworkBehaviour for Behaviour {

// If the peer is not in the IP whitelist, disconnect.
if !self
.limits
.cfg
.ip_whitelist
.iter()
.any(|net| net.contains(&peer_ip))
Expand Down Expand Up @@ -225,13 +225,13 @@ impl NetworkBehaviour for Behaviour {
// The check must be repeated when the connection is established due to race conditions,
// since multiple peers may be attempting to connect at the same time.
if is_relay {
if self.inbound_relay_peers >= self.limits.max_inbound_relay_peers {
if self.inbound_relay_peers >= self.cfg.max_inbound_relay_peers {
tracing::debug!(%connection_id, "Too many inbound relay peers, closing");
return Err(ConnectionDenied::new(anyhow!(
"too many inbound relay peers"
)));
}
} else if self.inbound_direct_peers >= self.limits.max_inbound_direct_peers {
} else if self.inbound_direct_peers >= self.cfg.max_inbound_direct_peers {
tracing::debug!(%connection_id, "Too many inbound direct peers, closing");
return Err(ConnectionDenied::new(anyhow!(
"too many inbound direct peers"
Expand Down Expand Up @@ -262,7 +262,7 @@ impl Behaviour {
pub fn new(
identity: &identity::Keypair,
chain_id: ChainId,
limits: LimitsConfig,
cfg: Config,
) -> (Self, relay::client::Transport) {
const PROVIDER_PUBLICATION_INTERVAL: Duration = Duration::from_secs(600);

Expand Down Expand Up @@ -309,11 +309,11 @@ impl Behaviour {

(
Self {
recent_inbound_direct_peers: RecentPeers::new(limits.direct_connection_timeout),
recent_inbound_relay_peers: RecentPeers::new(limits.relay_connection_timeout),
recent_inbound_direct_peers: RecentPeers::new(cfg.direct_connection_timeout),
recent_inbound_relay_peers: RecentPeers::new(cfg.relay_connection_timeout),
inbound_direct_peers: Default::default(),
inbound_relay_peers: Default::default(),
limits,
cfg,
connected_peers: Default::default(),
inner: Inner {
relay,
Expand Down
43 changes: 17 additions & 26 deletions crates/p2p/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use ipnet::IpNet;
use libp2p::gossipsub::IdentTopic;
use libp2p::identity::Keypair;
use libp2p::kad::RecordKey;
use libp2p::swarm::Config;
use libp2p::swarm;
use libp2p::{Multiaddr, PeerId, Swarm};
use p2p_proto::block::{
BlockBodiesRequest, BlockBodiesResponse, BlockHeadersRequest, BlockHeadersResponse, NewBlock,
Expand Down Expand Up @@ -45,13 +45,12 @@ pub use behaviour::{kademlia_protocol_name, IDENTIFY_PROTOCOL_NAME};
pub fn new(
keypair: Keypair,
peers: Arc<RwLock<peers::Peers>>,
periodic_cfg: PeriodicTaskConfig,
limits_cfg: LimitsConfig,
cfg: Config,
chain_id: ChainId,
) -> (Client, EventReceiver, MainLoop) {
let local_peer_id = keypair.public().to_peer_id();

let (behaviour, relay_transport) = behaviour::Behaviour::new(&keypair, chain_id, limits_cfg);
let (behaviour, relay_transport) = behaviour::Behaviour::new(&keypair, chain_id, cfg.clone());

let swarm = Swarm::new(
transport::create(&keypair, relay_transport),
Expand All @@ -66,7 +65,7 @@ pub fn new(
// 2. I'm not sure if we really need keep alive, as connections should be closed when not used
// because they consume resources, and in general we should be managing connections in a wiser manner,
// the deprecated `libp2p::swarm::keep_alive::Behaviour` was supposed to be mostly used for testing anyway.
Config::with_tokio_executor().with_idle_connection_timeout(Duration::MAX),
swarm::Config::with_tokio_executor().with_idle_connection_timeout(Duration::MAX),
);

let (command_sender, command_receiver) = mpsc::channel(1);
Expand All @@ -75,25 +74,13 @@ pub fn new(
(
Client::new(command_sender, local_peer_id),
event_receiver,
MainLoop::new(
swarm,
command_receiver,
event_sender,
peers,
periodic_cfg,
chain_id,
),
MainLoop::new(swarm, command_receiver, event_sender, peers, cfg, chain_id),
)
}

#[derive(Copy, Clone, Debug)]
pub struct PeriodicTaskConfig {
pub bootstrap: BootstrapConfig,
}

/// P2P limitations.
#[derive(Debug, Clone)]
pub struct LimitsConfig {
pub struct Config {
/// A direct (not relayed) peer can only connect once in this period.
pub direct_connection_timeout: Duration,
/// A relayed peer can only connect once in this period.
Expand All @@ -103,16 +90,22 @@ pub struct LimitsConfig {
/// Maximum number of relayed peers.
pub max_inbound_relay_peers: usize,
pub ip_whitelist: Vec<IpNet>,
pub bootstrap: BootstrapConfig,
}

impl LimitsConfig {
pub fn new(max_inbound_direct_peers: usize, max_inbound_relay_peers: usize) -> Self {
impl Config {
pub fn new(
max_inbound_direct_peers: usize,
max_inbound_relay_peers: usize,
bootstrap: BootstrapConfig,
) -> Self {
Self {
direct_connection_timeout: Duration::from_secs(30),
relay_connection_timeout: Duration::from_secs(10),
max_inbound_direct_peers,
max_inbound_relay_peers,
ip_whitelist: vec!["::/0".parse().unwrap(), "0.0.0.0/0".parse().unwrap()],
bootstrap,
}
}
}
Expand All @@ -123,13 +116,11 @@ pub struct BootstrapConfig {
pub period: Duration,
}

impl Default for PeriodicTaskConfig {
impl Default for BootstrapConfig {
fn default() -> Self {
Self {
bootstrap: BootstrapConfig {
start_offset: Duration::from_secs(5),
period: Duration::from_secs(10 * 60),
},
start_offset: Duration::from_secs(5),
period: Duration::from_secs(10 * 60),
}
}
}
Expand Down
9 changes: 4 additions & 5 deletions crates/p2p/src/main_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,8 @@ use crate::behaviour;
use crate::peers;
#[cfg(test)]
use crate::test_utils;
use crate::{
BootstrapConfig, Command, EmptyResultSender, Event, PeriodicTaskConfig, TestCommand, TestEvent,
};
use crate::Config;
use crate::{BootstrapConfig, Command, EmptyResultSender, Event, TestCommand, TestEvent};

pub struct MainLoop {
bootstrap_cfg: BootstrapConfig,
Expand Down Expand Up @@ -80,11 +79,11 @@ impl MainLoop {
command_receiver: mpsc::Receiver<Command>,
event_sender: mpsc::Sender<Event>,
peers: Arc<RwLock<peers::Peers>>,
periodic_cfg: PeriodicTaskConfig,
cfg: Config,
chain_id: ChainId,
) -> Self {
Self {
bootstrap_cfg: periodic_cfg.bootstrap,
bootstrap_cfg: cfg.bootstrap,
swarm,
command_receiver,
event_sender,
Expand Down
Loading

0 comments on commit 2306dbf

Please sign in to comment.