libp2p::kad

Struct Behaviour

pub struct Behaviour<TStore> { /* private fields */ }
Available on crate feature kad only.
Expand description

Behaviour is a NetworkBehaviour that implements the libp2p Kademlia protocol.

Implementations§

§

impl<TStore> Behaviour<TStore>
where TStore: RecordStore + Send + 'static,

pub fn new(id: PeerId, store: TStore) -> Behaviour<TStore>

Creates a new Kademlia network behaviour with a default configuration.

pub fn protocol_names(&self) -> &[StreamProtocol]

Get the protocol name of this kademlia instance.

pub fn with_config( id: PeerId, store: TStore, config: Config, ) -> Behaviour<TStore>

Creates a new Kademlia network behaviour with the given configuration.

pub fn iter_queries(&self) -> impl Iterator<Item = QueryRef<'_>>

Gets an iterator over immutable references to all running queries.

pub fn iter_queries_mut(&mut self) -> impl Iterator<Item = QueryMut<'_>>

Gets an iterator over mutable references to all running queries.

pub fn query(&self, id: &QueryId) -> Option<QueryRef<'_>>

Gets an immutable reference to a running query, if it exists.

pub fn query_mut<'a>(&'a mut self, id: &QueryId) -> Option<QueryMut<'a>>

Gets a mutable reference to a running query, if it exists.

pub fn add_address( &mut self, peer: &PeerId, address: Multiaddr, ) -> RoutingUpdate

Adds a known listen address of a peer participating in the DHT to the routing table.

Explicitly adding addresses of peers serves two purposes:

  1. In order for a node to join the DHT, it must know about at least one other node of the DHT.

  2. When a remote peer initiates a connection and that peer is not yet in the routing table, the Kademlia behaviour must be informed of an address on which that peer is listening for connections before it can be added to the routing table from where it can subsequently be discovered by all peers in the DHT.

If the routing table has been updated as a result of this operation, a Event::RoutingUpdated event is emitted.

pub fn remove_address( &mut self, peer: &PeerId, address: &Multiaddr, ) -> Option<EntryView<Key<PeerId>, Addresses>>

Removes an address of a peer from the routing table.

If the given address is the last address of the peer in the routing table, the peer is removed from the routing table and Some is returned with a view of the removed entry. The same applies if the peer is currently pending insertion into the routing table.

If the given peer or address is not in the routing table, this is a no-op.

pub fn remove_peer( &mut self, peer: &PeerId, ) -> Option<EntryView<Key<PeerId>, Addresses>>

Removes a peer from the routing table.

Returns None if the peer was not in the routing table, not even pending insertion.

pub fn kbuckets( &mut self, ) -> impl Iterator<Item = KBucketRef<'_, Key<PeerId>, Addresses>>

Returns an iterator over all non-empty buckets in the routing table.

pub fn kbucket<K>( &mut self, key: K, ) -> Option<KBucketRef<'_, Key<PeerId>, Addresses>>
where K: Into<Key<K>> + Clone,

Returns the k-bucket for the distance to the given key.

Returns None if the given key refers to the local key.

pub fn get_closest_peers<K>(&mut self, key: K) -> QueryId
where K: Into<Key<K>> + Into<Vec<u8>> + Clone,

Initiates an iterative query for the closest peers to the given key.

The result of the query is delivered in a [Event::OutboundQueryProgressed{QueryResult::GetClosestPeers}].

pub fn get_n_closest_peers<K>( &mut self, key: K, num_results: NonZero<usize>, ) -> QueryId
where K: Into<Key<K>> + Into<Vec<u8>> + Clone,

Initiates an iterative query for the closest peers to the given key. The expected responding peers is specified by num_results Note that the result is capped after exceeds K_VALUE

The result of the query is delivered in a [Event::OutboundQueryProgressed{QueryResult::GetClosestPeers}].

pub fn get_closest_local_peers<'a, K>( &'a mut self, key: &'a Key<K>, ) -> impl Iterator<Item = Key<PeerId>> + 'a
where K: Clone,

Returns all peers ordered by distance to the given key; takes peers from local routing table only.

pub fn find_closest_local_peers<'a, K>( &'a mut self, key: &'a Key<K>, source: &'a PeerId, ) -> impl Iterator<Item = KadPeer> + 'a
where K: Clone,

