Hi, I’m new to libp2p-rs and I’m building p2p protocol and I need help with creating network behavior.
What do I need?
I need to have struct and impl in rust with swarm so I can launch a node and peers can connect to it and like this EG. let node = p2p::node_init();
And in some other function do like node.broadcast(&encoded_message)
For my network behavior I just need send_message, broadcast message and message handler. Do you think you can help me?
I want to thank you in advance as I think this is the best rust p2p lib
Code I have:
use libp2p::{
futures::StreamExt,
identity,
mdns::{Mdns, MdnsConfig, MdnsEvent},
swarm::{Swarm, SwarmEvent},
PeerId,
};
use std::error::Error;
pub async fn start() -> Result<(), Box<dyn Error>> {
let id_keys = identity::Keypair::generate_ed25519();
let peer_id = PeerId::from(id_keys.public());
println!("Local peer id: {:?}", peer_id);
let transport = libp2p::development_transport(id_keys).await?;
let behaviour = Mdns::new(MdnsConfig::default()).await?;
let mut swarm = Swarm::new(transport, behaviour, peer_id);
swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;
loop {
match swarm.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } => {
println!("Listening on local address {:?}", address)
}
SwarmEvent::Behaviour(MdnsEvent::Discovered(peers)) => {
for (peer, addr) in peers {
println!("discovered {} {}", peer, addr);
}
}
SwarmEvent::Behaviour(MdnsEvent::Expired(expired)) => {
for (peer, addr) in expired {
println!("expired {} {}", peer, addr);
}
}
_ => {}
}
}
}