Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor for removing Discv5 prefix #206

Merged
merged 2 commits into from
Jul 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ Status]][Crates Link]
This is a rust implementation of the [Discovery v5](https:/ethereum/devp2p/blob/master/discv5/discv5.md)
peer discovery protocol.

Discovery v5 is a protocol designed for encrypted peer discovery (and topic advertisement tba). Each peer/node
on the network is identified via it's `ENR` ([Ethereum Node
Record](https://eips.ethereum.org/EIPS/eip-778)), which is essentially a signed key-value store
containing the node's public key and optionally IP address and port.
Discovery v5 is a protocol designed for encrypted peer discovery. Each peer/node on the network is
identified via it's `ENR` ([Ethereum Node Record](https://eips.ethereum.org/EIPS/eip-778)), which
is essentially a signed key-value store containing the node's public key and optionally IP address
and port.

Discv5 employs a kademlia-like routing table to store and manage discovered peers and topics. The
protocol allows for external IP discovery in NAT environments through regular PING/PONG's with
Expand All @@ -37,7 +37,7 @@ For a simple CLI discovery service see [discv5-cli](https:/AgeMannin
A simple example of creating this service is as follows:

```rust
use discv5::{enr, enr::{CombinedKey, NodeId}, TokioExecutor, Discv5, Discv5ConfigBuilder};
use discv5::{enr, enr::{CombinedKey, NodeId}, TokioExecutor, Discv5, ConfigBuilder};
use discv5::socket::ListenConfig;
use std::net::SocketAddr;

Expand All @@ -59,7 +59,7 @@ A simple example of creating this service is as follows:
};

// default configuration
let config = Discv5ConfigBuilder::new(listen_config).build();
let config = ConfigBuilder::new(listen_config).build();

// construct the discv5 server
let mut discv5: Discv5 = Discv5::new(enr, enr_key, config).unwrap();
Expand Down
8 changes: 4 additions & 4 deletions examples/custom_executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
//! $ cargo run --example custom_executor <BASE64ENR>
//! ```

use discv5::{enr, enr::CombinedKey, Discv5, Discv5ConfigBuilder, Discv5Event, ListenConfig};
use discv5::{enr, enr::CombinedKey, ConfigBuilder, Discv5, Event, ListenConfig};
use std::net::Ipv4Addr;

fn main() {
Expand Down Expand Up @@ -39,7 +39,7 @@ fn main() {
.unwrap();

// default configuration - uses the current executor
let config = Discv5ConfigBuilder::new(listen_config).build();
let config = ConfigBuilder::new(listen_config).build();

// construct the discv5 server
let mut discv5: Discv5 = Discv5::new(enr, enr_key, config).unwrap();
Expand Down Expand Up @@ -72,10 +72,10 @@ fn main() {

loop {
match event_stream.recv().await {
Some(Discv5Event::SocketUpdated(addr)) => {
Some(Event::SocketUpdated(addr)) => {
println!("Nodes ENR socket address has been updated to: {addr:?}");
}
Some(Discv5Event::Discovered(enr)) => {
Some(Event::Discovered(enr)) => {
println!("A peer has been discovered: {}", enr.node_id());
}
_ => {}
Expand Down
18 changes: 9 additions & 9 deletions examples/find_nodes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use clap::Parser;
use discv5::{
enr,
enr::{k256, CombinedKey},
Discv5, Discv5ConfigBuilder, Discv5Event, ListenConfig,
ConfigBuilder, Discv5, Event, ListenConfig,
};
use std::{
net::{IpAddr, Ipv4Addr, Ipv6Addr},
Expand Down Expand Up @@ -120,10 +120,10 @@ async fn main() {
};

// default configuration with packet filtering
// let config = Discv5ConfigBuilder::new(listen_config).enable_packet_filter().build();
// let config = ConfigBuilder::new(listen_config).enable_packet_filter().build();

// default configuration without packet filtering
let config = Discv5ConfigBuilder::new(listen_config).build();
let config = ConfigBuilder::new(listen_config).build();

info!("Node Id: {}", enr.node_id());
if args.enr_ip6.is_some() || args.enr_ip4.is_some() {
Expand Down Expand Up @@ -192,12 +192,12 @@ async fn main() {
continue;
}
match discv5_ev {
Discv5Event::Discovered(enr) => info!("Enr discovered {}", enr),
Discv5Event::EnrAdded { enr, replaced: _ } => info!("Enr added {}", enr),
Discv5Event::NodeInserted { node_id, replaced: _ } => info!("Node inserted {}", node_id),
Discv5Event::SessionEstablished(enr, _) => info!("Session established {}", enr),
Discv5Event::SocketUpdated(addr) => info!("Socket updated {}", addr),
Discv5Event::TalkRequest(_) => info!("Talk request received"),
Event::Discovered(enr) => info!("Enr discovered {}", enr),
Event::EnrAdded { enr, replaced: _ } => info!("Enr added {}", enr),
Event::NodeInserted { node_id, replaced: _ } => info!("Node inserted {}", node_id),
Event::SessionEstablished(enr, _) => info!("Session established {}", enr),
Event::SocketUpdated(addr) => info!("Socket updated {}", addr),
Event::TalkRequest(_) => info!("Talk request received"),
};
}
}
Expand Down
4 changes: 2 additions & 2 deletions examples/request_enr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
//!
//! This requires the "libp2p" feature.
#[cfg(feature = "libp2p")]
use discv5::Discv5ConfigBuilder;
use discv5::ConfigBuilder;
#[cfg(feature = "libp2p")]
use discv5::ListenConfig;
#[cfg(feature = "libp2p")]
Expand Down Expand Up @@ -46,7 +46,7 @@ async fn main() {
let enr = enr::EnrBuilder::new("v4").build(&enr_key).unwrap();

// default discv5 configuration
let config = Discv5ConfigBuilder::new(listen_config).build();
let config = ConfigBuilder::new(listen_config).build();

let multiaddr = std::env::args()
.nth(1)
Expand Down
8 changes: 4 additions & 4 deletions examples/simple_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
//! $ cargo run --example simple_server -- <ENR-IP> <ENR-PORT> <BASE64ENR>
//! ```

use discv5::{enr, enr::CombinedKey, Discv5, Discv5ConfigBuilder, Discv5Event, ListenConfig};
use discv5::{enr, enr::CombinedKey, ConfigBuilder, Discv5, Event, ListenConfig};
use std::net::Ipv4Addr;

#[tokio::main]
Expand Down Expand Up @@ -72,7 +72,7 @@ async fn main() {
}

// default configuration
let config = Discv5ConfigBuilder::new(listen_config).build();
let config = ConfigBuilder::new(listen_config).build();

// construct the discv5 server
let mut discv5: Discv5 = Discv5::new(enr, enr_key, config).unwrap();
Expand Down Expand Up @@ -104,10 +104,10 @@ async fn main() {

loop {
match event_stream.recv().await {
Some(Discv5Event::SocketUpdated(addr)) => {
Some(Event::SocketUpdated(addr)) => {
println!("Nodes ENR socket address has been updated to: {addr:?}");
}
Some(Discv5Event::Discovered(enr)) => {
Some(Event::Discovered(enr)) => {
println!("A peer has been discovered: {}", enr.node_id());
}
_ => {}
Expand Down
18 changes: 9 additions & 9 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::time::Duration;

/// Configuration parameters that define the performance of the discovery network.
#[derive(Clone)]
pub struct Discv5Config {
pub struct Config {
/// Whether to enable the incoming packet filter. Default: false.
pub enable_packet_filter: bool,

Expand Down Expand Up @@ -101,11 +101,11 @@ pub struct Discv5Config {
}

#[derive(Debug)]
pub struct Discv5ConfigBuilder {
config: Discv5Config,
pub struct ConfigBuilder {
config: Config,
}

impl Discv5ConfigBuilder {
impl ConfigBuilder {
pub fn new(listen_config: ListenConfig) -> Self {
// This is only applicable if enable_packet_filter is set.
let filter_rate_limiter = Some(
Expand All @@ -118,7 +118,7 @@ impl Discv5ConfigBuilder {
);

// set default values
let config = Discv5Config {
let config = Config {
enable_packet_filter: false,
request_timeout: Duration::from_secs(1),
vote_duration: Duration::from_secs(30),
Expand All @@ -145,7 +145,7 @@ impl Discv5ConfigBuilder {
listen_config,
};

Discv5ConfigBuilder { config }
ConfigBuilder { config }
}

/// Whether to enable the incoming packet filter.
Expand Down Expand Up @@ -302,7 +302,7 @@ impl Discv5ConfigBuilder {
self
}

pub fn build(&mut self) -> Discv5Config {
pub fn build(&mut self) -> Config {
// If an executor is not provided, assume a current tokio runtime is running.
if self.config.executor.is_none() {
self.config.executor = Some(Box::<crate::executor::TokioExecutor>::default());
Expand All @@ -314,9 +314,9 @@ impl Discv5ConfigBuilder {
}
}

impl std::fmt::Debug for Discv5Config {
impl std::fmt::Debug for Config {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Discv5Config")
f.debug_struct("Config")
.field("filter_enabled", &self.enable_packet_filter)
.field("request_timeout", &self.request_timeout)
.field("vote_duration", &self.vote_duration)
Expand Down
32 changes: 15 additions & 17 deletions src/discv5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
//!
//! This provides the main struct for running and interfacing with a discovery v5 server.
//!
//! A [`Discv5`] struct needs to be created either with an [`crate::executor::Executor`] specified in the
//! [`Discv5Config`] via the [`crate::Discv5ConfigBuilder`] or in the presence of a tokio runtime that has
//! timing and io enabled.
//! A [`Discv5`] struct needs to be created either with an [`crate::executor::Executor`] specified
//! in the [`Config`] via the [`crate::ConfigBuilder`] or in the presence of a tokio runtime that
//! has timing and io enabled.
//!
//! Once a [`Discv5`] struct has been created the service is started by running the [`Discv5::start`]
//! functions with a UDP socket. This will start a discv5 server in the background listening on the
Expand All @@ -13,15 +13,15 @@
//! The server can be shutdown using the [`Discv5::shutdown`] function.

use crate::{
error::{Discv5Error, QueryError, RequestError},
error::{Error, QueryError, RequestError},
kbucket::{
self, ConnectionDirection, ConnectionState, FailureReason, InsertResult, KBucketsTable,
NodeStatus, UpdateResult,
},
node_info::NodeContact,
packet::ProtocolIdentity,
service::{QueryKind, Service, ServiceRequest, TalkRequest},
DefaultProtocolId, Discv5Config, Enr, IpMode,
Config, DefaultProtocolId, Enr, IpMode,
};
use enr::{CombinedKey, EnrError, EnrKey, NodeId};
use parking_lot::RwLock;
Expand Down Expand Up @@ -53,7 +53,7 @@ mod test;

/// Events that can be produced by the `Discv5` event stream.
#[derive(Debug)]
pub enum Discv5Event {
pub enum Event {
/// A node has been discovered from a FINDNODES request.
///
/// The ENR of the node is returned. Various properties can be derived from the ENR.
Expand Down Expand Up @@ -81,7 +81,7 @@ pub struct Discv5<P = DefaultProtocolId>
where
P: ProtocolIdentity,
{
config: Discv5Config,
config: Config,
/// The channel to make requests from the main service.
service_channel: Option<mpsc::Sender<ServiceRequest>>,
/// The exit channel to shutdown the underlying service.
Expand All @@ -102,7 +102,7 @@ impl<P: ProtocolIdentity> Discv5<P> {
pub fn new(
local_enr: Enr,
enr_key: CombinedKey,
mut config: Discv5Config,
mut config: Config,
) -> Result<Self, &'static str> {
// ensure the keypair matches the one that signed the enr.
if local_enr.public_key() != enr_key.public() {
Expand Down Expand Up @@ -154,10 +154,10 @@ impl<P: ProtocolIdentity> Discv5<P> {
}

/// Starts the required tasks and begins listening on a given UDP SocketAddr.
pub async fn start(&mut self) -> Result<(), Discv5Error> {
pub async fn start(&mut self) -> Result<(), Error> {
if self.service_channel.is_some() {
warn!("Service is already started");
return Err(Discv5Error::ServiceAlreadyStarted);
return Err(Error::ServiceAlreadyStarted);
}

// create the main service
Expand Down Expand Up @@ -670,7 +670,7 @@ impl<P: ProtocolIdentity> Discv5<P> {
/// Creates an event stream channel which can be polled to receive Discv5 events.
pub fn event_stream(
&self,
) -> impl Future<Output = Result<mpsc::Receiver<Discv5Event>, Discv5Error>> + 'static {
) -> impl Future<Output = Result<mpsc::Receiver<Event>, Error>> + 'static {
let channel = self.clone_channel();

async move {
Expand All @@ -682,20 +682,18 @@ impl<P: ProtocolIdentity> Discv5<P> {
channel
.send(event)
.await
.map_err(|_| Discv5Error::ServiceChannelClosed)?;
.map_err(|_| Error::ServiceChannelClosed)?;

callback_recv
.await
.map_err(|_| Discv5Error::ServiceChannelClosed)
callback_recv.await.map_err(|_| Error::ServiceChannelClosed)
}
}

/// Internal helper function to send events to the Service.
fn clone_channel(&self) -> Result<mpsc::Sender<ServiceRequest>, Discv5Error> {
fn clone_channel(&self) -> Result<mpsc::Sender<ServiceRequest>, Error> {
if let Some(channel) = self.service_channel.as_ref() {
Ok(channel.clone())
} else {
Err(Discv5Error::ServiceNotStarted)
Err(Error::ServiceNotStarted)
}
}
}
Expand Down
12 changes: 6 additions & 6 deletions src/discv5/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async fn build_nodes(n: usize, base_port: u16) -> Vec<Discv5> {
for port in base_port..base_port + n as u16 {
let enr_key = CombinedKey::generate_secp256k1();
let listen_config = ListenConfig::Ipv4 { ip, port };
let config = Discv5ConfigBuilder::new(listen_config).build();
let config = ConfigBuilder::new(listen_config).build();

let enr = EnrBuilder::new("v4")
.ip4(ip)
Expand All @@ -50,7 +50,7 @@ async fn build_nodes_from_keypairs(keys: Vec<CombinedKey>, base_port: u16) -> Ve
let port = base_port + i as u16;

let listen_config = ListenConfig::Ipv4 { ip, port };
let config = Discv5ConfigBuilder::new(listen_config).build();
let config = ConfigBuilder::new(listen_config).build();

let enr = EnrBuilder::new("v4")
.ip4(ip)
Expand All @@ -75,7 +75,7 @@ async fn build_nodes_from_keypairs_ipv6(keys: Vec<CombinedKey>, base_port: u16)
ip: Ipv6Addr::LOCALHOST,
port,
};
let config = Discv5ConfigBuilder::new(listen_config).build();
let config = ConfigBuilder::new(listen_config).build();

let enr = EnrBuilder::new("v4")
.ip6(Ipv6Addr::LOCALHOST)
Expand Down Expand Up @@ -106,7 +106,7 @@ async fn build_nodes_from_keypairs_dual_stack(
ipv6: Ipv6Addr::LOCALHOST,
ipv6_port,
};
let config = Discv5ConfigBuilder::new(listen_config).build();
let config = ConfigBuilder::new(listen_config).build();

let enr = EnrBuilder::new("v4")
.ip4(Ipv4Addr::LOCALHOST)
Expand Down Expand Up @@ -753,7 +753,7 @@ async fn test_table_limits() {
ip: enr.ip4().unwrap(),
port: enr.udp4().unwrap(),
};
let config = Discv5ConfigBuilder::new(listen_config).ip_limit().build();
let config = ConfigBuilder::new(listen_config).ip_limit().build();

// let socket_addr = enr.udp_socket().unwrap();
let discv5: Discv5 = Discv5::new(enr, enr_key, config).unwrap();
Expand Down Expand Up @@ -822,7 +822,7 @@ async fn test_bucket_limits() {
ip: enr.ip4().unwrap(),
port: enr.udp4().unwrap(),
};
let config = Discv5ConfigBuilder::new(listen_config).ip_limit().build();
let config = ConfigBuilder::new(listen_config).ip_limit().build();

let discv5: Discv5 = Discv5::new(enr, enr_key, config).unwrap();
for enr in enrs {
Expand Down
Loading