Finds the closest peers to a key in the context of a request by the source peer, such that the source peer is never included in the result.

Takes peers from local routing table only. Only returns number of peers equal to configured replication factor.

pub fn get_record(&mut self, key: Key) -> QueryId

Performs a lookup for a record in the DHT.

The result of this operation is delivered in a [Event::OutboundQueryProgressed{QueryResult::GetRecord}].

pub fn put_record( &mut self, record: Record, quorum: Quorum, ) -> Result<QueryId, Error>

Stores a record in the DHT, locally as well as at the nodes closest to the key as per the xor distance metric.

Returns Ok if a record has been stored locally, providing the QueryId of the initial query that replicates the record in the DHT. The result of the query is eventually reported as a [Event::OutboundQueryProgressed{QueryResult::PutRecord}].

The record is always stored locally with the given expiration. If the record’s expiration is None, the common case, it does not expire in local storage but is still replicated with the configured record TTL. To remove the record locally and stop it from being re-published in the DHT, see Behaviour::remove_record.

After the initial publication of the record, it is subject to (re-)replication and (re-)publication as per the configured intervals. Periodic (re-)publication does not update the record’s expiration in local storage, thus a given record with an explicit expiration will always expire at that instant and until then is subject to regular (re-)replication and (re-)publication.

pub fn put_record_to<I>( &mut self, record: Record, peers: I, quorum: Quorum, ) -> QueryId
where I: ExactSizeIterator<Item = PeerId>,

Stores a record at specific peers, without storing it locally.

The given Quorum is understood in the context of the total number of distinct peers given.

If the record’s expiration is None, the configured record TTL is used.

Note: This is not a regular Kademlia DHT operation. It needs to be used to selectively update or store a record to specific peers for the purpose of e.g. making sure these peers have the latest “version” of a record or to “cache” a record at further peers to increase the lookup success rate on the DHT for other peers.

In particular, there is no automatic storing of records performed, and this method must be used to ensure the standard Kademlia procedure of “caching” (i.e. storing) a found record at the closest node to the key that did not return it.

pub fn remove_record(&mut self, key: &Key)

Removes the record with the given key from local storage, if the local node is the publisher of the record.

Has no effect if a record for the given key is stored locally but the local node is not a publisher of the record.

This is a local operation. However, it also has the effect that the record will no longer be periodically re-published, allowing the record to eventually expire throughout the DHT.

pub fn store_mut(&mut self) -> &mut TStore

Gets a mutable reference to the record store.

pub fn bootstrap(&mut self) -> Result<QueryId, NoKnownPeers>

Bootstraps the local node to join the DHT.

Bootstrapping is a multi-step operation that starts with a lookup of the local node’s own ID in the DHT. This introduces the local node to the other nodes in the DHT and populates its routing table with the closest neighbours.

Subsequently, all buckets farther from the bucket of the closest neighbour are refreshed by initiating an additional bootstrapping query for each such bucket with random keys.

Returns Ok if bootstrapping has been initiated with a self-lookup, providing the QueryId for the entire bootstrapping process. The progress of bootstrapping is reported via [Event::OutboundQueryProgressed{QueryResult::Bootstrap}] events, with one such event per bootstrapping query.

Returns Err if bootstrapping is impossible due an empty routing table.

Note: Bootstrapping requires at least one node of the DHT to be known. See Behaviour::add_address.

Note: Bootstrap does not require to be called manually. It is periodically invoked at regular intervals based on the configured periodic_bootstrap_interval (see Config::set_periodic_bootstrap_interval for details) and it is also automatically invoked when a new peer is inserted in the routing table. This parameter is used to call Behaviour::bootstrap periodically and automatically to ensure a healthy routing table.

pub fn start_providing(&mut self, key: Key) -> Result<QueryId, Error>

Establishes the local node as a provider of a value for the given key.

This operation publishes a provider record with the given key and identity of the local node to the peers closest to the key, thus establishing the local node as a provider.

Returns Ok if a provider record has been stored locally, providing the QueryId of the initial query that announces the local node as a provider.

The publication of the provider records is periodically repeated as per the configured interval, to renew the expiry and account for changes to the DHT topology. A provider record may be removed from local storage and thus no longer re-published by calling Behaviour::stop_providing.

