//! libp2p P2P Netzwerk-Implementierung use libp2p::tcp::TokioTcpConfig; let transport =…
- Assistant
Hello! How can I assist you today?
- User
- Assistant
- User
ja bitte
- Assistant
- User
ja bitte
- Assistant
Hello! How can I assist you today?
ja bitte
ja bitte
//! libp2p P2P Netzwerk-Implementierung
use libp2p::tcp::TokioTcpConfig;
let transport = TokioTcpConfig::new().nodelay(true)
.upgrade(libp2p::core::upgrade::Version::V1)
.authenticate(
noise::NoiseAuthenticated::xx(&local_key).expect("Noise keygen failed"),
)
.multiplex(yamux::YamuxConfig::default())
.timeout(std::time::Duration::from_secs(20))
.boxed();
use std::collections::HashSet;
use std::time::Duration;
use tokio::time;
use anyhow::Result;
use libp2p::swarm::{NetworkBehaviour, SwarmEvent};
use libp2p::NetworkBehaviour; // für das #[derive(NetworkBehaviour)]
/// Netzwerk-Verhalten für L1VECHAIN #[derive(NetworkBehaviour)] #[behaviour(event_process = true)] pub struct L1VEBehaviour { pub gossipsub: Gossipsub, pub mdns: Mdns, pub identify: Identify, }
/// P2P Node für L1VECHAIN pub struct L1VENode { swarm: Swarm, topics: HashSet, }
impl L1VENode { /// Erstellt einen neuen P2P Node pub async fn new() -> Result { let local_key = libp2p::identity::Keypair::generate_ed25519(); let local_peer_id = PeerId::from(local_key.public());
log::info!("Local peer id: {}", local_peer_id);
// Transport konfigurieren
let transport = tcp::tokio::Transport::new(tcp::Config::default().nodelay(true))
.upgrade(libp2p::core::upgrade::Version::V1)
.authenticate(
noise::NoiseAuthenticated::xx(&local_key)
.expect("Signing libp2p-noise static DH keypair failed."),
)
.multiplex(yamux::YamuxConfig::default())
.timeout(Duration::from_secs(20))
.boxed();
// Gossipsub konfigurieren
let gossipsub_config = gossipsub::GossipsubConfig::default();
.heartbeat_interval(Duration::from_secs(1))
.validation_mode(gossipsub::ValidationMode::Strict)
.build()
.expect("Valid config");
let mut gossipsub = Gossipsub::new(
MessageAuthenticity::Signed(local_key.clone()),
gossipsub_config,
)
.expect("Correct configuration");
// Standard-Topic abonnieren
let topic = Topic::new("l1vechain-general");
gossipsub.subscribe(&topic).unwrap();
// mDNS für lokale Peer-Discovery
let mdns = Mdns::new(mdns::Config::default()).await?;
// Identify für Peer-Information
let identify = Identify::new(IdentifyConfig::new(
"/l1vechain/1.0.0".to_string(),
local_key.public(),
));
let behaviour = L1VEBehaviour {
gossipsub,
mdns,
identify,
};
let swarm = Swarm::new(transport, behaviour, local_peer_id);
Ok(Self {
swarm,
topics: HashSet::new(),
})
}
/// Startet das Listening auf einer Adresse
pub fn listen_on(&mut self, addr: Multiaddr) -> Result<()> {
self.swarm.listen_on(addr)?;
log::info!("Listening on address");
Ok(())
}
/// Verbindet zu einem Remote-Peer
pub fn dial(&mut self, addr: Multiaddr) -> Result<()> {
self.swarm.dial(addr)?;
log::info!("Dialing remote peer");
Ok(())
}
/// Abonniert ein Topic
pub fn subscribe(&mut self, topic_name: &str) -> Result<()> {
let topic = Topic::new(topic_name);
self.swarm.behaviour_mut().gossipsub.subscribe(&topic)?;
self.topics.insert(topic);
log::info!("Subscribed to topic: {}", topic_name);
Ok(())
}
/// Sendet eine Nachricht an ein Topic
pub fn publish(&mut self, topic_name: &str, message: Vec<u8>) -> Result<()> {
let topic = Topic::new(topic_name);
self.swarm.behaviour_mut().gossipsub.publish(topic, message)?;
log::info!("Published message to topic: {}", topic_name);
Ok(())
}
/// Hauptevent-Loop
pub async fn run(&mut self) -> Result<()> {
let mut heartbeat = time::interval(Duration::from_secs(30));
loop {
tokio::select! {
event = self.swarm.next() => {
match event {
SwarmEvent::NewListenAddr { address, .. } => {
log::info!("Listening on {:?}", address);
}
SwarmEvent::Behaviour(event) => {
self.handle_behaviour_event(event).await;
}
SwarmEvent::ConnectionEstablished { peer_id, .. } => {
log::info!("Connection established with {}", peer_id);
}
SwarmEvent::ConnectionClosed { peer_id, .. } => {
log::info!("Connection closed with {}", peer_id);
}
_ => {}
}
}
_ = heartbeat.tick() => {
log::debug!("Heartbeat - Connected peers: {}", self.swarm.connected_peers().count());
}
}
}
}
/// Behandelt Behaviour-Events
async fn handle_behaviour_event(&mut self, event: L1VEBehaviourEvent) {
match event {
L1VEBehaviourEvent::Gossipsub(GossipsubEvent::Message {
propagation_source: _,
message_id: _,
message,
}) => {
log::info!(
"Received message from {}: {}",
message.source.map(|id| id.to_string()).unwrap_or_else(|| "Unknown".to_string()),
String::from_utf8_lossy(&message.data)
);
}
L1VEBehaviourEvent::Gossipsub(GossipsubEvent::Subscribed { peer_id, topic }) => {
log::info!("Peer {} subscribed to topic {}", peer_id, topic);
}
L1VEBehaviourEvent::Gossipsub(GossipsubEvent::Unsubscribed { peer_id, topic }) => {
log::info!("Peer {} unsubscribed from topic {}", peer_id, topic);
}
L1VEBehaviourEvent::Mdns(MdnsEvent::Discovered(list)) => {
for (peer_id, multiaddr) in list {
log::info!("Discovered peer {} at {}", peer_id, multiaddr);
if let Err(e) = self.swarm.dial(multiaddr) {
log::warn!("Failed to dial discovered peer: {}", e);
}
}
}
L1VEBehaviourEvent::Mdns(MdnsEvent::Expired(list)) => {
for (peer_id, multiaddr) in list {
log::info!("Peer {} at {} expired", peer_id, multiaddr);
}
}
L1VEBehaviourEvent::Identify(IdentifyEvent::Received { peer_id, info }) => {
log::info!("Received identify info from {}: {}", peer_id, info.protocol_version);
}
L1VEBehaviourEvent::Identify(IdentifyEvent::Sent { peer_id }) => {
log::debug!("Sent identify info to {}", peer_id);
}
L1VEBehaviourEvent::Identify(IdentifyEvent::Error { peer_id, error }) => {
log::warn!("Identify error with {}: {}", peer_id, error);
}
_ => {}
}
}
/// Gibt die Anzahl verbundener Peers zurück
pub fn connected_peers_count(&self) -> usize {
self.swarm.connected_peers().count()
}
/// Gibt die Liste der verbundenen Peers zurück
pub fn connected_peers(&self) -> Vec<PeerId> {
self.swarm.connected_peers().cloned().collect()
}
/// Gibt die abonnierten Topics zurück
pub fn subscribed_topics(&self) -> Vec<String> {
self.topics.iter().map(|t| t.to_string()).collect()
}
}
/// Hilfsfunktion zum Erstellen eines Standard-Nodes pub async fn create_default_node() -> Result { let mut node = L1VENode::new().await?;
// Standard-Listening-Adresse
let listen_addr = "/ip4/0.0.0.0/tcp/0".parse()?;
node.listen_on(listen_addr)?;
// Standard-Topics abonnieren
node.subscribe("l1vechain-cells")?;
node.subscribe("l1vechain-dag")?;
node.subscribe("l1vechain-consensus")?;
Ok(node)
}
/// Nachrichtentypen für das Netzwerk #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum NetworkMessage { CellUpdate { generation: usize, alive_cells: Vec<(i32, i32)>, sender_id: String, }, DAGUpdate { node_id: String, data: Vec, parents: Vec, }, PeerDiscovery { peer_id: String, capabilities: Vec, }, Heartbeat { peer_id: String, timestamp: u64, }, }
impl NetworkMessage { /// Serialisiert die Nachricht zu Bytes pub fn to_bytes(&self) -> Result<Vec> { Ok(bincode::serialize(self)?) }
/// Deserialisiert Bytes zu einer Nachricht
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
Ok(bincode::deserialize(bytes)?)
}
}
#[cfg(test)] mod tests { use super::*; use tokio::time::{timeout, Duration};
#[tokio::test]
async fn test_node_creation() {
let result = L1VENode::new().await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_message_serialization() {
let message = NetworkMessage::CellUpdate {
generation: 42,
alive_cells: vec![(1, 2), (3, 4)],
sender_id: "test-peer".to_string(),
};
let bytes = message.to_bytes().unwrap();
let deserialized = NetworkMessage::from_bytes(&bytes).unwrap();
match deserialized {
NetworkMessage::CellUpdate { generation, .. } => {
assert_eq!(generation, 42);
}
_ => panic!("Wrong message type"),
}
}
#[tokio::test]
async fn test_topic_subscription() {
let mut node = L1VENode::new().await.unwrap();
let result = node.subscribe("test-topic");
assert!(result.is_ok());
let topics = node.subscribed_topics();
assert!(topics.contains(&"test-topic".to_string()));
}
#[tokio::test]
async fn test_default_node_creation() {
let result = timeout(Duration::from_secs(5), create_default_node()).await;
assert!(result.is_ok());
let node = result.unwrap().unwrap();
let topics = node.subscribed_topics();
assert!(topics.contains(&"l1vechain-cells".to_string()));
assert!(topics.contains(&"l1vechain-dag".to_string()));
assert!(topics.contains(&"l1vechain-consensus".to_string()));
}
}
Dein libp2p P2P-Netzwerkcode für L1VECHAIN sieht schon sehr umfangreich und sauber aus! Ich habe ein paar Verbesserungsvorschläge, Hinweise und Korrekturen, um deinen Code kompilierbar und funktional zu machen.
use-StatementsZahlreiche wichtige use-Statements fehlen, z.B. für libp2p-Komponenten wie Swarm, PeerId, Multiaddr, Protokolle (noise, yamux), Verhalten (Gossipsub, Mdns, Identify, etc.) und Traits.
Zum Beispiel:
use libp2p::{
PeerId, Swarm, Multiaddr,
noise,
yamux,
swarm::SwarmEvent,
gossipsub::{self, Gossipsub, GossipsubEvent, GossipsubConfig, MessageAuthenticity, ValidationMode, Topic},
mdns::{self, Mdns, MdnsEvent},
identify::{Identify, IdentifyEvent, IdentifyConfig},
core::upgrade,
tcp::TokioTcpConfig,
NetworkBehaviour,
};
In deinem new() hast du folgenden Code:
let transport = tcp::tokio::Transport::new(tcp::Config::default().nodelay(true))
// ...
Das ist so nicht korrekt - die letzten libp2p-Versionen verwenden TokioTcpConfig aus libp2p::tcp::TokioTcpConfig, das entspricht deinem am Anfang angegeben Transport.
Korrekt wäre:
let transport = TokioTcpConfig::new()
.nodelay(true)
.upgrade(upgrade::Version::V1)
.authenticate(
noise::NoiseAuthenticated::xx(&local_key)
.expect("Signing libp2p-noise static DH keypair failed."),
)
.multiplex(yamux::YamuxConfig::default())
.timeout(Duration::from_secs(20))
.boxed();
Hier hast du zwei Aufrufe gemischt:
let gossipsub_config = gossipsub::GossipsubConfig::default();
.heartbeat_interval(Duration::from_secs(1))
.validation_mode(gossipsub::ValidationMode::Strict)
.build()
.expect("Valid config");
Das ist syntaktisch falsch, da default() den Wert zurückgibt. Du musst stattdessen den GossipsubConfigBuilder verwenden:
let gossipsub_config = gossipsub::GossipsubConfigBuilder::default()
.heartbeat_interval(Duration::from_secs(1))
.validation_mode(ValidationMode::Strict)
.build()
.expect("Valid config");
L1VEBehaviourEvent fehltDer Code verwendet:
async fn handle_behaviour_event(&mut self, event: L1VEBehaviourEvent)
Diese Event-Typ kommt durch die #[derive(NetworkBehaviour)] automatisch mit generiertem Alias, der aus den Ereignissen aller eingebetteten Protokolle besteht.
Falls die trait-bedingten Ereignisse nicht automatisch importiert werden, musst du eventuell
use crate::L1VEBehaviourEvent;
einfügen oder den Event-Typ mit L1VEBehaviourEvent explizit importieren.
publishgossipsub.publish erwartet für den Topic-Parameter eine Referenz auf Topic, aber du übergibst ihn als Wert.
Korrekt:
self.swarm.behaviour_mut().gossipsub.publish(&topic, message)?;
topics-Menge im newIm Konstruktor fügst du dem Feld topics: HashSet<Topic> bei Verwendung im Konstruktor noch keine Topics hinzu.
Enweder:
topics hinzu:let mut topics = HashSet::new();
topics.insert(topic);
subscribe-Methode nach dem gossipsub.subscribe hinzu.self.swarm.next() (in run) benötigt den Trait StreamExt von futures oder tokio_stream.
Bsp.:
use futures::StreamExt;
Cargo.tomlDamit der Code kompiliert, solltest du in Cargo.toml mindestens haben:
[dependencies]
libp2p = { version = "0.50", features = ["tcp-tokio", "noise", "mdns", "gossipsub", "identify", "yamux", "dns"] }
tokio = { version = "1", features = ["full"] }
anyhow = "1.0"
serde = { version = "1.0", features = ["derive"] }
bincode = "1.3"
futures = "0.3"
log = "0.4"
.await vermeidenDie handle_behaviour_event Funktion kann auch synchron sein, wenn keine echten async-Operationen darin sind, außer Logging. Du kannst es dann einfacher machen.
.cloned()In
pub fn connected_peers(&self) -> Vec<PeerId> {
self.swarm.connected_peers().cloned().collect()
}
Ist gut so, da PeerId ist Copy, sonst könnte man über Referenzen arbeiten.
Wenn du diese Punkte beachtest und deine fehlenden use-Anweisungen ergänzt und kleine Syntaxfehler korrigierst, läuft dein Code problemlos als libp2p Node.
use std::collections::HashSet;
use std::time::Duration;
use anyhow::Result;
use futures::prelude::*;
use libp2p::{
core::upgrade,
gossipsub::{
Gossipsub, GossipsubConfigBuilder, GossipsubEvent, MessageAuthenticity,
Topic, ValidationMode,
},
identify::{Identify, IdentifyConfig, IdentifyEvent},
mdns::{Mdns, MdnsEvent},
noise,
swarm::{NetworkBehaviour, Swarm, SwarmEvent},
tcp::TokioTcpConfig,
yamux, Multiaddr, PeerId,
};
use log::{debug, info, warn};
use tokio::time;
Wenn du möchtest, kann ich dir auch ein leicht korrigiertes, vollständiges Beispiel des Codes erstellen! Soll ich das machen?
Gerne! Hier ein korrigiertes, vollständiges Beispiel deiner L1VENode-Libp2p-Implementierung mit allen nötigen use-Anweisungen, korrigierter Transport- und Gossipsub-Konfiguration, und einem lauffähigen Boilerplate:
// libp2p imports und weitere Abhängigkeiten
use std::{collections::HashSet, time::Duration};
use anyhow::Result;
use futures::prelude::*;
use libp2p::{
core::upgrade,
gossipsub::{
Gossipsub, GossipsubConfigBuilder, GossipsubEvent, MessageAuthenticity, Topic,
ValidationMode,
},
identify::{Identify, IdentifyConfig, IdentifyEvent},
mdns::{Mdns, MdnsEvent},
noise,
swarm::{NetworkBehaviour, Swarm, SwarmEvent},
tcp::TokioTcpConfig,
yamux, Multiaddr, PeerId,
};
use log::{debug, info, warn};
use tokio::time;
#[derive(NetworkBehaviour)]
#[behaviour(event_process = true)]
pub struct L1VEBehaviour {
pub gossipsub: Gossipsub,
pub mdns: Mdns,
pub identify: Identify,
}
pub struct L1VENode {
swarm: Swarm<L1VEBehaviour>,
topics: HashSet<Topic>,
}
impl L1VENode {
pub async fn new() -> Result<Self> {
let local_key = libp2p::identity::Keypair::generate_ed25519();
let local_peer_id = PeerId::from(local_key.public());
info!("Local peer id: {}", local_peer_id);
// Transport
let transport = TokioTcpConfig::new()
.nodelay(true)
.upgrade(upgrade::Version::V1)
.authenticate(
noise::NoiseAuthenticated::xx(&local_key)
.expect("Signing libp2p-noise static DH keypair failed."),
)
.multiplex(yamux::YamuxConfig::default())
.timeout(Duration::from_secs(20))
.boxed();
// Gossipsub Config
let gossipsub_config = GossipsubConfigBuilder::default()
.heartbeat_interval(Duration::from_secs(1))
.validation_mode(ValidationMode::Strict)
.build()
.expect("Valid config");
let mut gossipsub = Gossipsub::new(
MessageAuthenticity::Signed(local_key.clone()),
gossipsub_config,
)
.expect("Correct configuration");
let topic = Topic::new("l1vechain-general");
gossipsub.subscribe(&topic)?;
let mut topics = HashSet::new();
topics.insert(topic);
// Mdns for local peer discovery
let mdns = Mdns::new(mdns::Config::default()).await?;
// Identify for peer info exchange
let identify = Identify::new(IdentifyConfig::new(
"/l1vechain/1.0.0".to_string(),
local_key.public(),
));
let behaviour = L1VEBehaviour {
gossipsub,
mdns,
identify,
};
let swarm = Swarm::new(transport, behaviour, local_peer_id);
Ok(Self { swarm, topics })
}
pub fn listen_on(&mut self, addr: Multiaddr) -> Result<()> {
self.swarm.listen_on(addr)?;
info!("Started listening on address");
Ok(())
}
pub fn dial(&mut self, addr: Multiaddr) -> Result<()> {
self.swarm.dial(addr)?;
info!("Dialing remote peer");
Ok(())
}
pub fn subscribe(&mut self, topic_name: &str) -> Result<()> {
let topic = Topic::new(topic_name);
self.swarm.behaviour_mut().gossipsub.subscribe(&topic)?;
self.topics.insert(topic);
info!("Subscribed to topic: {}", topic_name);
Ok(())
}
pub fn publish(&mut self, topic_name: &str, message: Vec<u8>) -> Result<()> {
let topic = Topic::new(topic_name);
self.swarm.behaviour_mut().gossipsub.publish(&topic, message)?;
info!("Published message to topic: {}", topic_name);
Ok(())
}
pub async fn run(&mut self) -> Result<()> {
let mut heartbeat = time::interval(Duration::from_secs(30));
loop {
tokio::select! {
event = self.swarm.next() => {
if let Some(event) = event {
match event {
SwarmEvent::NewListenAddr { address, .. } => {
info!("Listening on {:?}", address);
}
SwarmEvent::Behaviour(event) => {
self.handle_behaviour_event(event).await;
}
SwarmEvent::ConnectionEstablished { peer_id, .. } => {
info!("Connection established with {}", peer_id);
}
SwarmEvent::ConnectionClosed { peer_id, .. } => {
info!("Connection closed with {}", peer_id);
}
_ => {}
}
}
}
_ = heartbeat.tick() => {
debug!("Heartbeat - Connected peers: {}", self.swarm.connected_peers().count());
}
}
}
}
async fn handle_behaviour_event(&mut self, event: libp2p::swarm::derive_prelude::L1VEBehaviourEvent) {
// Der Typ L1VEBehaviourEvent wurde automatisch via #[derive(NetworkBehaviour)] generiert
// oder ersetze hier den konkreten Event-Typ aus dem derive, z.B.
// use crate::L1VEBehaviourEvent;
match event {
L1VEBehaviourEvent::Gossipsub(GossipsubEvent::Message { propagation_source: _, message_id: _, message }) => {
info!(
"Received message from {}: {}",
message.source.map(|id| id.to_string()).unwrap_or_else(|| "Unknown".to_string()),
String::from_utf8_lossy(&message.data)
);
}
L1VEBehaviourEvent::Gossipsub(GossipsubEvent::Subscribed { peer_id, topic }) => {
info!("Peer {} subscribed to topic {}", peer_id, topic);
}
L1VEBehaviourEvent::Gossipsub(GossipsubEvent::Unsubscribed { peer_id, topic }) => {
info!("Peer {} unsubscribed from topic {}", peer_id, topic);
}
L1VEBehaviourEvent::Mdns(MdnsEvent::Discovered(list)) => {
for (peer_id, multiaddr) in list {
info!("Discovered peer {} at {}", peer_id, multiaddr);
if let Err(e) = self.swarm.dial(multiaddr) {
warn!("Failed to dial discovered peer: {}", e);
}
}
}
L1VEBehaviourEvent::Mdns(MdnsEvent::Expired(list)) => {
for (peer_id, multiaddr) in list {
info!("Peer {} at {} expired", peer_id, multiaddr);
}
}
L1VEBehaviourEvent::Identify(IdentifyEvent::Received { peer_id, info }) => {
info!("Received identify info from {}: {}", peer_id, info.protocol_version);
}
L1VEBehaviourEvent::Identify(IdentifyEvent::Sent { peer_id }) => {
debug!("Sent identify info to {}", peer_id);
}
L1VEBehaviourEvent::Identify(IdentifyEvent::Error { peer_id, error }) => {
warn!("Identify error with {}: {}", peer_id, error);
}
_ => {}
}
}
pub fn connected_peers_count(&self) -> usize {
self.swarm.connected_peers().count()
}
pub fn connected_peers(&self) -> Vec<PeerId> {
self.swarm.connected_peers().cloned().collect()
}
pub fn subscribed_topics(&self) -> Vec<String> {
self.topics.iter().map(|t| t.to_string()).collect()
}
}
pub async fn create_default_node() -> Result<L1VENode> {
let mut node = L1VENode::new().await?;
let listen_addr: Multiaddr = "/ip4/0.0.0.0/tcp/0".parse()?;
node.listen_on(listen_addr)?;
node.subscribe("l1vechain-cells")?;
node.subscribe("l1vechain-dag")?;
node.subscribe("l1vechain-consensus")?;
Ok(node)
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum NetworkMessage {
CellUpdate {
generation: usize,
alive_cells: Vec<(i32, i32)>,
sender_id: String,
},
DAGUpdate {
node_id: String,
data: Vec<u8>,
parents: Vec<String>,
},
PeerDiscovery {
peer_id: String,
capabilities: Vec<String>,
},
Heartbeat {
peer_id: String,
timestamp: u64,
},
}
impl NetworkMessage {
pub fn to_bytes(&self) -> Result<Vec<u8>> {
Ok(bincode::serialize(self)?)
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
Ok(bincode::deserialize(bytes)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::time::{timeout, Duration};
#[tokio::test]
async fn test_node_creation() {
let result = L1VENode::new().await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_message_serialization() {
let message = NetworkMessage::CellUpdate {
generation: 42,
alive_cells: vec![(1, 2), (3, 4)],
sender_id: "test-peer".to_string(),
};
let bytes = message.to_bytes().unwrap();
let deserialized = NetworkMessage::from_bytes(&bytes).unwrap();
match deserialized {
NetworkMessage::CellUpdate { generation, .. } => {
assert_eq!(generation, 42);
}
_ => panic!("Wrong message type"),
}
}
#[tokio::test]
async fn test_topic_subscription() {
let mut node = L1VENode::new().await.unwrap();
let result = node.subscribe("test-topic");
assert!(result.is_ok());
let topics = node.subscribed_topics();
assert!(topics.contains(&"test-topic".to_string()));
}
#[tokio::test]
async fn test_default_node_creation() {
let result = timeout(Duration::from_secs(5), create_default_node()).await;
assert!(result.is_ok());
let node = result.unwrap().unwrap();
let topics = node.subscribed_topics();
assert!(topics.contains(&"l1vechain-cells".to_string()));
assert!(topics.contains(&"l1vechain-dag".to_string()));
assert!(topics.contains(&"l1vechain-consensus".to_string()));
}
}
env_logger oder tracing).L1VEBehaviourEvent wird über #[derive(NetworkBehaviour)] generiert, erfordert eventuell korrektes Importieren / Qualifizieren je nach Projektstruktur.Bei Bedarf kann ich auch eine Minimalausführung mit tokio::main und Startshell des Nodes bauen.
Meld dich gern, falls du mehr brauchst!
Natürlich! Hier ein minimal lauffähiges Beispiel mit tokio::main, Logging, Starten und Event-Loop des Nodes. So kannst du das direkt ausführen und dein P2P Netzwerk testen:
use std::{collections::HashSet, time::Duration};
use anyhow::Result;
use futures::prelude::*;
use libp2p::{
core::upgrade,
gossipsub::{
Gossipsub, GossipsubConfigBuilder, GossipsubEvent, MessageAuthenticity, Topic,
ValidationMode,
},
identify::{Identify, IdentifyConfig, IdentifyEvent},
mdns::{Mdns, MdnsEvent},
noise,
swarm::{NetworkBehaviour, Swarm, SwarmEvent},
tcp::TokioTcpConfig,
yamux, Multiaddr, PeerId,
};
use log::{debug, info, warn};
use tokio::time;
// Deine Behaviour Definition mit Events
#[derive(NetworkBehaviour)]
#[behaviour(event_process = true)]
pub struct L1VEBehaviour {
pub gossipsub: Gossipsub,
pub mdns: Mdns,
pub identify: Identify,
}
pub struct L1VENode {
swarm: Swarm<L1VEBehaviour>,
topics: HashSet<Topic>,
}
impl L1VENode {
pub async fn new() -> Result<Self> {
let local_key = libp2p::identity::Keypair::generate_ed25519();
let local_peer_id = PeerId::from(local_key.public());
info!("Local peer id: {}", local_peer_id);
let transport = TokioTcpConfig::new()
.nodelay(true)
.upgrade(upgrade::Version::V1)
.authenticate(
noise::NoiseAuthenticated::xx(&local_key)
.expect("Noise keypair generation failed."),
)
.multiplex(yamux::YamuxConfig::default())
.timeout(Duration::from_secs(20))
.boxed();
let gossipsub_config = GossipsubConfigBuilder::default()
.heartbeat_interval(Duration::from_secs(1))
.validation_mode(ValidationMode::Strict)
.build()
.expect("Valid config");
let mut gossipsub = Gossipsub::new(
MessageAuthenticity::Signed(local_key.clone()),
gossipsub_config,
)?;
let topic = Topic::new("l1vechain-general");
gossipsub.subscribe(&topic)?;
let mut topics = HashSet::new();
topics.insert(topic);
let mdns = Mdns::new(mdns::Config::default()).await?;
let identify = Identify::new(IdentifyConfig::new(
"/l1vechain/1.0.0".into(),
local_key.public(),
));
let behaviour = L1VEBehaviour {
gossipsub,
mdns,
identify,
};
let swarm = Swarm::new(transport, behaviour, local_peer_id);
Ok(Self { swarm, topics })
}
pub fn listen_on(&mut self, addr: Multiaddr) -> Result<()> {
self.swarm.listen_on(addr)?;
info!("Started listening on {}", addr);
Ok(())
}
pub fn subscribe(&mut self, topic_name: &str) -> Result<()> {
let topic = Topic::new(topic_name);
self.swarm.behaviour_mut().gossipsub.subscribe(&topic)?;
self.topics.insert(topic);
info!("Subscribed to topic {}", topic_name);
Ok(())
}
pub async fn run(&mut self) -> Result<()> {
use libp2p::swarm::derive_prelude::L1VEBehaviourEvent; // ggf. anpassen wenn Dein Modulsystem anders ist
let mut heartbeat = time::interval(Duration::from_secs(30));
loop {
tokio::select! {
event = self.swarm.next() => {
if let Some(event) = event {
match event {
SwarmEvent::NewListenAddr { address, .. } => {
info!("Listening on {:?}", address);
}
SwarmEvent::Behaviour(event) => {
self.handle_behaviour_event(event).await;
}
SwarmEvent::ConnectionEstablished { peer_id, .. } => {
info!("Connection established with {}", peer_id);
}
SwarmEvent::ConnectionClosed { peer_id, .. } => {
info!("Connection closed with {}", peer_id);
}
_ => {}
}
}
}
_ = heartbeat.tick() => {
debug!("Heartbeat - connected peers: {}", self.swarm.connected_peers().count());
}
}
}
}
async fn handle_behaviour_event(&mut self, event: libp2p::swarm::derive_prelude::L1VEBehaviourEvent) {
match event {
L1VEBehaviourEvent::Gossipsub(GossipsubEvent::Message { message, .. }) => {
info!(
"Received message from {}: {}",
message.source
.map(|peer_id| peer_id.to_string())
.unwrap_or_else(|| "unknown".into()),
String::from_utf8_lossy(&message.data)
);
}
L1VEBehaviourEvent::Mdns(MdnsEvent::Discovered(list)) => {
for (peer_id, addr) in list {
info!("Discovered peer {} at {}", peer_id, addr);
if let Err(e) = self.swarm.dial(addr) {
warn!("Dial error: {}", e);
}
}
}
L1VEBehaviourEvent::Identify(IdentifyEvent::Received { peer_id, info }) => {
info!("Identify received from {}: {:?}", peer_id, info.protocol_version);
}
_ => {}
}
}
}
/// Simple main function, die Node startet und laufen lässt
#[tokio::main]
async fn main() -> Result<()> {
env_logger::init();
let mut node = L1VENode::new().await?;
// Auf einer zufälligen Portnummer auf allen Interfaces lauschen
node.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;
// Thema abonnieren
node.subscribe("l1vechain-general")?;
// Haupt-Loop starten (blockierend)
node.run().await?;
Ok(())
}
[dependencies]
libp2p = { version = "0.50", features = ["tcp-tokio", "noise", "mdns", "gossipsub", "identify", "yamux"] }
tokio = { version = "1.26", features = ["full"] }
anyhow = "1.0"
futures = "0.3"
log = "0.4"
env_logger = "0.9"
"l1vechain-general"cargo run
Starte mehrere Instanzen, sie entdecken sich per mDNS automatisch und tauschen PubSub-Nachrichten aus, wenn du publish entsprechend erweiterst.
Wenn du zusätzliche Features wie Nachrichtenaustausch, weitere Topics, oder komplexeres Verhalten möchtest, baue ich dir da gern noch Beispielcode zu!
Falls Fragen oder Probleme auftauchen, einfach melden! :)
Not yet included in a published release.