Implement next-gen modules: chrs-code-edit (Git), chrs-discovery (LibP2P), and chrs-observer (TUI)
This commit is contained in:
69
chrs-discovery/src/lib.rs
Normal file
69
chrs-discovery/src/lib.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
//! chrs-discovery: LibP2P-based peer discovery for CHORUS.
|
||||
|
||||
use libp2p::{
|
||||
mdns,
|
||||
swarm::{NetworkBehaviour, SwarmEvent},
|
||||
gossipsub,
|
||||
};
|
||||
use futures::StreamExt;
|
||||
use std::error::Error;
|
||||
|
||||
#[derive(NetworkBehaviour)]
|
||||
pub struct MyBehaviour {
|
||||
pub mdns: mdns::tokio::Behaviour,
|
||||
pub gossipsub: gossipsub::Behaviour,
|
||||
}
|
||||
|
||||
pub struct SwarmManager;
|
||||
|
||||
impl SwarmManager {
|
||||
/// Initialize a new LibP2P swarm with mDNS discovery.
|
||||
///
|
||||
/// **Why**: Moving away from polling a database to real-time P2P discovery
|
||||
/// reduces latency and allows CHORUS to scale to dynamic, broker-less environments.
|
||||
pub async fn start_discovery_loop() -> Result<(), Box<dyn Error>> {
|
||||
let mut swarm = libp2p::SwarmBuilder::with_new_identity()
|
||||
.with_tokio()
|
||||
.with_tcp(
|
||||
libp2p::tcp::Config::default(),
|
||||
libp2p::noise::Config::new,
|
||||
libp2p::yamux::Config::default,
|
||||
)?
|
||||
.with_behaviour(|key| {
|
||||
let message_id_fn = |message: &gossipsub::Message| {
|
||||
let mut s = std::collections::hash_map::DefaultHasher::new();
|
||||
use std::hash::Hasher;
|
||||
std::hash::Hash::hash(&message.data, &mut s);
|
||||
gossipsub::MessageId::from(s.finish().to_string())
|
||||
};
|
||||
|
||||
let gossipsub_config = gossipsub::ConfigBuilder::default()
|
||||
.message_id_fn(message_id_fn)
|
||||
.build()?;
|
||||
|
||||
Ok(MyBehaviour {
|
||||
mdns: mdns::tokio::Behaviour::new(mdns::Config::default(), key.public().to_peer_id())?,
|
||||
gossipsub: gossipsub::Behaviour::new(
|
||||
gossipsub::MessageAuthenticity::Signed(key.clone()),
|
||||
gossipsub_config,
|
||||
)?,
|
||||
})
|
||||
})?
|
||||
.build();
|
||||
|
||||
swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;
|
||||
|
||||
println!("[DISCOVERY] Swarm started. Listening for peers via mDNS...");
|
||||
|
||||
loop {
|
||||
match swarm.select_next_some().await {
|
||||
SwarmEvent::Behaviour(MyBehaviourEvent::Mdns(mdns::Event::Discovered(list))) => {
|
||||
for (peer_id, _multiaddr) in list {
|
||||
println!("[DISCOVERY] mDNS discovered a new peer: {}", peer_id);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user