### Kademlia DHT Example Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/05-protocols-overview.md A basic example demonstrating how to initialize and use the Kademlia DHT behaviour, including starting bootstrap and storing a record. ```APIDOC ```rust use libp2p::kad::{Behaviour, Config, store::MemoryStore}; use libp2p::kad::{Record, RecordKey}; use libp2p::PeerId; use std::time::Duration; // Assume local_peer_id is already defined let local_peer_id: PeerId = /* ... */; // Initialize Kademlia behaviour let mut behaviour = Behaviour::new(local_peer_id); // Start DHT bootstrap if let Some(query_id) = behaviour.bootstrap() { println!("Bootstrap started: {:?}", query_id); } // Store a record let key = RecordKey::new(&b"my-key"[..]); let record = Record { key: key.clone(), value: b"my-value".to_vec(), publisher: Some(local_peer_id), expires_at: None, }; match behaviour.put_record(record) { Ok(query_id) => println!("Put record started: {:?}", query_id), Err(e) => eprintln!("Failed to put record: {:?}", e), } // Example of retrieving a record (not shown in original example, but common usage) // let get_key = RecordKey::new(&b"my-key"[..]); // if let Some(query_id) = behaviour.get_record(get_key) { // println!("Get record started: {:?}", query_id); // } ``` ``` -------------------------------- ### Run rust-libp2p Examples with Cargo Source: https://github.com/libp2p/rust-libp2p/blob/master/examples/README.md This snippet shows the basic command to navigate to an example directory and run it using Cargo. It assumes Rust and Cargo are installed and that the user is in the root of the rust-libp2p project. ```shell cd examples/ping # Run the example cargo run ``` -------------------------------- ### Kademlia DHT Bootstrap and Record Storage Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/05-protocols-overview.md Example demonstrating how to initialize the Kademlia Behaviour, start the DHT bootstrap process, and store a record. ```rust use libp2p::kad::{Behaviour, Config, store::MemoryStore}; let mut behaviour = Behaviour::new(local_peer_id); // Start DHT bootstrap if let Some(query_id) = behaviour.bootstrap() { println!("Bootstrap started: {:?}", query_id); } // Store a record use libp2p::kad::{Record, RecordKey}; let key = RecordKey::new(&b"my-key"[..]); let record = Record { key: key.clone(), value: b"my-value".to_vec(), publisher: Some(local_peer_id), expires_at: None, }; behaviour.put_record(record)?; ``` -------------------------------- ### Example: Configure SwarmBuilder with DNS Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/01-swarmbuilder.md Example of initializing SwarmBuilder with default DNS resolver configuration. ```rust let builder = SwarmBuilder::with_new_identity() .with_tokio() .with_dns_config( libp2p_dns::ResolverConfig::default(), libp2p_dns::ResolverOpts::default(), ); ``` -------------------------------- ### Complete Transport Example in Rust Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/03-transport.md Demonstrates how to set up a transport, start listening on an address, and initiate a dial to a remote peer. Requires the `libp2p_core`, `futures`, and `multiaddr` crates. ```rust use libp2p_core:: Transport, transport::{DialOpts, ListenerId, TransportEvent}, muxing::StreamMuxerBox, Multiaddr; use futures::stream::StreamExt; use std::pin::Pin; use libp2p_identity::PeerId; async fn handle_transport( mut transport: T, local_peer_id: PeerId, ) -> Result<(), Box> where T::Output: Unpin, T::Dial: Unpin, T::ListenerUpgrade: Unpin, { // Start listening let listener_id = ListenerId::next(); use multiaddr::multiaddr; transport.listen_on( listener_id, multiaddr!(Ip4([127, 0, 0, 1]), Tcp(0)) )?; // Dial a remote peer let remote_addr = multiaddr!(Ip4([192, 0, 2, 1]), Tcp(30333)); let dial_future = transport.dial(remote_addr, DialOpts::default())?; // Wait for dial to complete let _output = dial_future.await?; println!("Connected!"); Ok(()) } ``` -------------------------------- ### Run rust-libp2p server with configuration Source: https://github.com/libp2p/rust-libp2p/blob/master/misc/server/README.md Demonstrates how to execute the server binary using Cargo. The first example displays the help menu for available CLI options, while the second shows how to start the server with a specific IPFS configuration file. ```bash cargo run -- --help ``` ```bash cargo run -- --config ~/.ipfs/config ``` -------------------------------- ### Example: Configure SwarmBuilder with Dummy Transport Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/01-swarmbuilder.md Example of adding a dummy transport to the SwarmBuilder. ```rust let builder = SwarmBuilder::with_new_identity() .with_tokio() .with_other_transport(|_key| { Ok(libp2p_core::transport::dummy::DummyTransport::new()) })?; ``` -------------------------------- ### Start the WebRTC Server Source: https://github.com/libp2p/rust-libp2p/blob/master/examples/browser-webrtc/README.md Run this command to start the libp2p WebRTC server. Open the printed URL in your browser. ```shell cargo run ``` -------------------------------- ### Example: Configure SwarmBuilder with WebSocket Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/01-swarmbuilder.md Example of setting up SwarmBuilder with WebSocket transport using libp2p-tls and libp2p-yamux. ```rust let builder = SwarmBuilder::with_new_identity() .with_tokio() .with_websocket( libp2p_tls::Config::new, libp2p_yamux::Config::default, ) .await?; ``` -------------------------------- ### Example: Configure SwarmBuilder with Relay Client Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/01-swarmbuilder.md Example of adding relay client support after configuring TCP transport. ```rust let builder = SwarmBuilder::with_new_identity() .with_tokio() .with_tcp(Default::default(), libp2p_tls::Config::new, libp2p_yamux::Config::default)? .with_relay_client(libp2p_tls::Config::new, libp2p_yamux::Config::default)?; ``` -------------------------------- ### Complete Rust Libp2p Swarm Example Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/02-swarm.md A full example of setting up a libp2p Swarm with TCP transport, TLS, and Yamux, then listening for connections and handling events. ```rust use libp2p::{SwarmBuilder, swarm::NetworkBehaviour}; use futures::StreamExt; #[derive(NetworkBehaviour)] #[behaviour(prelude = "libp2p_swarm::derive_prelude")] struct MyBehaviour; #[tokio::main] async fn main() -> Result<(), Box> { let mut swarm = SwarmBuilder::with_new_identity() .with_tokio() .with_tcp( Default::default(), libp2p_tls::Config::new, libp2p_yamux::Config::default, )? .with_behaviour(|_| Ok(MyBehaviour))? .build(); // Start listening use multiaddr::multiaddr; swarm.listen_on(multiaddr!(Ip4([127, 0, 0, 1]), Tcp(0)))?; // Poll events loop { match swarm.next().await { Some(swarm::SwarmEvent::NewListenAddr { address, .. }) => { println!("Listening on {}", address); } Some(swarm::SwarmEvent::ConnectionEstablished { peer_id, .. }) => { println!("Connected to {}", peer_id); } Some(swarm::SwarmEvent::ConnectionClosed { peer_id, .. }) => { println!("Disconnected from {}", peer_id); } _ => {} } } } ``` -------------------------------- ### Run libp2p UPnP example Source: https://github.com/libp2p/rust-libp2p/blob/master/examples/upnp/README.md Executes the libp2p UPnP example using Cargo. The command initializes the swarm and attempts to map a port on the local network gateway, outputting the external address or a gateway error. ```sh cargo run ``` -------------------------------- ### Identify Protocol Example Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/05-protocols-overview.md Example demonstrating how to initialize the Identify behaviour and handle received peer information within the libp2p event loop. ```APIDOC ## Example Usage ### Purpose Illustrates how to set up and use the Identify behaviour in a libp2p application. ### Code ```rust use libp2p::{SwarmBuilder, identify::{Behaviour, Config}}; // Initialize the Identify behaviour let identify_behaviour = Behaviour::new(local_peer_id) .with_protocol_version("my-app/1.0.0") .with_agent_version("my-agent/1.0.0"); // In your libp2p event loop: // match event { // SwarmEvent::Behaviour(identify::Event::Received { peer_id, info }) => { // println!("Peer {{}} supports: {{:?}}", peer_id, info.protocols); // println!("Observed address: {{}}", info.observed_addr); // } // _ => {{}} // } ``` ``` -------------------------------- ### Initialize and Run Rust Libp2p WebRTC Example in Browser Source: https://github.com/libp2p/rust-libp2p/blob/master/examples/browser-webrtc/static/index.html This JavaScript code initializes the Rust libp2p WebRTC module and runs an example. It requires the './browser_webrtc_example.js' module to be present. The `run` function takes a libp2p endpoint as an argument, which is dynamically replaced by the server at runtime. ```javascript import init, { run } from "./browser_webrtc_example.js" await init(); run("__LIBP2P_ENDPOINT__"); ``` -------------------------------- ### Example: Configure SwarmBuilder with Custom Behaviour Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/01-swarmbuilder.md Example of configuring SwarmBuilder with a custom network behaviour that includes relay client. ```rust use libp2p::swarm::NetworkBehaviour; #[derive(NetworkBehaviour)] #[behaviour(prelude = "libp2p_swarm::derive_prelude")] struct MyBehaviour { relay: libp2p_relay::client::Behaviour, } let builder = SwarmBuilder::with_new_identity() .with_tokio() .with_tcp(Default::default(), libp2p_tls::Config::new, libp2p_yamux::Config::default)? .with_behaviour(|_key, relay| { Ok(MyBehaviour { relay }) })?; ``` -------------------------------- ### Code Examples Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/MANIFEST.txt A variety of code examples are provided to illustrate usage and facilitate implementation. ```APIDOC ## Code Examples ### Description Over 50 code examples are available: - Complete runnable examples: 5 - Snippet examples: 45+ - All examples include error handling ``` -------------------------------- ### Relay Client Behaviour Initialization Example Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/05-protocols-overview.md Demonstrates how to initialize the `Behaviour` for the relay client and compose it within a `NetworkBehaviour`. ```rust use libp2p::relay::client::Behaviour; let relay_behaviour = Behaviour::new(Default::default()); // The behaviour is typically composed with other behaviors: #[derive(NetworkBehaviour)] #[behaviour(prelude = "libp2p_swarm::derive_prelude")] struct MyBehaviour { relay: Behaviour, } ``` -------------------------------- ### Build Client Library with wasm-pack Source: https://github.com/libp2p/rust-libp2p/blob/master/examples/browser-webrtc/README.md Use this command to build the client library for web deployment. Ensure wasm-pack is installed. ```shell wasm-pack build --target web --out-dir static ``` -------------------------------- ### Example: Aggressive Swarm Configuration Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/09-configuration-reference.md Demonstrates creating a Swarm configuration with aggressive settings for higher throughput and concurrency. ```rust let config = Config::new() .with_idle_connection_timeout(Duration::from_secs(300)) .with_dial_concurrency_factor(NonZeroU8::new(16).unwrap()) .with_notify_handler_buffer_size(NonZeroUsize::new(32).unwrap()) .with_per_connection_event_buffer_size(32) .with_max_negotiating_inbound_streams(256); ``` -------------------------------- ### Rust Libp2p Swarm Configuration Example Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/02-swarm.md Demonstrates setting idle connection timeout and dial concurrency factor for the Swarm configuration. ```rust use libp2p_swarm::Config; use std::time::Duration; let config = Config::default() .with_idle_connection_timeout(Duration::from_secs(30)) .with_dial_concurrency_factor(std::num::NonZeroU8::new(8).unwrap()); ``` -------------------------------- ### Build Swarm with DNS Transport Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/06-transports-overview.md Example of building a libp2p Swarm with DNS transport enabled. ```rust use libp2p::SwarmBuilder; let swarm = SwarmBuilder::with_new_identity() .with_tokio() .with_tcp(Default::default(), libp2p_tls::Config::new, libp2p_yamux::Config::default)? .with_dns()? .await?; ``` -------------------------------- ### Usage Guide Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/MANIFEST.txt Guidance on how to navigate and utilize the documentation effectively. ```APIDOC ## Usage Guide **Getting Started:** 1. README.md (index and quick navigation) 2. 01-swarmbuilder.md (getting started) 3. 02-swarm.md (main event loop) 4. 05-protocols-overview.md or 06-transports-overview.md (specific features) **Deep Dives:** - 03-transport.md (lower-level transport abstraction) - 04-networkbehaviour.md (custom protocol implementation) - 10-module-structure.md (architecture and design) - 11-common-patterns.md (practical patterns and recipes) ``` -------------------------------- ### Example: Conservative Swarm Configuration Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/09-configuration-reference.md Demonstrates creating a Swarm configuration with conservative settings for lower resource usage and stricter timeouts. ```rust use libp2p::swarm::Config; use std::time::Duration; use std::num::NonZeroUsize; let config = Config::new() .with_idle_connection_timeout(Duration::from_secs(30)) .with_dial_concurrency_factor(NonZeroU8::new(4).unwrap()) .with_notify_handler_buffer_size(NonZeroUsize::new(4).unwrap()) .with_per_connection_event_buffer_size(4) .with_max_negotiating_inbound_streams(64); ``` -------------------------------- ### Gossipsub Example Usage Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/05-protocols-overview.md Demonstrates how to initialize the Gossipsub behaviour, subscribe to a topic, handle incoming messages, and publish a message within an event loop. ```rust use libp2p::gossipsub::{Behaviour, Config, MessageAuthenticity, TopicHash}; let behaviour = Behaviour::new( MessageAuthenticity::Signed(local_keys), Config::default(), )?; let topic = TopicHash::from_raw("my-topic"); // In event loop: match event { SwarmEvent::Behaviour(gossipsub::Event::Message { propagation_source, message_id, message, }) => { println!("Received from {:?}: {:?}", propagation_source, message.data); } _ => {} } // Publish a message (requires mutable access) swarm.behaviour_mut().publish(topic, b"hello world".to_vec())?; ``` -------------------------------- ### Minimal libp2p Swarm Configuration Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/09-configuration-reference.md Set up a basic libp2p Swarm with a new identity, Tokio runtime, and QUIC transport. This is a starting point for simple applications. ```rust use libp2p::SwarmBuilder; let swarm = SwarmBuilder::with_new_identity() .with_tokio() .with_quic()? .with_behaviour(|_| Ok(MyBehaviour))? .build(); ``` -------------------------------- ### Create UDS Transport Instance Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/06-transports-overview.md Example of creating a UDS transport instance. ```rust use libp2p::uds::Config; let uds_transport = libp2p_uds::Transport::new(Config::new()); ``` -------------------------------- ### Configure TCP Transport with Custom Options Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/09-configuration-reference.md Example of creating and configuring a TCP transport for a libp2p swarm, setting TTL, Nagle's algorithm, and backlog. ```rust use libp2p::tcp::Config; let mut config = Config::new(); config.ttl(64); // Cross-subnet communication config.nodelay(true); // Disable Nagle for low latency config.backlog(2048); // Larger listen queue let swarm = SwarmBuilder::with_new_identity() .with_tokio() .with_tcp(config, libp2p_tls::Config::new, libp2p_yamux::Config::default)?; ``` -------------------------------- ### Start Listening on an Address Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/03-transport.md Initiates listening for inbound connections on a specified multi-address. Requires a unique listener identifier. ```rust use libp2p_core::transport::ListenerId; use multiaddr::multiaddr; let id = ListenerId::next(); transport.listen_on(id, multiaddr!(Ip4([0, 0, 0, 0]), Tcp(30333)))?; ``` -------------------------------- ### listen_on Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/03-transport.md Starts listening for inbound connections on a specified address with a unique listener identifier. ```APIDOC ## listen_on ### Description Starts listening for inbound connections on the given address. ### Method `listen_on` ### Parameters #### Path Parameters - **id** (ListenerId) - Required - Unique listener identifier - **addr** (Multiaddr) - Required - Address to listen on ### Returns - `Result<(), TransportError>` — Success or transport error ### Errors - `TransportError::MultiaddrNotSupported` — Address format not supported - `TransportError::Other` — I/O or binding error ### Emits Events - `TransportEvent::NewAddress` — After successful binding - `TransportEvent::ListenerClosed` — When listener closes ### Example ```rust use libp2p_core::transport::ListenerId; use multiaddr::multiaddr; let id = ListenerId::next(); transport.listen_on(id, multiaddr!(Ip4([0, 0, 0, 0]), Tcp(30333)))?; ``` ``` -------------------------------- ### Kademlia Key Methods Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/05-protocols-overview.md Core methods for interacting with the Kademlia DHT, including getting and putting records, bootstrapping, and finding providers. ```rust pub fn get_record(&mut self, key: RecordKey) -> Option pub fn put_record(&mut self, record: Record) -> Result pub fn bootstrap(&mut self) -> Option pub fn start_providing(&mut self, key: RecordKey) -> Result pub fn get_providers(&mut self, key: RecordKey) -> Option ``` -------------------------------- ### Configure QUIC Transport with Custom Idle Timeout Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/09-configuration-reference.md Example of creating a QUIC transport for a libp2p swarm with a custom maximum idle timeout. ```rust use libp2p::quic::Config; use std::time::Duration; let config = Config::new() .with_max_idle_timeout(Duration::from_secs(30)); let swarm = SwarmBuilder::with_new_identity() .with_tokio() .with_quic()?; ``` -------------------------------- ### Build Browser-Based WebRTC Node Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/10-module-structure.md Initialize a libp2p Swarm for browser environments using WebRTC and WASM. This example utilizes a WASM executor and the WebSockets transport. ```rust use libp2p::SwarmBuilder; let swarm = SwarmBuilder::with_new_identity() .with_wasm_executor() .with_webrtc_websys()? .with_behaviour(|_| Ok(MyBehaviour))? .build(); ``` -------------------------------- ### TCP Transport Initialization with SwarmBuilder Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/06-transports-overview.md Demonstrates how to initialize the TCP transport and integrate it into a `SwarmBuilder` along with security and multiplexer configurations. This is a common setup for creating a libp2p node. ```rust use libp2p::tcp::Config; let tcp_config = Config::new(); let tcp_transport = libp2p::tcp::Transport::new(tcp_config); // Usage in SwarmBuilder: let swarm = SwarmBuilder::with_new_identity() .with_tokio() .with_tcp( tcp_config, libp2p_tls::Config::new, // Security libp2p_yamux::Config::default, // Multiplexer )?; ``` -------------------------------- ### Unit Test with Memory Transport in Rust Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/11-common-patterns.md Demonstrates setting up a basic unit test using the MemoryTransport for in-memory libp2p connections. This is a simplified example; actual tests would involve constructing a full Swarm. ```rust #[cfg(test)] mod tests { use super::*; use libp2p_core::transport::memory::MemoryTransport; #[tokio::test] async fn test_basic_connection() { let transport = MemoryTransport::new(); // Would use SwarmBuilder with memory transport // This is simplified; actual test would fully construct swarm } } ``` -------------------------------- ### Minimal P2P Echo Server Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/11-common-patterns.md A basic libp2p application that sets up a swarm, listens for incoming connections, and prints connection events. It's a starting point for building P2P applications. ```rust use libp2p::{SwarmBuilder, swarm::NetworkBehaviour, StreamProtocol}; use futures::StreamExt; use multiaddr::multiaddr; #[derive(NetworkBehaviour)] #[behaviour(prelude = "libp2p_swarm::derive_prelude")] struct MyBehaviour; #[tokio::main] async fn main() -> Result<(), Box> { // Build swarm let mut swarm = SwarmBuilder::with_new_identity() .with_tokio() .with_tcp( Default::default(), libp2p_tls::Config::new, libp2p_yamux::Config::default, )? .with_behaviour(|_| Ok(MyBehaviour))? .build(); // Start listening swarm.listen_on(multiaddr!(Ip4([127, 0, 0, 1]), Tcp(0)))?; println!("Local peer ID: {}", swarm.local_peer_id()); // Event loop loop { match swarm.next().await { Some(swarm::SwarmEvent::NewListenAddr { address, .. }) => { println!("Listening on {}", address); } Some(swarm::SwarmEvent::ConnectionEstablished { peer_id, .. }) => { println!("Connected to {}", peer_id); } Some(swarm::SwarmEvent::ConnectionClosed { peer_id, .. }) => { println!("Disconnected from {}", peer_id); } _ => {} } } } ``` -------------------------------- ### Build DHT-Based Discovery Network Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/10-module-structure.md Construct a libp2p Swarm for DHT-based discovery using Kademlia. This example includes TCP transport, TLS, Yamux, and QUIC. ```rust use libp2p::{SwarmBuilder, kad::Behaviour as KadBehaviour}; let behaviour = KadBehaviour::new(local_peer_id); let swarm = SwarmBuilder::with_new_identity() .with_tokio() .with_tcp(Default::default(), libp2p_tls::Config::new, libp2p_yamux::Config::default)? .with_quic()? .with_behaviour(|_| Ok(behaviour))? .build(); ``` -------------------------------- ### Start Listening on an Address Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/02-swarm.md Call `listen_on` to begin accepting inbound connections on a specified network address. Ensure the address is supported by the transport layer to avoid errors. ```rust pub fn listen_on(&mut self, addr: Multiaddr) -> Result> ``` ```rust use multiaddr::multiaddr; let listener_id = swarm.listen_on(multiaddr!(Ip4([127, 0, 0, 1]), Tcp(30333)))?; println!("Listening with ID: {}", listener_id); ``` -------------------------------- ### Configure OpenTelemetry and Tracing Source: https://github.com/libp2p/rust-libp2p/blob/master/examples/metrics/README.md Commands to start the OpenTelemetry collector and configure environment variables for tracing libp2p swarm activity. ```shell docker compose up export RUST_LOG=info,[ConnectionHandler::poll]=trace,[NetworkBehaviour::poll]=trace ``` -------------------------------- ### DHT Bootstrap Node Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/11-common-patterns.md An example of a libp2p node configured to act as a bootstrap node for a Distributed Hash Table (DHT). It listens on both TCP and QUIC protocols. ```rust use libp2p::{SwarmBuilder, kad::Behaviour as KadBehaviour}; use futures::StreamExt; use multiaddr::multiaddr; #[tokio::main] async fn main() -> Result<(), Box> { let mut swarm = SwarmBuilder::with_new_identity() .with_tokio() .with_tcp( Default::default(), libp2p_tls::Config::new, libp2p_yamux::Config::default, )? .with_quic()? .with_behaviour(|_| { Ok(KadBehaviour::new(*swarm.local_peer_id())) })? .build(); // Listen on all interfaces swarm.listen_on(multiaddr!(Ip4([0, 0, 0, 0]), Tcp(0)))?; swarm.listen_on(multiaddr!(Ip4([0, 0, 0, 0]), Quic(0)))?; println!("Bootstrap node started: {}", swarm.local_peer_id()); loop { match swarm.next().await { Some(swarm::SwarmEvent::NewListenAddr { address, .. }) => { println!("Listening on {}", address); } Some(swarm::SwarmEvent::Behaviour(event)) => { println!("Kademlia event: {:?}", event); } _ => {} } } } ``` -------------------------------- ### Initialize Swarm with QUIC Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/06-transports-overview.md Initializes a libp2p Swarm with the QUIC transport. Ensure the necessary dependencies are included. ```rust use libp2p::SwarmBuilder; let swarm = SwarmBuilder::with_new_identity() .with_tokio() .with_quic()?; ``` -------------------------------- ### Request-Response Codec Implementation Example Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/05-protocols-overview.md An example implementation of the `RequestResponseCodec` trait for handling byte vector requests and responses using length-prefixed framing. ```rust use libp2p::request_response::{Behaviour, Config, ProtocolSupport}; use libp2p_core::upgrade::read_length_prefixed; pub struct MyCodec; impl RequestResponseCodec for MyCodec { type Protocol = String; type Request = Vec; type Response = Vec; async fn read_request( &self, _protocol: &Self::Protocol, io: &mut impl AsyncRead + Unpin, ) -> io::Result { read_length_prefixed(io, 1024).await.map(|vec| vec.into()) } async fn write_request( &self, _protocol: &Self::Protocol, io: &mut impl AsyncWrite + Unpin, data: Self::Request, ) -> io::Result<()> { write_length_prefixed(io, data).await } async fn read_response( &self, _protocol: &Self::Protocol, io: &mut impl AsyncRead + Unpin, ) -> io::Result { read_length_prefixed(io, 1024).await.map(|vec| vec.into()) } async fn write_response( &self, _protocol: &Self::Protocol, io: &mut impl AsyncWrite + Unpin, data: Self::Response, ) -> io::Result<()> { write_length_prefixed(io, data).await } } ``` -------------------------------- ### Transport Error Type Example Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/03-transport.md Shows an example of defining the `Error` associated type for a transport, specifying `std::io::Error` for a TCP transport, indicating potential I/O-related failures. ```rust impl Transport for TcpTransport { type Error = std::io::Error; // ... } ``` -------------------------------- ### Get Network Information Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/02-swarm.md Retrieves comprehensive network state including local peer ID, connection count, and external addresses. Use this to get an overview of the swarm's status. ```rust let info = swarm.network_info(); println!("Local peer ID: {}", info.local_peer_id); println!("Num connections: {}", info.num_peers()); ``` -------------------------------- ### Get Immutable Swarm Behavior Reference Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/02-swarm.md Use `behaviour` to get an immutable reference to the swarm's network behavior. This is useful for inspecting the current state or capabilities of the behavior without modifying it. ```rust pub fn behaviour(&self) -> &TBehaviour ``` ```rust let protocol_info = swarm.behaviour().some_info(); ``` -------------------------------- ### Basic Libp2p Dependency with Full Features Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/10-module-structure.md This snippet shows how to include the libp2p crate with the 'full' feature enabled, which includes all available features. Use this for development or when all functionalities are required. ```toml [dependencies] libp2p = { version = "0.57", features = ["full"] } ``` -------------------------------- ### Handling ListenError Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/08-errors-reference.md Example of how to match and handle ListenError when calling listen_on. ```rust match swarm.listen_on(addr) { Ok(listener_id) => println!("Listening: {:?}", listener_id), Err(e) => eprintln!("Listen failed: {}", e), } ``` -------------------------------- ### Minimal QUIC Transport Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/06-transports-overview.md Sets up a libp2p swarm using only the QUIC transport. This is the simplest configuration. ```rust let swarm = SwarmBuilder::with_new_identity() .with_tokio() .with_quic()? .with_behaviour(|_| Ok(MyBehaviour))? .build(); ``` -------------------------------- ### Handling TransportError Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/08-errors-reference.md Example of how to match and handle TransportError, specifically MultiaddrNotSupported and Other variants. ```rust use libp2p_core::transport::TransportError; match result { Err(TransportError::MultiaddrNotSupported(addr)) => { eprintln!("Transport does not support: {}", addr); } Err(TransportError::Other(e)) => { eprintln!("Transport error: {}", e); } Ok(_) => {} } ``` -------------------------------- ### Handling DialError Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/08-errors-reference.md Example of how to match and handle different DialError variants when initiating a connection. ```rust use libp2p::swarm::DialError; match swarm.dial(dial_opts) { Ok(()) => println!("Dial initiated"), Err(DialError::NoAddresses) => eprintln!("No addresses to dial"), Err(DialError::LocalPeerId) => eprintln!("Cannot dial self"), Err(DialError::InvalidAddress(_)) => eprintln!("Invalid address format"), Err(DialError::DialInProgress) => eprintln!("Already dialing this peer"), Err(DialError::DialFailed { errors, .. }) => { eprintln!("Dial failed with {} errors", errors.len()); } } ``` -------------------------------- ### Full Transport Stack (TCP, QUIC, WebSocket, DNS, Relay) Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/06-transports-overview.md Sets up a comprehensive libp2p swarm including TCP, QUIC, WebSocket, DNS resolution, and Relay client functionality. This configuration offers maximum connectivity options. ```rust let swarm = SwarmBuilder::with_new_identity() .with_tokio() .with_tcp( Default::default(), (libp2p_tls::Config::new, libp2p_noise::Config::new), libp2p_yamux::Config::default, )? .with_quic()? .with_dns()? .await? .with_websocket( libp2p_tls::Config::new, libp2p_yamux::Config::default, ) .await? .with_relay_client( libp2p_tls::Config::new, libp2p_yamux::Config::default, )? .with_behaviour(|_, relay| Ok(MyBehaviour { relay }))? .build(); ``` -------------------------------- ### Initialize and Use Ping Behaviour Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/05-protocols-overview.md Demonstrates how to create a Ping behaviour with custom intervals and timeouts, and how to handle ping events in the main event loop. ```rust use libp2p::{SwarmBuilder, ping::{Behaviour, Config}}; let behaviour = Behaviour::new( Config::new() .with_interval(Duration::from_secs(30)) .with_timeout(Duration::from_secs(10)) ); // In event loop: match event { SwarmEvent::Behaviour(ping::Event { peer, result, .. }) => { match result { Ok(rtt) => println!("Ping to {}: {}ms", peer, rtt.as_millis()), Err(e) => println!("Ping failed: {:?}", e), } } _ => {} } ``` -------------------------------- ### Handling ConnectionError Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/08-errors-reference.md Example of how to match and handle ConnectionError variants when a connection event indicates closure. ```rust match swarm_event { SwarmEvent::ConnectionClosed { cause: Some(err), peer_id, .. } => { match err { ConnectionError::IO(io_err) => { eprintln!("I/O error from {}: {}", peer_id, io_err); } ConnectionError::KeepAliveTimeout => { eprintln!("Connection to {} timed out", peer_id); // Attempt to reconnect } _ => eprintln!("Connection error: {:?}", err), } } _ => {} } ``` -------------------------------- ### and_then Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/03-transport.md Applies an asynchronous post-processing function to connections after they are established. This is useful for additional protocol negotiation or setup. ```APIDOC ## and_then ### Description Applies an async post-processing function to connections. ### Returns - `AndThen` — Transport with post-processing ### Example ```rust let processed = transport.and_then(|output, endpoint| async move { // Additional protocol negotiation Ok(output) }); ``` ``` -------------------------------- ### Perform Sequential Socket I/O with async/await Source: https://github.com/libp2p/rust-libp2p/blob/master/docs/coding-guidelines.md Demonstrates the recommended approach for sequential socket operations using async/await syntax to maintain simplicity. ```rust socket.read_exact(&mut read_buf).await; socket.write(&write_buf).await; ``` -------------------------------- ### Swarm Configuration Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/07-types-reference.md Shows how to create and configure a libp2p Swarm using the Config builder pattern. ```APIDOC ## Config ### Description Configuration for `Swarm` behavior and event handling. ### Methods - `new()`: Creates a new `Config` with default values. - `with_executor(executor)`: Sets a custom executor for the swarm. - `without_executor()`: Configures the swarm to not use an executor. - `with_wasm_executor()`: Configures the swarm to use a WASM-compatible executor. - `with_tokio_executor()`: Configures the swarm to use a Tokio executor. - `with_idle_connection_timeout(timeout)`: Sets the duration after which idle connections are closed. - `with_dial_concurrency_factor(factor)`: Sets the maximum number of concurrent outgoing connection attempts. - `with_per_connection_event_buffer_size(size)`: Sets the buffer size for events per connection. ### Example ```rust use libp2p_swarm::Config; use std::time::Duration; let config = Config::new() .with_idle_connection_timeout(Duration::from_secs(30)) .with_dial_concurrency_factor(std::num::NonZeroU8::new(8).unwrap()); ``` ``` -------------------------------- ### Initialize Mplex Muxer Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/06-transports-overview.md Instantiate the default Mplex configuration. ```rust let muxer = libp2p_mplex::Config::default(); ``` -------------------------------- ### Accessing Swarm Behavior Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/02-swarm.md Provides methods to get immutable or mutable references to the swarm's network behavior. ```APIDOC ## behaviour ### Description Returns an immutable reference to the swarm's network behavior. ### Returns - `&TBehaviour` — Reference to the behavior ### Example ```rust let protocol_info = swarm.behaviour().some_info(); ``` ## behaviour_mut ### Description Returns a mutable reference to the swarm's network behavior. ### Returns - `&mut TBehaviour` — Mutable reference to the behavior ### Example ```rust swarm.behaviour_mut().update_state(); ``` ``` -------------------------------- ### Minimal libp2p Feature Flags Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/README.md Use this configuration for a minimal build, including only essential features like TCP, noise encryption, yamux multiplexing, and the ping protocol. ```toml libp2p = { version = "0.57", features = ["tcp", "noise", "yamux", "ping"] } ``` -------------------------------- ### Get Local Peer ID Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/02-swarm.md Returns the unique identifier for the local peer in the swarm. This is essential for identifying your node on the network. ```rust let peer_id = swarm.local_peer_id(); println!("My peer ID: {}", peer_id); ``` -------------------------------- ### Relay Client Behaviour Key Methods Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/05-protocols-overview.md Methods for interacting with the Relay client. `reserve` initiates a reservation, and `connect` establishes a relayed connection. ```rust pub fn reserve(&mut self) -> Result<(), ()> pub fn connect(&mut self, relay_addr: Multiaddr, dest_addr: Multiaddr) -> Result<(), ()> ``` -------------------------------- ### Run libp2p nodes and retrieve metrics Source: https://github.com/libp2p/rust-libp2p/blob/master/examples/metrics/README.md Commands to initialize libp2p nodes and fetch performance metrics via HTTP. Requires a running node to expose the metrics endpoint. ```sh cargo run cargo run -- curl localhost:/metrics ``` -------------------------------- ### Initiate Outbound Connection Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/03-transport.md Starts an outbound connection to a given multi-address with specified dial options. The returned future begins work only when polled. ```rust use libp2p_core::transport::DialOpts; use multiaddr::multiaddr; use futures::future::Future; let addr = multiaddr!(Ip4([192, 0, 2, 1]), Tcp(30333)); let dial_future = transport.dial(addr, DialOpts::default())?; // Race multiple dials concurrently let output = dial_future.await?; ``` -------------------------------- ### Build Libp2p Swarm with SwarmBuilder Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/01-swarmbuilder.md This snippet shows the complete process of building a libp2p swarm with multiple transports and behaviors. It configures TCP, QUIC, DNS, and a relay client, and sets an idle connection timeout. Ensure you have the necessary libp2p crates added to your Cargo.toml. ```rust use libp2p::{SwarmBuilder, swarm::NetworkBehaviour}; use std::time::Duration; #[derive(NetworkBehaviour)] #[behaviour(prelude = "libp2p_swarm::derive_prelude")] struct MyNetworkBehaviour { relay: libp2p_relay::client::Behaviour, } #[tokio::main] async fn main() -> Result<(), Box> { let mut swarm = SwarmBuilder::with_new_identity() .with_tokio() .with_tcp( Default::default(), (libp2p_tls::Config::new, libp2p_noise::Config::new), libp2p_yamux::Config::default, )? .with_quic()? .with_dns()? .await? .with_relay_client( libp2p_tls::Config::new, libp2p_yamux::Config::default, )? .with_behaviour(|_key, relay| { Ok(MyNetworkBehaviour { relay }) })? .with_swarm_config(|cfg| { cfg.with_idle_connection_timeout(Duration::from_secs(30)) }) .build(); // Use swarm... Ok(()) } ``` -------------------------------- ### Create SwarmBuilder with New Identity Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/01-swarmbuilder.md Initializes a SwarmBuilder with a randomly generated Ed25519 keypair and the Tokio executor. This is the starting point for building a Swarm. ```rust use libp2p::SwarmBuilder; let builder = SwarmBuilder::with_new_identity(); ``` -------------------------------- ### Add Default QUIC Transport Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/01-swarmbuilder.md Adds QUIC transport with default TLS security and Yamux multiplexing. This is a convenient method for common QUIC setups. ```rust let builder = SwarmBuilder::with_new_identity() .with_tokio() .with_quic()?; ``` -------------------------------- ### TCP Transport Constructor Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/06-transports-overview.md Provides the constructor for creating a new TCP transport instance. This is a basic setup; further configuration is done via the `Config` struct. ```rust pub fn new(config: Config) -> Transport ``` -------------------------------- ### Build Pub/Sub Messaging Network Source: https://github.com/libp2p/rust-libp2p/blob/master/_autodocs/10-module-structure.md Create a libp2p Swarm for Pub/Sub messaging using Gossipsub. This setup uses TCP transport, TLS, and Yamux. ```rust use libp2p::{SwarmBuilder, gossipsub::{Behaviour, MessageAuthenticity}}; let behaviour = Behaviour::new( MessageAuthenticity::Signed(local_keys), Default::default(), )?; let swarm = SwarmBuilder::with_new_identity() .with_tokio() .with_tcp(Default::default(), libp2p_tls::Config::new, libp2p_yamux::Config::default)? .with_behaviour(|_| Ok(behaviour))? .build(); ```