diff --git a/README.md b/README.md index c87f42577..c9ca44d23 100644 --- a/README.md +++ b/README.md @@ -19,10 +19,10 @@ Status]][Crates Link] This is a rust implementation of the [Discovery v5](https://github.com/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 @@ -37,7 +37,7 @@ For a simple CLI discovery service see [discv5-cli](https://github.com/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; @@ -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(); diff --git a/examples/custom_executor.rs b/examples/custom_executor.rs index 9ac0df7c4..1d97d3561 100644 --- a/examples/custom_executor.rs +++ b/examples/custom_executor.rs @@ -9,7 +9,7 @@ //! $ cargo run --example custom_executor //! ``` -use discv5::{enr, enr::CombinedKey, Discv5, Discv5ConfigBuilder, Discv5Event, ListenConfig}; +use discv5::{enr, enr::CombinedKey, ConfigBuilder, Discv5, Event, ListenConfig}; use std::net::Ipv4Addr; fn main() { @@ -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(); @@ -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()); } _ => {} diff --git a/examples/find_nodes.rs b/examples/find_nodes.rs index f52d8364f..383d141e8 100644 --- a/examples/find_nodes.rs +++ b/examples/find_nodes.rs @@ -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}, @@ -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() { @@ -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"), }; } } diff --git a/examples/request_enr.rs b/examples/request_enr.rs index 1fa780ba5..e6986f1b3 100644 --- a/examples/request_enr.rs +++ b/examples/request_enr.rs @@ -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")] @@ -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) diff --git a/examples/simple_server.rs b/examples/simple_server.rs index c4b2509b8..41a925e57 100644 --- a/examples/simple_server.rs +++ b/examples/simple_server.rs @@ -10,7 +10,7 @@ //! $ cargo run --example simple_server -- //! ``` -use discv5::{enr, enr::CombinedKey, Discv5, Discv5ConfigBuilder, Discv5Event, ListenConfig}; +use discv5::{enr, enr::CombinedKey, ConfigBuilder, Discv5, Event, ListenConfig}; use std::net::Ipv4Addr; #[tokio::main] @@ -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(); @@ -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()); } _ => {} diff --git a/src/config.rs b/src/config.rs index 3d4153229..b1ccc8762 100644 --- a/src/config.rs +++ b/src/config.rs @@ -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, @@ -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( @@ -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), @@ -145,7 +145,7 @@ impl Discv5ConfigBuilder { listen_config, }; - Discv5ConfigBuilder { config } + ConfigBuilder { config } } /// Whether to enable the incoming packet filter. @@ -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::::default()); @@ -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) diff --git a/src/discv5.rs b/src/discv5.rs index f813e8a42..1fe10e92b 100644 --- a/src/discv5.rs +++ b/src/discv5.rs @@ -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 @@ -13,7 +13,7 @@ //! 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, @@ -21,7 +21,7 @@ use crate::{ 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; @@ -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. @@ -81,7 +81,7 @@ pub struct Discv5

where P: ProtocolIdentity, { - config: Discv5Config, + config: Config, /// The channel to make requests from the main service. service_channel: Option>, /// The exit channel to shutdown the underlying service. @@ -102,7 +102,7 @@ impl Discv5

{ pub fn new( local_enr: Enr, enr_key: CombinedKey, - mut config: Discv5Config, + mut config: Config, ) -> Result { // ensure the keypair matches the one that signed the enr. if local_enr.public_key() != enr_key.public() { @@ -154,10 +154,10 @@ impl Discv5

{ } /// 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 @@ -670,7 +670,7 @@ impl Discv5

{ /// Creates an event stream channel which can be polled to receive Discv5 events. pub fn event_stream( &self, - ) -> impl Future, Discv5Error>> + 'static { + ) -> impl Future, Error>> + 'static { let channel = self.clone_channel(); async move { @@ -682,20 +682,18 @@ impl Discv5

{ 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, Discv5Error> { + fn clone_channel(&self) -> Result, Error> { if let Some(channel) = self.service_channel.as_ref() { Ok(channel.clone()) } else { - Err(Discv5Error::ServiceNotStarted) + Err(Error::ServiceNotStarted) } } } diff --git a/src/discv5/test.rs b/src/discv5/test.rs index bb627ff7f..07d3a9c47 100644 --- a/src/discv5/test.rs +++ b/src/discv5/test.rs @@ -26,7 +26,7 @@ async fn build_nodes(n: usize, base_port: u16) -> Vec { 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) @@ -50,7 +50,7 @@ async fn build_nodes_from_keypairs(keys: Vec, 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) @@ -75,7 +75,7 @@ async fn build_nodes_from_keypairs_ipv6(keys: Vec, 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) @@ -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) @@ -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(); @@ -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 { diff --git a/src/error.rs b/src/error.rs index d35ba90d4..35b2b4768 100644 --- a/src/error.rs +++ b/src/error.rs @@ -4,7 +4,7 @@ use std::fmt; #[derive(Debug)] /// A general error that is used throughout the Discv5 library. -pub enum Discv5Error { +pub enum Error { /// An invalid ENR was received. InvalidEnr, /// The public key type is known. @@ -41,9 +41,9 @@ pub enum Discv5Error { Io(std::io::Error), } -impl From for Discv5Error { - fn from(err: std::io::Error) -> Discv5Error { - Discv5Error::Io(err) +impl From for Error { + fn from(err: std::io::Error) -> Error { + Error::Io(err) } } @@ -127,7 +127,7 @@ pub enum QueryError { InvalidMultiaddr(String), } -impl fmt::Display for Discv5Error { +impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{self:?}") } diff --git a/src/handler/crypto/mod.rs b/src/handler/crypto/mod.rs index 2bda3b0f7..c96d7afdc 100644 --- a/src/handler/crypto/mod.rs +++ b/src/handler/crypto/mod.rs @@ -6,7 +6,7 @@ //! encryption and key-derivation algorithms. Future versions may abstract some of these to allow //! for different algorithms. use crate::{ - error::Discv5Error, + error::Error, node_info::NodeContact, packet::{ChallengeData, MessageNonce}, }; @@ -48,7 +48,7 @@ pub(crate) fn generate_session_keys( local_id: &NodeId, contact: &NodeContact, challenge_data: &ChallengeData, -) -> Result<(Key, Key, Vec), Discv5Error> { +) -> Result<(Key, Key, Vec), Error> { let (secret, ephem_pk) = { match contact.public_key() { CombinedPublicKey::Secp256k1(remote_pk) => { @@ -57,9 +57,7 @@ pub(crate) fn generate_session_keys( let ephem_pk = ephem_sk.verifying_key(); (secret, ephem_pk.to_sec1_bytes().to_vec()) } - CombinedPublicKey::Ed25519(_) => { - return Err(Discv5Error::KeyTypeNotSupported("Ed25519")) - } + CombinedPublicKey::Ed25519(_) => return Err(Error::KeyTypeNotSupported("Ed25519")), } }; @@ -74,7 +72,7 @@ fn derive_key( first_id: &NodeId, second_id: &NodeId, challenge_data: &ChallengeData, -) -> Result<(Key, Key), Discv5Error> { +) -> Result<(Key, Key), Error> { let mut info = [0u8; INFO_LENGTH]; info[0..26].copy_from_slice(KEY_AGREEMENT_STRING.as_bytes()); info[26..26 + NODE_ID_LENGTH].copy_from_slice(&first_id.raw()); @@ -84,7 +82,7 @@ fn derive_key( let mut okm = [0u8; 2 * KEY_LENGTH]; hk.expand(&info, &mut okm) - .map_err(|_| Discv5Error::KeyDerivationFailed)?; + .map_err(|_| Error::KeyDerivationFailed)?; let mut initiator_key: Key = Default::default(); let mut recipient_key: Key = Default::default(); @@ -101,17 +99,17 @@ pub(crate) fn derive_keys_from_pubkey( remote_id: &NodeId, challenge_data: &ChallengeData, ephem_pubkey: &[u8], -) -> Result<(Key, Key), Discv5Error> { +) -> Result<(Key, Key), Error> { let secret = { match local_key { CombinedKey::Secp256k1(key) => { // convert remote pubkey into secp256k1 public key // the key type should match our own node record let remote_pubkey = k256::ecdsa::VerifyingKey::from_sec1_bytes(ephem_pubkey) - .map_err(|_| Discv5Error::InvalidRemotePublicKey)?; + .map_err(|_| Error::InvalidRemotePublicKey)?; ecdh(&remote_pubkey, key) } - CombinedKey::Ed25519(_) => return Err(Discv5Error::KeyTypeNotSupported("Ed25519")), + CombinedKey::Ed25519(_) => return Err(Error::KeyTypeNotSupported("Ed25519")), } }; @@ -127,7 +125,7 @@ pub(crate) fn sign_nonce( challenge_data: &ChallengeData, ephem_pubkey: &[u8], dst_id: &NodeId, -) -> Result, Discv5Error> { +) -> Result, Error> { let signing_message = generate_signing_nonce(challenge_data, ephem_pubkey, dst_id); match signing_key { @@ -135,10 +133,10 @@ pub(crate) fn sign_nonce( let message = Sha256::new().chain_update(signing_message); let signature: Signature = key .try_sign_digest(message) - .map_err(|e| Discv5Error::Error(format!("Failed to sign message: {e}")))?; + .map_err(|e| Error::Error(format!("Failed to sign message: {e}")))?; Ok(signature.to_vec()) } - CombinedKey::Ed25519(_) => Err(Discv5Error::KeyTypeNotSupported("Ed25519")), + CombinedKey::Ed25519(_) => Err(Error::KeyTypeNotSupported("Ed25519")), } } @@ -191,9 +189,9 @@ pub(crate) fn decrypt_message( message_nonce: MessageNonce, msg: &[u8], aad: &[u8], -) -> Result, Discv5Error> { +) -> Result, Error> { if msg.len() < 16 { - return Err(Discv5Error::DecryptionFailed( + return Err(Error::DecryptionFailed( "Message not long enough to contain a MAC".into(), )); } @@ -201,7 +199,7 @@ pub(crate) fn decrypt_message( let aead = Aes128Gcm::new(GenericArray::from_slice(key)); let payload = Payload { msg, aad }; aead.decrypt(GenericArray::from_slice(&message_nonce), payload) - .map_err(|e| Discv5Error::DecryptionFailed(e.to_string())) + .map_err(|e| Error::DecryptionFailed(e.to_string())) } /* Encryption related functions */ @@ -213,11 +211,11 @@ pub(crate) fn encrypt_message( message_nonce: MessageNonce, msg: &[u8], aad: &[u8], -) -> Result, Discv5Error> { +) -> Result, Error> { let aead = Aes128Gcm::new(GenericArray::from_slice(key)); let payload = Payload { msg, aad }; aead.encrypt(GenericArray::from_slice(&message_nonce), payload) - .map_err(|e| Discv5Error::DecryptionFailed(e.to_string())) + .map_err(|e| Error::DecryptionFailed(e.to_string())) } #[cfg(test)] diff --git a/src/handler/mod.rs b/src/handler/mod.rs index 625582402..c86ef2001 100644 --- a/src/handler/mod.rs +++ b/src/handler/mod.rs @@ -27,9 +27,9 @@ //! Messages from a node on the network come by [`Socket`] and get the form of a [`HandlerOut`] //! and can be forwarded to the application layer via the send channel. use crate::{ - config::Discv5Config, + config::Config, discv5::PERMIT_BAN_LIST, - error::{Discv5Error, RequestError}, + error::{Error, RequestError}, packet::{ChallengeData, IdNonce, MessageNonce, Packet, PacketKind, ProtocolIdentity}, rpc::{Message, Request, RequestBody, RequestId, Response, ResponseBody}, socket, @@ -222,7 +222,7 @@ impl Handler { pub async fn spawn( enr: Arc>, key: Arc>, - config: Discv5Config, + config: Config, ) -> Result { let (exit_sender, exit) = oneshot::channel(); // create the channels to send/receive messages from the application @@ -866,7 +866,7 @@ impl Handler { } } } - Err(Discv5Error::InvalidChallengeSignature(challenge)) => { + Err(Error::InvalidChallengeSignature(challenge)) => { warn!( "Authentication header contained invalid signature. Ignoring packet from: {}", node_address diff --git a/src/handler/session.rs b/src/handler/session.rs index 9f79f9017..9c1f96a8f 100644 --- a/src/handler/session.rs +++ b/src/handler/session.rs @@ -61,7 +61,7 @@ impl Session { &mut self, src_id: NodeId, message: &[u8], - ) -> Result { + ) -> Result { self.counter += 1; // If the message nonce length is ever set below 4 bytes this will explode. The packet @@ -104,7 +104,7 @@ impl Session { message_nonce: MessageNonce, message: &[u8], aad: &[u8], - ) -> Result, Discv5Error> { + ) -> Result, Error> { // First try with the canonical keys. let result_canon = crypto::decrypt_message(&self.keys.decryption_key, message_nonce, message, aad); @@ -140,7 +140,7 @@ impl Session { id_nonce_sig: &[u8], ephem_pubkey: &[u8], enr_record: Option, - ) -> Result<(Session, Enr), Discv5Error> { + ) -> Result<(Session, Enr), Error> { // check and verify a potential ENR update // Duplicate code here to avoid cloning an ENR @@ -160,7 +160,7 @@ impl Session { "Peer did not respond with their ENR. Session could not be established. Node: {}", remote_id ); - return Err(Discv5Error::SessionNotEstablished); + return Err(Error::SessionNotEstablished); } }; enr.public_key() @@ -174,7 +174,7 @@ impl Session { local_id, id_nonce_sig, ) { - return Err(Discv5Error::InvalidChallengeSignature(challenge)); + return Err(Error::InvalidChallengeSignature(challenge)); } // The keys are derived after the message has been verified to prevent potential extra work @@ -220,7 +220,7 @@ impl Session { local_node_id: &NodeId, challenge_data: &ChallengeData, message: &[u8], - ) -> Result<(Packet, Session), Discv5Error> { + ) -> Result<(Packet, Session), Error> { // generate the session keys let (encryption_key, decryption_key, ephem_pubkey) = crypto::generate_session_keys(local_node_id, remote_contact, challenge_data)?; @@ -237,7 +237,7 @@ impl Session { &ephem_pubkey, &remote_contact.node_id(), ) - .map_err(|_| Discv5Error::Custom("Could not sign WHOAREYOU nonce"))?; + .map_err(|_| Error::Custom("Could not sign WHOAREYOU nonce"))?; // build an authentication packet let message_nonce: MessageNonce = rand::random(); diff --git a/src/handler/tests.rs b/src/handler/tests.rs index db9c7d3a8..d425417c9 100644 --- a/src/handler/tests.rs +++ b/src/handler/tests.rs @@ -5,7 +5,7 @@ use crate::{ packet::DefaultProtocolId, return_if_ipv6_is_not_supported, rpc::{Request, Response}, - Discv5ConfigBuilder, IpMode, + ConfigBuilder, IpMode, }; use std::net::{Ipv4Addr, Ipv6Addr}; @@ -25,7 +25,7 @@ fn init() { } async fn build_handler() -> Handler { - let config = Discv5ConfigBuilder::new(ListenConfig::default()).build(); + let config = ConfigBuilder::new(ListenConfig::default()).build(); let key = CombinedKey::generate_secp256k1(); let enr = EnrBuilder::new("v4") .ip4(Ipv4Addr::LOCALHOST) @@ -117,7 +117,7 @@ async fn simple_session_message() { ip: sender_enr.ip4().unwrap(), port: sender_enr.udp4().unwrap(), }; - let sender_config = Discv5ConfigBuilder::new(sender_listen_config) + let sender_config = ConfigBuilder::new(sender_listen_config) .enable_packet_filter() .build(); let (_exit_send, sender_send, _sender_recv) = Handler::spawn::( @@ -132,7 +132,7 @@ async fn simple_session_message() { ip: receiver_enr.ip4().unwrap(), port: receiver_enr.udp4().unwrap(), }; - let receiver_config = Discv5ConfigBuilder::new(receiver_listen_config) + let receiver_config = ConfigBuilder::new(receiver_listen_config) .enable_packet_filter() .build(); let (_exit_recv, recv_send, mut receiver_recv) = Handler::spawn::( @@ -198,7 +198,7 @@ async fn multiple_messages() { ip: sender_enr.ip4().unwrap(), port: sender_enr.udp4().unwrap(), }; - let sender_config = Discv5ConfigBuilder::new(sender_listen_config).build(); + let sender_config = ConfigBuilder::new(sender_listen_config).build(); let receiver_enr = EnrBuilder::new("v4") .ip4(ip) @@ -209,7 +209,7 @@ async fn multiple_messages() { ip: receiver_enr.ip4().unwrap(), port: receiver_enr.udp4().unwrap(), }; - let receiver_config = Discv5ConfigBuilder::new(receiver_listen_config).build(); + let receiver_config = ConfigBuilder::new(receiver_listen_config).build(); let (_exit_send, sender_handler, mut sender_handler_recv) = Handler::spawn::( @@ -353,7 +353,7 @@ async fn test_self_request_ipv4() { ip: enr.ip4().unwrap(), port: enr.udp4().unwrap(), }; - let config = Discv5ConfigBuilder::new(listen_config) + let config = ConfigBuilder::new(listen_config) .enable_packet_filter() .build(); @@ -393,7 +393,7 @@ async fn test_self_request_ipv6() { ip: enr.ip6().unwrap(), port: enr.udp6().unwrap(), }; - let config = Discv5ConfigBuilder::new(listen_config) + let config = ConfigBuilder::new(listen_config) .enable_packet_filter() .build(); diff --git a/src/lib.rs b/src/lib.rs index bff44ebee..e48990dcf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -34,13 +34,13 @@ //! ## Event Stream //! //! The [`Discv5`] struct provides access to an event-stream which allows the user to listen to -//! [`Discv5Event`] that get generated from the underlying server. The stream can be obtained from -//! the [`Discv5::event_stream`] function. +//! [`Event`] that get generated from the underlying server. The stream can be obtained from the +//! [`Discv5::event_stream`] function. //! //! ## Runtimes //! //! Discv5 requires a tokio runtime with timing and io enabled. An explicit runtime can be given -//! via the configuration. See the [`Discv5ConfigBuilder`] for further details. Such a runtime must +//! via the configuration. See the [`ConfigBuilder`] for further details. Such a runtime must //! implement the [`Executor`] trait. //! //! If an explicit runtime is not provided via the configuration parameters, it is assumed that a @@ -53,7 +53,7 @@ //! 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::{Ipv4Addr, SocketAddr}; //! @@ -75,7 +75,7 @@ //! }; //! //! // 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(); @@ -116,9 +116,9 @@ extern crate lazy_static; pub type Enr = enr::Enr; -pub use crate::discv5::{Discv5, Discv5Event}; -pub use config::{Discv5Config, Discv5ConfigBuilder}; -pub use error::{Discv5Error, QueryError, RequestError, ResponseError}; +pub use crate::discv5::{Discv5, Event}; +pub use config::{Config, ConfigBuilder}; +pub use error::{Error, QueryError, RequestError, ResponseError}; pub use executor::{Executor, TokioExecutor}; pub use ipmode::IpMode; pub use kbucket::{ConnectionDirection, ConnectionState, Key}; diff --git a/src/query_pool/peers/closest.rs b/src/query_pool/peers/closest.rs index 936cf2c9d..334d8a39f 100644 --- a/src/query_pool/peers/closest.rs +++ b/src/query_pool/peers/closest.rs @@ -23,7 +23,7 @@ // use super::*; use crate::{ - config::Discv5Config, + config::Config, kbucket::{Distance, Key, MAX_NODES_PER_BUCKET}, }; use std::{ @@ -76,7 +76,7 @@ pub struct FindNodeQueryConfig { } impl FindNodeQueryConfig { - pub fn new_from_config(config: &Discv5Config) -> Self { + pub fn new_from_config(config: &Config) -> Self { Self { parallelism: config.query_parallelism, num_results: MAX_NODES_PER_BUCKET, diff --git a/src/query_pool/peers/predicate.rs b/src/query_pool/peers/predicate.rs index 4768a1c35..3b4442019 100644 --- a/src/query_pool/peers/predicate.rs +++ b/src/query_pool/peers/predicate.rs @@ -1,6 +1,6 @@ use super::*; use crate::{ - config::Discv5Config, + config::Config, kbucket::{Distance, Key, PredicateKey, MAX_NODES_PER_BUCKET}, }; use std::{ @@ -55,7 +55,7 @@ pub(crate) struct PredicateQueryConfig { } impl PredicateQueryConfig { - pub(crate) fn new_from_config(config: &Discv5Config) -> Self { + pub(crate) fn new_from_config(config: &Config) -> Self { Self { parallelism: config.query_parallelism, num_results: MAX_NODES_PER_BUCKET, diff --git a/src/service.rs b/src/service.rs index 68e1ffb62..c20e55d36 100644 --- a/src/service.rs +++ b/src/service.rs @@ -29,7 +29,7 @@ use crate::{ query_pool::{ FindNodeQueryConfig, PredicateQueryConfig, QueryId, QueryPool, QueryPoolState, TargetKey, }, - rpc, Discv5Config, Discv5Event, Enr, IpMode, + rpc, Config, Enr, Event, IpMode, }; use delay_map::HashSetDelay; use enr::{CombinedKey, NodeId}; @@ -161,14 +161,14 @@ pub enum ServiceRequest { Ping(Enr, Option>>), /// Sets up an event stream where the discv5 server will return various events such as /// discovered nodes as it traverses the DHT. - RequestEventStream(oneshot::Sender>), + RequestEventStream(oneshot::Sender>), } use crate::discv5::PERMIT_BAN_LIST; pub struct Service { /// Configuration parameters. - config: Discv5Config, + config: Config, /// The local ENR of the server. local_enr: Arc>, @@ -211,7 +211,7 @@ pub struct Service { peers_to_ping: HashSetDelay, /// A channel that the service emits events on. - event_stream: Option>, + event_stream: Option>, // Type of socket we are using ip_mode: IpMode, @@ -277,7 +277,7 @@ impl Service { local_enr: Arc>, enr_key: Arc>, kbuckets: Arc>>, - config: Discv5Config, + config: Config, ) -> Result<(oneshot::Sender<()>, mpsc::Sender), std::io::Error> { // process behaviour-level configuration parameters let ip_votes = if config.enr_update { @@ -378,7 +378,7 @@ impl Service { Some(event) = self.handler_recv.recv() => { match event { HandlerOut::Established(enr, socket_addr, direction) => { - self.send_event(Discv5Event::SessionEstablished(enr.clone(), socket_addr)); + self.send_event(Event::SessionEstablished(enr.clone(), socket_addr)); self.inject_session_established(enr, direction); } HandlerOut::Request(node_address, request) => { @@ -631,7 +631,7 @@ impl Service { sender: Some(self.handler_send.clone()), }; - self.send_event(Discv5Event::TalkRequest(req)); + self.send_event(Event::TalkRequest(req)); } } } @@ -836,9 +836,7 @@ impl Service { "Local UDP ip6 socket updated to: {}", new_ip6, ); - self.send_event(Discv5Event::SocketUpdated( - new_ip6, - )); + self.send_event(Event::SocketUpdated(new_ip6)); } Err(e) => { warn!("Failed to update local UDP ip6 socket. ip6: {}, error: {:?}", new_ip6, e); @@ -855,9 +853,7 @@ impl Service { Ok(_) => { updated = true; info!("Local UDP socket updated to: {}", new_ip4); - self.send_event(Discv5Event::SocketUpdated( - new_ip4, - )); + self.send_event(Event::SocketUpdated(new_ip4)); } Err(e) => { warn!("Failed to update local UDP socket. ip: {}, error: {:?}", new_ip4, e); @@ -1170,7 +1166,7 @@ impl Service { } } - fn send_event(&mut self, event: Discv5Event) { + fn send_event(&mut self, event: Event) { if let Some(stream) = self.event_stream.as_mut() { if let Err(mpsc::error::TrySendError::Closed(_)) = stream.try_send(event) { // If the stream has been dropped prevent future attempts to send events @@ -1190,7 +1186,7 @@ impl Service { // If any of the discovered nodes are in the routing table, and there contains an older ENR, update it. // If there is an event stream send the Discovered event if self.config.report_discovered_peers { - self.send_event(Discv5Event::Discovered(enr.clone())); + self.send_event(Event::Discovered(enr.clone())); } // ignore peers that don't pass the table filter @@ -1286,7 +1282,7 @@ impl Service { self.send_ping(enr, None); } - let event = Discv5Event::NodeInserted { + let event = Event::NodeInserted { node_id, replaced: None, }; @@ -1500,14 +1496,12 @@ impl Service { } /// A future that maintains the routing table and inserts nodes when required. This returns the - /// `Discv5Event::NodeInserted` variant if a new node has been inserted into the routing table. - async fn bucket_maintenance_poll( - kbuckets: &Arc>>, - ) -> Discv5Event { + /// [`Event::NodeInserted`] variant if a new node has been inserted into the routing table. + async fn bucket_maintenance_poll(kbuckets: &Arc>>) -> Event { future::poll_fn(move |_cx| { // Drain applied pending entries from the routing table. if let Some(entry) = kbuckets.write().take_applied_pending() { - let event = Discv5Event::NodeInserted { + let event = Event::NodeInserted { node_id: entry.inserted.into_preimage(), replaced: entry.evicted.map(|n| n.key.into_preimage()), }; diff --git a/src/service/test.rs b/src/service/test.rs index b2860700e..24186a28c 100644 --- a/src/service/test.rs +++ b/src/service/test.rs @@ -12,7 +12,7 @@ use crate::{ rpc::RequestId, service::{ActiveRequest, Service}, socket::ListenConfig, - Discv5ConfigBuilder, Enr, + ConfigBuilder, Enr, }; use enr::{CombinedKey, EnrBuilder}; use parking_lot::RwLock; @@ -48,7 +48,7 @@ async fn build_service( ip: local_enr.read().ip4().unwrap(), port: local_enr.read().udp4().unwrap(), }; - let config = Discv5ConfigBuilder::new(listen_config) + let config = ConfigBuilder::new(listen_config) .executor(Box::::default()) .build(); // build the session service