Essential libp2p
Setup network identity
A local node in the network must have a network identity. Identityies are handled with public/private key pairs and nodes identify each other with their PeerId
(a hash derived from their public key).
use libp2p::{identity, PeerId};
use std::error::Error;
#[async_std::main]
async fn main() -> Result<(), Box<dyn Error>> {
let local_key = identity::Keypair::generate_ed25519(); -> Keypair
let local_peer_id = PeerId::from(local_key.public()); -> PeerId
println!("Local peer id: {:?}", local_peer_id);
Ok(())
}
use libp2p::{identity, PeerId};
use std::error::Error;
#[async_std::main]
async fn main() -> Result<(), Box<dyn Error>> {
let local_key = identity::Keypair::generate_ed25519(); -> Keypair
let local_peer_id = PeerId::from(local_key.public()); -> PeerId
println!("Local peer id: {:?}", local_peer_id);
Ok(())
}
Setup transport
The transport is the communication channel (e.g. TCP, UDP) that is used to transmit data over the wire and any additional transport protocols needed for security and authentication. In libp2p, a transport is anything that implements the Transport
trait. The tranport specifies how to send data bytes on the network. ![[Pasted image 20221110160228.png]] ![[Pasted image 20221110160255.png]]
Network Behaviour
A NetworkBehaviour
defines what bytes to send on the network. See https://docs.rs/libp2p/latest/libp2p/swarm/trait.NetworkBehaviour.html
Swarm (aka Switch)
In libp2p the Swarm connects the two otherwise separate items Transport
and NetworkBehaviour
by passing commands from the NetworkBehaviour to the Transport, and sending events from the Transport to the NetworkBehaviour.
let mut swarm = Swarm::new(transport, behaviour, local_peer_id);
let mut swarm = Swarm::new(transport, behaviour, local_peer_id);
After the Sawrm is created the program is ready to accept incoming connections. To achieve this you have to pass an address to Swarm (like you would a UdpSocket::bind(/* addr */)
call). But instead of a typical socket address you have to use a Multiaddr.
Multiaddr
In libp2p, a Multiaddr is a method of describing network addresses that may take on different forms, may encapsulate different protocols, and may include multiple addresses to multiple peers.
Note
- You can only dial public computers.
TERMS
- Firewall: In computing, a firewall is a network security system that monitors and controls incoming and outgoing network traffic based on predetermined security rules. A firewall typically establishes a barrier between a trusted network and an untrusted network, such as the Internet. Wikipedia ![[Pasted image 20221110210744.png]]
- NAT: Network address translation is a method of mapping an IP address space into another by modifying network address information in the IP header of packets while they are in transit across a traffic routing device. Wikipedia
ADDITIONAL RESOURCES