Struct discv5::Discv5

source ·
pub struct Discv5<P = DefaultProtocolId>{ /* private fields */ }
Expand description

The main Discv5 Service struct. This provides the user-level API for performing queries and interacting with the underlying service.

Implementations§

source§

impl<P: ProtocolIdentity> Discv5<P>

source

pub fn new( local_enr: Enr, enr_key: CombinedKey, config: Config ) -> Result<Self, &'static str>

source

pub async fn start(&mut self) -> Result<(), Error>

Starts the required tasks and begins listening on a given UDP SocketAddr.

source

pub fn shutdown(&mut self)

Terminates the service.

source

pub fn add_enr(&self, enr: Enr) -> Result<(), &'static str>

Adds a known ENR of a peer participating in Service to the routing table.

This allows pre-populating the Kademlia routing table with known addresses, so that they can be used immediately in following DHT operations involving one of these peers, without having to dial them upfront.

source

pub fn remove_node(&self, node_id: &NodeId) -> bool

Removes a node_id from the routing table.

This allows applications, for whatever reason, to remove nodes from the local routing table. Returns true if the node was in the table and false otherwise.

source

pub fn nodes_by_distance(&self, distances: Vec<u64>) -> Vec<Enr>

Returns a vector of closest nodes by the given distances.

source

pub fn disconnect_node(&self, node_id: &NodeId) -> bool

Mark a node in the routing table as Disconnected.

A Disconnected node will be present in the routing table and will be only used if there are no other Connected peers in the bucket. Returns true if node was in table and false otherwise.

source

pub fn connected_peers(&self) -> usize

Returns the number of connected peers that exist in the routing table.

source

pub fn metrics(&self) -> Metrics

Gets the metrics associated with the Server

source

pub fn raw_metrics() -> &'static METRICS

Exposes the raw reference to the underlying internal metrics.

source

pub fn local_enr(&self) -> Enr

Returns the local ENR of the node.

source

pub fn external_enr(&self) -> Arc<RwLock<Enr>>

Identical to Discv5::local_enr except that this exposes the Arc itself.

This is useful for synchronising views of the local ENR outside of Discv5.

source

pub fn kbuckets(&self) -> KBucketsTable<NodeId, Enr>

Returns the routing table of the discv5 service

source

pub fn find_enr(&self, node_id: &NodeId) -> Option<Enr>

Returns an ENR if one is known for the given NodeId.

source

pub fn send_ping( &self, enr: Enr ) -> impl Future<Output = Result<Pong, RequestError>> + 'static

Sends a PING request to a node.

source

pub fn ban_node(&self, node_id: &NodeId, duration_of_ban: Option<Duration>)

Bans a node from the server. This will remove the node from the routing table if it exists and block all incoming packets from the node until the timeout specified. Setting the timeout to None creates a permanent ban.

source

pub fn ban_node_remove(&self, node_id: &NodeId)

Removes a banned node from the banned list.

source

pub fn permit_node(&self, node_id: &NodeId)

Permits a node, allowing the node to bypass the packet filter.

source

pub fn permit_node_remove(&self, node_id: &NodeId)

Removes a node from the permit list.

source

pub fn ban_ip(&self, ip: IpAddr, duration_of_ban: Option<Duration>)

Bans an IP from the server. This will block all incoming packets from the IP.

source

pub fn ban_ip_remove(&self, ip: &IpAddr)

Removes a banned IP from the banned list.

source

pub fn permit_ip(&self, ip: IpAddr)

Permits an IP, allowing the all packets from the IP to bypass the packet filter.

source

pub fn permit_ip_remove(&self, ip: &IpAddr)

Removes an IP from the permit list.

source

pub fn update_local_enr_socket( &self, socket_addr: SocketAddr, is_tcp: bool ) -> bool

Updates the local ENR TCP/UDP socket.

source

pub fn enr_insert<T: Encodable>( &self, key: &str, value: &T ) -> Result<Option<Vec<u8>>, EnrError>