In contrast to the standard Kademlia push-based model for content distribution implemented by Behaviour::put_record, the provider API implements a pull-based model that may be used in addition or as an alternative. The means by which the actual value is obtained from a provider is out of scope of the libp2p Kademlia provider API.

The results of the (repeated) provider announcements sent by this node are reported via [Event::OutboundQueryProgressed{QueryResult::StartProviding}].

pub fn stop_providing(&mut self, key: &Key)

Stops the local node from announcing that it is a provider for the given key.

This is a local operation. The local node will still be considered as a provider for the key by other nodes until these provider records expire.

pub fn get_providers(&mut self, key: Key) -> QueryId

Performs a lookup for providers of a value to the given key.

The result of this operation is delivered in a reported via [Event::OutboundQueryProgressed{QueryResult::GetProviders}].

pub fn set_mode(&mut self, mode: Option<Mode>)

Set the Mode in which we should operate.

By default, we are in Mode::Client and will swap into Mode::Server as soon as we have a confirmed, external address via FromSwarm::ExternalAddrConfirmed.

Setting a mode via this function disables this automatic behaviour and unconditionally operates in the specified mode. To reactivate the automatic configuration, pass None instead.

pub fn mode(&self) -> Mode

Get the Mode in which the DHT is currently operating.

Trait Implementations§

§

impl<TStore> NetworkBehaviour for Behaviour<TStore>
where TStore: RecordStore + Send + 'static,

§

type ConnectionHandler = Handler

Handler for all the protocols the network behaviour supports.
§

type ToSwarm = Event

Event generated by the NetworkBehaviour and that the swarm will report back.
§

fn handle_established_inbound_connection( &mut self, connection_id: ConnectionId, peer: PeerId, local_addr: &Multiaddr, remote_addr: &Multiaddr, ) -> Result<<Behaviour<TStore> as NetworkBehaviour>::ConnectionHandler, ConnectionDenied>

Callback that is invoked for every established inbound connection. Read more
§

fn handle_established_outbound_connection( &mut self, connection_id: ConnectionId, peer: PeerId, addr: &Multiaddr, role_override: Endpoint, port_use: PortUse, ) -> Result<<Behaviour<TStore> as NetworkBehaviour>::ConnectionHandler, ConnectionDenied>

Callback that is invoked for every established outbound connection. Read more
§

fn handle_pending_outbound_connection( &mut self, _connection_id: ConnectionId, maybe_peer: Option<PeerId>, _addresses: &[Multiaddr], _effective_role: Endpoint, ) -> Result<Vec<Multiaddr>, ConnectionDenied>

Callback that is invoked for every outbound connection attempt. Read more
§

fn on_connection_handler_event( &mut self, source: PeerId, connection: ConnectionId, event: <<Behaviour<TStore> as NetworkBehaviour>::ConnectionHandler as ConnectionHandler>::ToBehaviour, )

Informs the behaviour about an event generated by the ConnectionHandler dedicated to the peer identified by peer_id. for the behaviour. Read more
§

fn poll( &mut self, cx: &mut Context<'_>, ) -> Poll<ToSwarm<<Behaviour<TStore> as NetworkBehaviour>::ToSwarm, <<Behaviour<TStore> as NetworkBehaviour>::ConnectionHandler as ConnectionHandler>::FromBehaviour>>

Polls for things that swarm should do. Read more
§

fn on_swarm_event(&mut self, event: FromSwarm<'_>)

Informs the behaviour about an event from the Swarm.
§

fn handle_pending_inbound_connection( &mut self, _connection_id: ConnectionId, _local_addr: &Multiaddr, _remote_addr: &Multiaddr, ) -> Result<(), ConnectionDenied>

Callback that is invoked for every new inbound connection. Read more

Auto Trait Implementations§

§

impl<TStore> Freeze for Behaviour<TStore>
where TStore: Freeze,

§

impl<TStore> !RefUnwindSafe for Behaviour<TStore>

§

impl<TStore> Send for Behaviour<TStore>
where TStore: Send,

§

impl<TStore> Sync for Behaviour<TStore>
where TStore: Sync,

§

impl<TStore> Unpin for Behaviour<TStore>
where TStore: Unpin,

§

impl<TStore> !UnwindSafe for Behaviour<TStore>

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
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

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.

§

impl<T> Instrument for T

§

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

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

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

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>,

Source§

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.
§

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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