Documentation updates (#1005)

* Documentation updates:

  * libp2p: Update the top-level module documentation, already including
    intra-rustdoc links, removing outdated documentation, updating examples and
    polishing the text.

  * libp2p-core: Update the transport documentation to clarify that a `Transport`
    is really an abstraction only for connection-oriented transports.

* More links

* Fix typo.

* Address review comments.

* More doc tweaks.

  * Mention the necessity of creating an identity keypair.
  * Remove another mention of the removed Topology trait.
This commit is contained in:
Roman Borschel
2019-03-19 12:45:57 +01:00
committed by GitHub
parent 463e1a5837
commit 9575fa6c08
6 changed files with 193 additions and 143 deletions

View File

@ -42,8 +42,6 @@
//! - Use the `NetworkBehaviour` trait to customize the behaviour of a `Swarm`. It is the //! - Use the `NetworkBehaviour` trait to customize the behaviour of a `Swarm`. It is the
//! `NetworkBehaviour` that controls what happens on the network. Multiple types that implement //! `NetworkBehaviour` that controls what happens on the network. Multiple types that implement
//! `NetworkBehaviour` can be composed into a single behaviour. //! `NetworkBehaviour` can be composed into a single behaviour.
//! - The `Topology` trait is implemented for types that hold the layout of a network. When other
//! components need the network layout to operate, they are passed an instance of a `Topology`.
//! - The `StreamMuxer` trait is implemented on structs that hold a connection to a remote and can //! - The `StreamMuxer` trait is implemented on structs that hold a connection to a remote and can
//! subdivide this connection into multiple substreams. See the `muxing` module. //! subdivide this connection into multiple substreams. See the `muxing` module.
//! - The `UpgradeInfo`, `InboundUpgrade` and `OutboundUpgrade` traits define how to upgrade each //! - The `UpgradeInfo`, `InboundUpgrade` and `OutboundUpgrade` traits define how to upgrade each
@ -58,8 +56,7 @@
//! //!
//! - The low-level APIs are contained within the `nodes` module. See the documentation for more //! - The low-level APIs are contained within the `nodes` module. See the documentation for more
//! information. //! information.
//! - The high-level APIs include the concepts of `Swarm`, `ProtocolsHandler`, `NetworkBehaviour` //! - The high-level APIs include the concepts of `Swarm`, `ProtocolsHandler` and `NetworkBehaviour`.
//! and `Topology`.
/// Multi-address re-export. /// Multi-address re-export.

View File

@ -20,22 +20,21 @@
//! High level manager of the network. //! High level manager of the network.
//! //!
//! The `Swarm` struct contains the state of the network as a whole. The entire behaviour of a //! A [`Swarm`] contains the state of the network as a whole. The entire behaviour of a
//! libp2p network can be controlled through the `Swarm`. //! libp2p network can be controlled through the `Swarm`.
//! //!
//! # Initializing a Swarm //! # Initializing a Swarm
//! //!
//! Creating a `Swarm` requires three things: //! Creating a `Swarm` requires three things:
//! //!
//! - An implementation of the `Transport` trait. This is the type that will be used in order to //! 1. A network identity of the local node in form of a [`PeerId`].
//! reach nodes on the network based on their address. See the `transport` module for more //! 2. An implementation of the [`Transport`] trait. This is the type that will be used in
//! information. //! order to reach nodes on the network based on their address. See the [`transport`] module
//! - An implementation of the `NetworkBehaviour` trait. This is a state machine that defines how //! for more information.
//! the swarm should behave once it is connected to a node. //! 3. An implementation of the [`NetworkBehaviour`] trait. This is a state machine that
//! - An implementation of the `Topology` trait. This is a container that holds the list of nodes //! defines how the swarm should behave once it is connected to a node.
//! that we think are part of the network. See the `topology` module for more information.
//! //!
//! # Network behaviour //! # Network Behaviour
//! //!
//! The `NetworkBehaviour` trait is implemented on types that indicate to the swarm how it should //! The `NetworkBehaviour` trait is implemented on types that indicate to the swarm how it should
//! behave. This includes which protocols are supported and which nodes to try to connect to. //! behave. This includes which protocols are supported and which nodes to try to connect to.

View File

@ -18,13 +18,12 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
//! Handles entering a connection with a peer. //! Connection-oriented communication channels.
//! //!
//! The main element of this module is the `Transport` trait. It is implemented on objects that //! The main entity of this module is the [`Transport`] trait, which provides an
//! allow dialing and listening. //! interface for establishing connections with other nodes, thereby negotiating
//! //! any desired protocols. The rest of the module defines combinators for
//! The rest of the module holds combinators that allow tweaking an implementation of `Transport`, //! modifying a transport through composition with other transports or protocol upgrades.
//! combine multiple transports together, or combine a transport with an upgrade.
use crate::{InboundUpgrade, OutboundUpgrade, nodes::raw_swarm::ConnectedPoint}; use crate::{InboundUpgrade, OutboundUpgrade, nodes::raw_swarm::ConnectedPoint};
use futures::prelude::*; use futures::prelude::*;
@ -47,73 +46,103 @@ pub use self::choice::OrTransport;
pub use self::memory::MemoryTransport; pub use self::memory::MemoryTransport;
pub use self::upgrade::Upgrade; pub use self::upgrade::Upgrade;
/// A transport is an object that can be used to produce connections by listening or dialing a /// A transport provides connection-oriented communication between two peers
/// peer. /// through ordered streams of data (i.e. connections).
/// ///
/// This trait is implemented on concrete transports (e.g. TCP, UDP, etc.), but also on wrappers /// Connections are established either by [listening](Transport::listen_on)
/// around them. /// or [dialing](Transport::dial) on a [`Transport`]. A peer that
/// obtains a connection by listening is often referred to as the *listener* and the
/// peer that initiated the connection through dialing as the *dialer*, in
/// contrast to the traditional roles of *server* and *client*.
///
/// Most transports also provide a form of reliable delivery on the established
/// connections but the precise semantics of these guarantees depend on the
/// specific transport.
///
/// This trait is implemented for concrete connection-oriented transport protocols
/// like TCP or Unix Domain Sockets, but also on wrappers that add additional
/// functionality to the dialing or listening process (e.g. name resolution via
/// the DNS).
///
/// Additional protocols can be layered on top of the connections established
/// by a [`Transport`] through an upgrade mechanism that is initiated via
/// [`with_upgrade`](Transport::with_upgrade) and optionally followed by further upgrades
/// through chaining calls to [`with_upgrade`](Transport::with_upgrade) and
/// [`and_then`](Transport::and_then). Thereby every upgrade yields a new [`Transport`]
/// whose connection setup incorporates all earlier upgrades followed by the new upgrade,
/// i.e. the order of the upgrades is significant.
/// ///
/// > **Note**: The methods of this trait use `self` and not `&self` or `&mut self`. In other /// > **Note**: The methods of this trait use `self` and not `&self` or `&mut self`. In other
/// > words, listening or dialing consumes the transport object. This has been designed /// > words, listening or dialing consumes the transport object. This has been designed
/// > so that you would implement this trait on `&Foo` or `&mut Foo` instead of directly /// > so that you would implement this trait on `&Foo` or `&mut Foo` instead of directly
/// > on `Foo`. /// > on `Foo`.
pub trait Transport { pub trait Transport {
/// The raw connection to a peer. /// The result of a connection setup process, including protocol upgrades.
///
/// Typically the output contains at least a handle to a data stream (i.e. a
/// connection or a substream multiplexer on top of a connection) that
/// provides APIs for sending and receiving data through the connection.
type Output; type Output;
/// Error that can happen when dialing or listening.
/// An error that occurred during connection setup.
type Error: error::Error; type Error: error::Error;
/// The listener produces incoming connections. /// A stream of [`Output`](Transport::Output)s for inbound connections.
/// ///
/// An item should be produced whenever a connection is received at the lowest level of the /// An item should be produced whenever a connection is received at the lowest level of the
/// transport stack. The item is a `Future` that is signalled once some pre-processing has /// transport stack. The item must be a [`ListenerUpgrade`](Transport::ListenerUpgrade) future
/// taken place, and that connection has been upgraded to the wanted protocols. /// that resolves to an [`Output`](Transport::Output) value once all protocol upgrades
/// have been applied.
type Listener: Stream<Item = (Self::ListenerUpgrade, Multiaddr), Error = Self::Error>; type Listener: Stream<Item = (Self::ListenerUpgrade, Multiaddr), Error = Self::Error>;
/// After a connection has been received, we may need to do some asynchronous pre-processing /// A pending [`Output`](Transport::Output) for an inbound connection,
/// on it (e.g. an intermediary protocol negotiation). While this pre-processing takes place, /// obtained from the [`Listener`](Transport::Listener) stream.
/// we want to be able to continue polling on the listener. ///
/// After a connection has been accepted by the transport, it may need to go through
/// asynchronous post-processing (i.e. protocol upgrade negotiations). Such
/// post-processing should not block the `Listener` from producing the next
/// connection, hence further connection setup proceeds asynchronously.
/// Once a `ListenerUpgrade` future resolves it yields the [`Output`](Transport::Output)
/// of the connection setup process.
type ListenerUpgrade: Future<Item = Self::Output, Error = Self::Error>; type ListenerUpgrade: Future<Item = Self::Output, Error = Self::Error>;
/// A future which indicates that we are currently dialing to a peer. /// A pending [`Output`](Transport::Output) for an outbound connection,
/// obtained from [dialing](Transport::dial).
type Dial: Future<Item = Self::Output, Error = Self::Error>; type Dial: Future<Item = Self::Output, Error = Self::Error>;
/// Listen on the given multiaddr. Returns a stream of incoming connections, plus a modified /// Listens on the given [`Multiaddr`], producing a stream of pending, inbound connections.
/// version of the `Multiaddr`. This new `Multiaddr` is the one that that should be advertised
/// to other nodes, instead of the one passed as parameter.
/// ///
/// > **Note**: The reason why we need to change the `Multiaddr` on success is to handle /// > **Note**: The new [`Multiaddr`] that is returned alongside the connection stream
/// > situations such as turning `/ip4/127.0.0.1/tcp/0` into /// > is the address that should be advertised to other nodes, as the given address
/// > `/ip4/127.0.0.1/tcp/<actual port>`. /// > may be subject to changes such as an OS-assigned port number.
fn listen_on(self, addr: Multiaddr) -> Result<(Self::Listener, Multiaddr), TransportError<Self::Error>> fn listen_on(self, addr: Multiaddr) -> Result<(Self::Listener, Multiaddr), TransportError<Self::Error>>
where where
Self: Sized; Self: Sized;
/// Dial the given multi-addr. /// Dials the given [`Multiaddr`], returning a future for a pending outbound connection.
/// ///
/// Returns either a future which may resolve to a connection. /// If [`TransportError::MultiaddrNotSupported`] is returned, it may be desirable to
/// /// try an alternative [`Transport`], if available.
/// If `MultiaddrNotSupported` is returned, then caller can try another implementation of
/// `Transport` if there is any. If instead an error is returned, then we assume that there is
/// no point in trying another `Transport`.
fn dial(self, addr: Multiaddr) -> Result<Self::Dial, TransportError<Self::Error>> fn dial(self, addr: Multiaddr) -> Result<Self::Dial, TransportError<Self::Error>>
where where
Self: Sized; Self: Sized;
/// Takes a multiaddress we're listening on (`server`), and tries to convert it to an /// Takes a [`Multiaddr`] that represents a listening address together with an
/// externally-visible multiaddress. In order to do so, we pass an `observed` address which /// an address observed by another node and tries to incoporate information
/// a remote node observes for one of our dialers. /// from the observed address into the listening address, yielding an
/// externally-visible address.
/// ///
/// For example, if `server` is `/ip4/0.0.0.0/tcp/3000` and `observed` is /// In order to do so, `observed` must be an address that a remote node observes on an
/// `/ip4/80.81.82.83/tcp/29601`, then we should return `/ip4/80.81.82.83/tcp/3000`. /// inbound connection from the local node. Each [`Transport`] implementation is only
/// responsible for handling the protocols it supports and should only consider the
/// prefix of `observed` necessary to perform the address translation
/// (e.g. `/ip4/80.81.82.83`) but should otherwise preserve `server` as is. For example,
/// if `server` is the address `/ip4/0.0.0.0/tcp/3000` and `observed` is the address
/// `/ip4/80.81.82.83/tcp/29601`, then the address `/ip4/80.81.82.83/tcp/3000` should be
/// returned.
/// ///
/// Each implementation of `Transport` is only responsible for handling the protocols it /// Returns `None` if the transport does not recognize a protocol, or if `server` and
/// supports and should only consider the prefix of `observed` necessary to perform the /// `observed` are unrelated addresses.
/// address translation (e.g. `/ip4/80.81.82.83`) but should otherwise preserve `server`
/// as is.
///
/// Returns `None` if nothing can be determined. This happens if this trait implementation
/// doesn't recognize the protocols, or if `server` and `observed` are not related.
fn nat_traversal(&self, server: &Multiaddr, observed: &Multiaddr) -> Option<Multiaddr>; fn nat_traversal(&self, server: &Multiaddr, observed: &Multiaddr) -> Option<Multiaddr>;
/// Turns this `Transport` into an abstract boxed transport. /// Turns this `Transport` into an abstract boxed transport.
@ -127,7 +156,7 @@ pub trait Transport {
boxed::boxed(self) boxed::boxed(self)
} }
/// Applies a function on the output of the `Transport`. /// Applies a function on the connections created by the transport.
#[inline] #[inline]
fn map<F, O>(self, map: F) -> map::Map<Self, F> fn map<F, O>(self, map: F) -> map::Map<Self, F>
where where
@ -137,7 +166,7 @@ pub trait Transport {
map::Map::new(self, map) map::Map::new(self, map)
} }
/// Applies a function on the errors generated by the futures of the `Transport`. /// Applies a function on the errors generated by the futures of the transport.
#[inline] #[inline]
fn map_err<F, TNewErr>(self, map_err: F) -> map_err::MapErr<Self, F> fn map_err<F, TNewErr>(self, map_err: F) -> map_err::MapErr<Self, F>
where where
@ -147,9 +176,10 @@ pub trait Transport {
map_err::MapErr::new(self, map_err) map_err::MapErr::new(self, map_err)
} }
/// Builds a new struct that implements `Transport` that contains both `self` and `other`. /// Builds a new transport that falls back to another transport when
/// encountering errors on dialing or listening for connections.
/// ///
/// The returned object will redirect its calls to `self`, except that if `listen_on` or `dial` /// The returned transport will act like `self`, except that if `listen_on` or `dial`
/// return an error then `other` will be tried. /// return an error then `other` will be tried.
#[inline] #[inline]
fn or_transport<T>(self, other: T) -> OrTransport<Self, T> fn or_transport<T>(self, other: T) -> OrTransport<Self, T>
@ -159,11 +189,13 @@ pub trait Transport {
OrTransport::new(self, other) OrTransport::new(self, other)
} }
/// Wraps this transport inside an upgrade. Whenever a connection that uses this transport /// Wraps this transport inside an [`Upgrade`].
/// is established, it is wrapped inside the upgrade.
/// ///
/// > **Note**: The concept of an *upgrade* for example includes middlewares such *secio* /// Whenever an inbound or outbound connection is established by this
/// > (communication encryption), *multiplex*, but also a protocol handler. /// transport, the upgrade is applied on the current state of the
/// connection (which may have already gone through previous upgrades)
/// as an [`upgrade::InboundUpgrade`] or [`upgrade::OutboundUpgrade`],
/// respectively.
#[inline] #[inline]
fn with_upgrade<U, O, E>(self, upgrade: U) -> Upgrade<Self, U> fn with_upgrade<U, O, E>(self, upgrade: U) -> Upgrade<Self, U>
where where
@ -175,11 +207,12 @@ pub trait Transport {
Upgrade::new(self, upgrade) Upgrade::new(self, upgrade)
} }
/// Wraps this transport inside an upgrade. Whenever a connection that uses this transport /// Applies a function producing an asynchronous result to every connection
/// is established, it is wrapped inside the upgrade. /// created by this transport.
/// ///
/// > **Note**: The concept of an *upgrade* for example includes middlewares such *secio* /// This function can be used for ad-hoc protocol upgrades on a transport or
/// > (communication encryption), *multiplex*, but also a protocol handler. /// for processing or adapting the output of an earlier upgrade before
/// applying the next upgrade.
#[inline] #[inline]
fn and_then<C, F, O>(self, upgrade: C) -> and_then::AndThen<Self, C> fn and_then<C, F, O>(self, upgrade: C) -> and_then::AndThen<Self, C>
where where
@ -190,8 +223,8 @@ pub trait Transport {
and_then::AndThen::new(self, upgrade) and_then::AndThen::new(self, upgrade)
} }
/// Adds a timeout to the connection and upgrade steps for all the sockets created by /// Adds a timeout to the connection setup (including upgrades) for all inbound
/// the transport. /// and outbound connection attempts.
#[inline] #[inline]
fn with_timeout(self, timeout: Duration) -> timeout::TransportTimeout<Self> fn with_timeout(self, timeout: Duration) -> timeout::TransportTimeout<Self>
where where
@ -200,8 +233,8 @@ pub trait Transport {
timeout::TransportTimeout::new(self, timeout) timeout::TransportTimeout::new(self, timeout)
} }
/// Adds a timeout to the connection and upgrade steps for all the outgoing sockets created /// Adds a timeout to the connection setup (including upgrades) for all outbound
/// by the transport. /// connection attempts.
#[inline] #[inline]
fn with_outbound_timeout(self, timeout: Duration) -> timeout::TransportTimeout<Self> fn with_outbound_timeout(self, timeout: Duration) -> timeout::TransportTimeout<Self>
where where
@ -210,8 +243,8 @@ pub trait Transport {
timeout::TransportTimeout::with_outgoing_timeout(self, timeout) timeout::TransportTimeout::with_outgoing_timeout(self, timeout)
} }
/// Adds a timeout to the connection and upgrade steps for all the incoming sockets created /// Adds a timeout to the connection setup (including upgrades) for all inbound
/// by the transport. /// connection attempts.
#[inline] #[inline]
fn with_inbound_timeout(self, timeout: Duration) -> timeout::TransportTimeout<Self> fn with_inbound_timeout(self, timeout: Duration) -> timeout::TransportTimeout<Self>
where where
@ -221,20 +254,21 @@ pub trait Transport {
} }
} }
/// Error that can happen when dialing or listening. /// An error during [dialing][Transport::dial] or [listening][Transport::listen_on]
/// on a [`Transport`].
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum TransportError<TErr> { pub enum TransportError<TErr> {
/// The `Multiaddr` passed as parameter is not supported. /// The [`Multiaddr`] passed as parameter is not supported.
/// ///
/// Contains back the same address. /// Contains back the same address.
MultiaddrNotSupported(Multiaddr), MultiaddrNotSupported(Multiaddr),
/// Any other error that the `Transport` may produce. /// Any other error that a [`Transport`] may produce.
Other(TErr), Other(TErr),
} }
impl<TErr> TransportError<TErr> { impl<TErr> TransportError<TErr> {
/// Applies a map to the `Other` variant. /// Applies a function to the the error in [`TransportError::Other`].
#[inline] #[inline]
pub fn map<TNewErr>(self, map: impl FnOnce(TErr) -> TNewErr) -> TransportError<TNewErr> { pub fn map<TNewErr>(self, map: impl FnOnce(TErr) -> TNewErr) -> TransportError<TNewErr> {
match self { match self {

View File

@ -18,9 +18,10 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
//! Wraps around a `Transport` and adds a timeout to all the incoming and outgoing connections. //! Transports with timeouts on the connection setup.
//! //!
//! The timeout includes the upgrading process. //! The connection setup includes all protocol upgrades applied on the
//! underlying `Transport`.
// TODO: add example // TODO: add example
use crate::{Multiaddr, Transport, transport::TransportError}; use crate::{Multiaddr, Transport, transport::TransportError};
@ -30,10 +31,11 @@ use std::{error, fmt, time::Duration};
use tokio_timer::Timeout; use tokio_timer::Timeout;
use tokio_timer::timeout::Error as TimeoutError; use tokio_timer::timeout::Error as TimeoutError;
/// Wraps around a `Transport` and adds a timeout to all the incoming and outgoing connections. /// A `TransportTimeout` is a `Transport` that wraps another `Transport` and adds
/// timeouts to all inbound and outbound connection attempts.
/// ///
/// The timeout includes the upgrade. There is no timeout on the listener or on stream of incoming /// **Note**: `listen_on` is never subject to a timeout, only the setup of each
/// substreams. /// individual accepted connection.
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
pub struct TransportTimeout<InnerTrans> { pub struct TransportTimeout<InnerTrans> {
inner: InnerTrans, inner: InnerTrans,

View File

@ -127,8 +127,6 @@ where
} }
} }
#[derive(Clone)] #[derive(Clone)]
pub struct Config(yamux::Config); pub struct Config(yamux::Config);

View File

@ -26,7 +26,8 @@
//! //!
//! ## Multiaddr //! ## Multiaddr
//! //!
//! A `Multiaddr` is a way to reach a node. Examples: //! A [`Multiaddr`] is a self-describing network address and protocol stack
//! that is used to establish connections to peers. Some examples:
//! //!
//! * `/ip4/80.123.90.4/tcp/5432` //! * `/ip4/80.123.90.4/tcp/5432`
//! * `/ip6/[::1]/udp/10560/quic` //! * `/ip6/[::1]/udp/10560/quic`
@ -34,100 +35,119 @@
//! //!
//! ## Transport //! ## Transport
//! //!
//! `Transport` is a trait that represents an object capable of dialing multiaddresses or //! [`Transport`] is a trait for types that provide connection-oriented communication channels
//! listening on multiaddresses. The `Transport` produces an output which varies depending on the //! based on dialing to or listening on a [`Multiaddr`]. To that end a transport
//! object that implements the trait. //! produces as output a type of data stream that varies depending on the concrete type of
//! transport.
//! //!
//! Each implementation of `Transport` typically supports only some multiaddresses. For example //! An implementation of transport typically supports only certain multi-addresses.
//! the `TcpConfig` type (which implements `Transport`) only supports multiaddresses of the format //! For example, the [`TcpConfig`] only supports multi-addresses of the format
//! `/ip4/.../tcp/...`. //! `/ip4/.../tcp/...`.
//! //!
//! Example: //! Example (Dialing a TCP/IP multi-address):
//! //!
//! ```rust //! ```rust
//! use libp2p::{Multiaddr, Transport, tcp::TcpConfig}; //! use libp2p::{Multiaddr, Transport, tcp::TcpConfig};
//! let tcp = TcpConfig::new(); //! let tcp = TcpConfig::new();
//! let addr: Multiaddr = "/ip4/98.97.96.95/tcp/20500".parse().expect("invalid multiaddr"); //! let addr: Multiaddr = "/ip4/98.97.96.95/tcp/20500".parse().expect("invalid multiaddr");
//! let _outgoing_connec = tcp.dial(addr); //! let _conn = tcp.dial(addr);
//! // Note that `_outgoing_connec` is a `Future`, and therefore doesn't do anything by itself
//! // unless it is run through a tokio runtime.
//! ``` //! ```
//! In the above example, `_conn` is a [`Future`] that needs to be polled in order for
//! the dialing to take place and eventually resolve to a connection. Polling
//! futures is typically done through a [tokio] runtime.
//! //!
//! The easiest way to create a transport is to use the `build_development_transport` function. //! The easiest way to create a transport is to use [`build_development_transport`].
//! This function provides support for the most common protocols. //! This function provides support for the most common protocols but it is also
//! subject to change over time and should thus not be used in production
//! configurations.
//! //!
//! Example: //! Example (Creating a development transport):
//! //!
//! ```rust //! ```rust
//! let key = libp2p::identity::Keypair::generate_ed25519(); //! let keypair = libp2p::identity::Keypair::generate_ed25519();
//! let _transport = libp2p::build_development_transport(key); //! let _transport = libp2p::build_development_transport(keypair);
//! // _transport.dial(...); //! // _transport.dial(...);
//! ``` //! ```
//! //!
//! See the documentation of the `libp2p-core` crate for more details about transports. //! The keypair that is passed as an argument in the above example is used
//! to set up transport-layer encryption using a newly generated long-term
//! identity keypair. The public key of this keypair uniquely identifies
//! the node in the network in the form of a [`PeerId`].
//! //!
//! # Connection upgrades //! See the documentation of the [`Transport`] trait for more details.
//! //!
//! Once a connection has been opened with a remote through a `Transport`, it can be *upgraded*. //! ### Connection Upgrades
//! This consists in negotiating a protocol with the remote (through a negotiation protocol
//! `multistream-select`), and applying that protocol on the socket.
//! //!
//! Example: //! Once a connection has been established with a remote through a [`Transport`], it can be
//! *upgraded*. Upgrading a transport is the process of negotiating an additional protocol
//! with the remote, mediated through a negotiation protocol called [`multistream-select`].
//!
//! Example ([`secio`] Protocol Upgrade):
//! //!
//! ```rust //! ```rust
//! # #[cfg(all(any(target_os = "emscripten", target_os = "unknown"), feature = "libp2p-secio"))] { //! # #[cfg(all(not(any(target_os = "emscripten", target_os = "unknown")), feature = "libp2p-secio"))] {
//! use libp2p::{Transport, tcp::TcpConfig, secio::{SecioConfig, SecioKeyPair}}; //! use libp2p::{Transport, tcp::TcpConfig, secio::SecioConfig, identity::Keypair};
//! let tcp = TcpConfig::new(); //! let tcp = TcpConfig::new();
//! let secio_upgrade = SecioConfig::new(SecioKeyPair::ed25519_generated().unwrap()); //! let secio_upgrade = SecioConfig::new(Keypair::generate_ed25519());
//! let with_security = tcp.with_upgrade(secio_upgrade); //! let tcp_secio = tcp.with_upgrade(secio_upgrade);
//! // let _ = with_security.dial(...); //! // let _ = tcp_secio.dial(...);
//! // `with_security` also implements the `Transport` trait, and all the connections opened
//! // through it will automatically negotiate the `secio` protocol.
//! # } //! # }
//! ``` //! ```
//! In this example, `tcp_secio` is a new [`Transport`] that negotiates the secio protocol
//! on all connections.
//! //!
//! See the documentation of the `libp2p-core` crate for more details about upgrades. //! ## Network Behaviour
//! //!
//! ## Topology //! The [`NetworkBehaviour`] trait is implemented on types that provide some capability to the
//! network. Examples of network behaviours include:
//! //!
//! The `Topology` trait is implemented for types that hold the layout of a network. When other //! * Periodically pinging other nodes on established connections.
//! components need the network layout to operate, they are passed an instance of a `Topology`. //! * Periodically asking for information from other nodes.
//! //! * Querying information from a DHT and propagating it to other nodes.
//! The most basic implementation of `Topology` is the `MemoryTopology`, which is essentially a
//! `HashMap`. Creating your own `Topology` makes it possible to add for example a reputation
//! system.
//!
//! ## Network behaviour
//!
//! The `NetworkBehaviour` trait is implemented on types that provide some capability to the
//! network. Examples of network behaviours include: periodically ping the nodes we are connected
//! to, periodically ask for information from the nodes we are connected to, connect to a DHT and
//! make queries to it, propagate messages to the nodes we are connected to (pubsub), and so on.
//! //!
//! ## Swarm //! ## Swarm
//! //!
//! The `Swarm` struct contains all active and pending connections to remotes and manages the //! A [`Swarm`] manages a pool of connections established through a [`Transport`]
//! state of all the substreams that have been opened, and all the upgrades that were built upon //! and drives a [`NetworkBehaviour`] through emitting events triggered by activity
//! these substreams. //! on the managed connections. Creating a [`Swarm`] thus involves combining a
//! [`Transport`] with a [`NetworkBehaviour`].
//! //!
//! It combines a `Transport`, a `NetworkBehaviour` and a `Topology` together. //! See the documentation of the [`core`] module for more details about swarms.
//!
//! See the documentation of the `libp2p-core` crate for more details about creating a swarm.
//! //!
//! # Using libp2p //! # Using libp2p
//! //!
//! This section contains details about how to use libp2p in practice. //! The easiest way to get started with libp2p involves the following steps:
//! //!
//! The most simple way to use libp2p consists in the following steps: //! 1. Creating an identity [`Keypair`] for the local node, obtaining the local
//! [`PeerId`] from the [`PublicKey`].
//! 2. Creating an instance of a base [`Transport`], e.g. [`TcpConfig`], upgrading it with
//! all the desired protocols, such as for transport security and multiplexing.
//! In order to be usable with a [`Swarm`] later, the [`Output`](Transport::Output)
//! of the final transport must be a tuple of a [`PeerId`] and a value whose type
//! implements [`StreamMuxer`] (e.g. [`Yamux`]). The peer ID must be the
//! identity of the remote peer of the established connection, which is
//! usually obtained through a transport encryption protocol such as
//! [`secio`] that authenticates the peer. See the implementation of
//! [`build_development_transport`] for an example.
//! 3. Creating a struct that implements the [`NetworkBehaviour`] trait and combines all the
//! desired network behaviours, implementing the event handlers as per the
//! desired application's networking logic.
//! 4. Instantiating a [`Swarm`] with the transport, the network behaviour and the
//! local peer ID from the previous steps.
//! //!
//! - Create a *base* implementation of `Transport` that combines all the protocols you want and //! The swarm instance can then be polled with the [tokio] library, in order to
//! the upgrades you want, such as the security layer and multiplexing. //! continuously drive the network activity of the program.
//! - Create a struct that implements the `NetworkBehaviour` trait and that combines all the
//! network behaviours that you want.
//! - Create and implement the `Topology` trait that to store the topology of the network.
//! - Create a swarm that combines your base transport, the network behaviour, and the topology.
//! - This swarm can now be polled with the `tokio` library in order to start the network.
//! //!
//! [`Keypair`]: identity::Keypair
//! [`PublicKey`]: identity::PublicKey
//! [`Future`]: futures::Future
//! [`TcpConfig`]: tcp::TcpConfig
//! [`NetworkBehaviour`]: core::swarm::NetworkBehaviour
//! [`StreamMuxer`]: core::muxing::StreamMuxer
//! [`Yamux`]: yamux::Yamux
//!
//! [tokio]: https://tokio.rs
//! [`multistream-select`]: https://github.com/multiformats/multistream-select
#![doc(html_logo_url = "https://libp2p.io/img/logo_small.png")] #![doc(html_logo_url = "https://libp2p.io/img/logo_small.png")]
#![doc(html_favicon_url = "https://libp2p.io/img/favicon.png")] #![doc(html_favicon_url = "https://libp2p.io/img/favicon.png")]