Allows application layer to insert an arbitrary field into the local ENR.

source

pub fn table_entries_id(&self) -> Vec<NodeId>

Returns an iterator over all ENR node IDs of nodes currently contained in the routing table.

source

pub fn table_entries_enr(&self) -> Vec<Enr>

Returns an iterator over all the ENR’s of nodes currently contained in the routing table.

source

pub fn table_entries(&self) -> Vec<(NodeId, Enr, NodeStatus)>

Returns an iterator over all the entries in the routing table.

source

pub fn with_kbuckets<F, T>(&self, f: F) -> T
where F: FnOnce(&Arc<RwLock<KBucketsTable<NodeId, Enr>>>) -> T,

Takes a closure parameterized by type Arc<RwLock<KBucketsTable<NodeId, Enr>>> as parameter. Caution: caller is responsible of dropping a lock taken on the kbuckets. For example, a read lock can be taken on the kbuckets to optimistically view the current keys in the kbuckets (optimistic since it doesn’t apply pending entries, which requires a write lock).

use std::str::FromStr;
use discv5::{ConfigBuilder, Discv5, ListenConfig, Enr, enr::CombinedKey};

let sk = CombinedKey::generate_secp256k1();
let enr = Enr::builder().build(&sk).unwrap();
let config = ConfigBuilder::new(ListenConfig::default()).build();
let discv5: Discv5 = Discv5::new(enr, sk, config).unwrap();

let entries =  discv5.with_kbuckets(|kbuckets| kbuckets
    .read()
    .iter_ref()
    .map(|entry| *entry.node.key.preimage())
    .collect::<Vec<_>>());
source

pub fn talk_req( &self, enr: Enr, protocol: Vec<u8>, request: Vec<u8> ) -> impl Future<Output = Result<Vec<u8>, RequestError>> + 'static

Request a TALK message from a node, identified via the ENR.

source

pub fn find_node_designated_peer( &self, enr: Enr, distances: Vec<u64> ) -> impl Future<Output = Result<Vec<Enr>, RequestError>> + 'static

Send a FINDNODE request for nodes that fall within the given set of distances, to the designated peer and wait for a response.

source

pub fn find_node( &self, target_node: NodeId ) -> impl Future<Output = Result<Vec<Enr>, QueryError>> + 'static

Runs an iterative FIND_NODE request.

This will return peers containing contactable nodes of the DHT closest to the requested NodeId.

Note: The async syntax is forgone here in order to create 'static futures, where the underlying sending channel is cloned.

source

pub fn find_node_predicate( &self, target_node: NodeId, predicate: Box<dyn Fn(&Enr) -> bool + Send>, target_peer_no: usize ) -> impl Future<Output = Result<Vec<Enr>, QueryError>> + 'static

Starts a FIND_NODE request.

This will return less than or equal to num_nodes ENRs which satisfy the predicate.

The predicate is a boxed function that takes an ENR reference and returns a boolean indicating if the record is applicable to the query or not.

Note: The async syntax is forgone here in order to create 'static futures, where the underlying sending channel is cloned.

§Example
 let predicate = Box::new(|enr: &Enr| enr.ip().is_some());
 let target = NodeId::random();
 let result = discv5.find_node_predicate(target, predicate, 5).await;
source

pub fn event_stream( &self ) -> impl Future<Output = Result<Receiver<Event>, Error>> + 'static

Creates an event stream channel which can be polled to receive Discv5 events.

Trait Implementations§

source§

impl<P: ProtocolIdentity> Drop for Discv5<P>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<P> Freeze for Discv5<P>

§

impl<P = DefaultProtocolId> !RefUnwindSafe for Discv5<P>

§

impl<P> Send for Discv5<P>
where P: Send,

§

impl<P> Sync for Discv5<P>
where P: Sync,

§

impl<P> Unpin for Discv5<P>
where P: Unpin,

§

impl<P = DefaultProtocolId> !UnwindSafe for Discv5<P>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more