|
| 1 | +/// libp2p transport integration for P2P networking |
| 2 | +/// Provides full networking layer with gossipsub and peer discovery |
| 3 | +
|
| 4 | +use libp2p::{ |
| 5 | + core::upgrade, |
| 6 | + gossipsub, identity, mdns, noise, |
| 7 | + swarm::{NetworkBehaviour, SwarmBuilder, SwarmEvent}, |
| 8 | + tcp, yamux, Multiaddr, PeerId, Swarm, Transport, |
| 9 | +}; |
| 10 | +use std::collections::HashSet; |
| 11 | +use std::error::Error; |
| 12 | +use tokio::sync::mpsc; |
| 13 | + |
| 14 | +use crate::messages::{Block, GliderCommit, GliderReveal, Transaction}; |
| 15 | +use crate::peer::{PeerInfo, PeerReputation}; |
| 16 | + |
| 17 | +/// Network behavior combining gossipsub and mDNS |
| 18 | +#[derive(NetworkBehaviour)] |
| 19 | +pub struct BitCellBehaviour { |
| 20 | + pub gossipsub: gossipsub::Behaviour, |
| 21 | + pub mdns: mdns::tokio::Behaviour, |
| 22 | +} |
| 23 | + |
| 24 | +/// P2P network manager |
| 25 | +pub struct NetworkManager { |
| 26 | + swarm: Swarm<BitCellBehaviour>, |
| 27 | + known_peers: HashSet<PeerId>, |
| 28 | + peer_reputations: std::collections::HashMap<PeerId, PeerReputation>, |
| 29 | + block_tx: mpsc::Sender<Block>, |
| 30 | + tx_tx: mpsc::Sender<Transaction>, |
| 31 | +} |
| 32 | + |
| 33 | +impl NetworkManager { |
| 34 | + /// Create a new network manager |
| 35 | + pub async fn new( |
| 36 | + listen_addr: Multiaddr, |
| 37 | + block_tx: mpsc::Sender<Block>, |
| 38 | + tx_tx: mpsc::Sender<Transaction>, |
| 39 | + ) -> Result<Self, Box<dyn Error>> { |
| 40 | + // Generate identity |
| 41 | + let local_key = identity::Keypair::generate_ed25519(); |
| 42 | + let local_peer_id = PeerId::from(local_key.public()); |
| 43 | + println!("Local peer id: {local_peer_id}"); |
| 44 | + |
| 45 | + // Create transport |
| 46 | + let transport = tcp::tokio::Transport::default() |
| 47 | + .upgrade(upgrade::Version::V1) |
| 48 | + .authenticate(noise::Config::new(&local_key).unwrap()) |
| 49 | + .multiplex(yamux::Config::default()) |
| 50 | + .boxed(); |
| 51 | + |
| 52 | + // Create gossipsub |
| 53 | + let gossipsub_config = gossipsub::ConfigBuilder::default() |
| 54 | + .heartbeat_interval(std::time::Duration::from_secs(1)) |
| 55 | + .validation_mode(gossipsub::ValidationMode::Strict) |
| 56 | + .build() |
| 57 | + .expect("Valid gossipsub config"); |
| 58 | + |
| 59 | + let mut gossipsub = gossipsub::Behaviour::new( |
| 60 | + gossipsub::MessageAuthenticity::Signed(local_key.clone()), |
| 61 | + gossipsub_config, |
| 62 | + ) |
| 63 | + .expect("Valid gossipsub behaviour"); |
| 64 | + |
| 65 | + // Subscribe to topics |
| 66 | + gossipsub.subscribe(&gossipsub::IdentTopic::new("blocks"))?; |
| 67 | + gossipsub.subscribe(&gossipsub::IdentTopic::new("transactions"))?; |
| 68 | + gossipsub.subscribe(&gossipsub::IdentTopic::new("commits"))?; |
| 69 | + gossipsub.subscribe(&gossipsub::IdentTopic::new("reveals"))?; |
| 70 | + |
| 71 | + // Create mDNS |
| 72 | + let mdns = mdns::tokio::Behaviour::new(mdns::Config::default(), local_peer_id)?; |
| 73 | + |
| 74 | + // Create swarm |
| 75 | + let behaviour = BitCellBehaviour { gossipsub, mdns }; |
| 76 | + let mut swarm = SwarmBuilder::with_tokio_executor(transport, behaviour, local_peer_id).build(); |
| 77 | + |
| 78 | + // Listen on address |
| 79 | + swarm.listen_on(listen_addr)?; |
| 80 | + |
| 81 | + Ok(Self { |
| 82 | + swarm, |
| 83 | + known_peers: HashSet::new(), |
| 84 | + peer_reputations: std::collections::HashMap::new(), |
| 85 | + block_tx, |
| 86 | + tx_tx, |
| 87 | + }) |
| 88 | + } |
| 89 | + |
| 90 | + /// Broadcast a block to the network |
| 91 | + pub fn broadcast_block(&mut self, block: &Block) -> Result<(), Box<dyn Error>> { |
| 92 | + let topic = gossipsub::IdentTopic::new("blocks"); |
| 93 | + let data = bincode::serialize(block)?; |
| 94 | + self.swarm.behaviour_mut().gossipsub.publish(topic, data)?; |
| 95 | + Ok(()) |
| 96 | + } |
| 97 | + |
| 98 | + /// Broadcast a transaction to the network |
| 99 | + pub fn broadcast_transaction(&mut self, tx: &Transaction) -> Result<(), Box<dyn Error>> { |
| 100 | + let topic = gossipsub::IdentTopic::new("transactions"); |
| 101 | + let data = bincode::serialize(tx)?; |
| 102 | + self.swarm.behaviour_mut().gossipsub.publish(topic, data)?; |
| 103 | + Ok(()) |
| 104 | + } |
| 105 | + |
| 106 | + /// Broadcast a glider commit |
| 107 | + pub fn broadcast_commit(&mut self, commit: &GliderCommit) -> Result<(), Box<dyn Error>> { |
| 108 | + let topic = gossipsub::IdentTopic::new("commits"); |
| 109 | + let data = bincode::serialize(commit)?; |
| 110 | + self.swarm.behaviour_mut().gossipsub.publish(topic, data)?; |
| 111 | + Ok(()) |
| 112 | + } |
| 113 | + |
| 114 | + /// Broadcast a glider reveal |
| 115 | + pub fn broadcast_reveal(&mut self, reveal: &GliderReveal) -> Result<(), Box<dyn Error>> { |
| 116 | + let topic = gossipsub::IdentTopic::new("reveals"); |
| 117 | + let data = bincode::serialize(reveal)?; |
| 118 | + self.swarm.behaviour_mut().gossipsub.publish(topic, data)?; |
| 119 | + Ok(()) |
| 120 | + } |
| 121 | + |
| 122 | + /// Run the network event loop |
| 123 | + pub async fn run(&mut self) -> Result<(), Box<dyn Error>> { |
| 124 | + loop { |
| 125 | + match self.swarm.select_next_some().await { |
| 126 | + SwarmEvent::Behaviour(BitCellBehaviourEvent::Mdns(mdns::Event::Discovered(list))) => { |
| 127 | + for (peer_id, addr) in list { |
| 128 | + println!("Discovered peer: {peer_id} at {addr}"); |
| 129 | + self.swarm.behaviour_mut().gossipsub.add_explicit_peer(&peer_id); |
| 130 | + self.known_peers.insert(peer_id); |
| 131 | + self.peer_reputations.insert(peer_id, PeerReputation::new()); |
| 132 | + } |
| 133 | + } |
| 134 | + SwarmEvent::Behaviour(BitCellBehaviourEvent::Mdns(mdns::Event::Expired(list))) => { |
| 135 | + for (peer_id, addr) in list { |
| 136 | + println!("Peer expired: {peer_id} at {addr}"); |
| 137 | + self.swarm.behaviour_mut().gossipsub.remove_explicit_peer(&peer_id); |
| 138 | + self.known_peers.remove(&peer_id); |
| 139 | + } |
| 140 | + } |
| 141 | + SwarmEvent::Behaviour(BitCellBehaviourEvent::Gossipsub(gossipsub::Event::Message { |
| 142 | + propagation_source, |
| 143 | + message, |
| 144 | + .. |
| 145 | + })) => { |
| 146 | + self.handle_gossipsub_message(propagation_source, message).await?; |
| 147 | + } |
| 148 | + SwarmEvent::NewListenAddr { address, .. } => { |
| 149 | + println!("Listening on {address}"); |
| 150 | + } |
| 151 | + _ => {} |
| 152 | + } |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + /// Handle incoming gossipsub messages |
| 157 | + async fn handle_gossipsub_message( |
| 158 | + &mut self, |
| 159 | + _source: PeerId, |
| 160 | + message: gossipsub::Message, |
| 161 | + ) -> Result<(), Box<dyn Error>> { |
| 162 | + let topic = message.topic.as_str(); |
| 163 | + |
| 164 | + match topic { |
| 165 | + "blocks" => { |
| 166 | + if let Ok(block) = bincode::deserialize::<Block>(&message.data) { |
| 167 | + self.block_tx.send(block).await?; |
| 168 | + } |
| 169 | + } |
| 170 | + "transactions" => { |
| 171 | + if let Ok(tx) = bincode::deserialize::<Transaction>(&message.data) { |
| 172 | + self.tx_tx.send(tx).await?; |
| 173 | + } |
| 174 | + } |
| 175 | + "commits" | "reveals" => { |
| 176 | + // Handle tournament messages (to be implemented) |
| 177 | + } |
| 178 | + _ => {} |
| 179 | + } |
| 180 | + |
| 181 | + Ok(()) |
| 182 | + } |
| 183 | + |
| 184 | + /// Get peer count |
| 185 | + pub fn peer_count(&self) -> usize { |
| 186 | + self.known_peers.len() |
| 187 | + } |
| 188 | + |
| 189 | + /// Get peer info |
| 190 | + pub fn get_peers(&self) -> Vec<PeerInfo> { |
| 191 | + self.known_peers |
| 192 | + .iter() |
| 193 | + .map(|peer_id| PeerInfo { |
| 194 | + peer_id: peer_id.to_string(), |
| 195 | + reputation: self.peer_reputations.get(peer_id).cloned().unwrap_or_default(), |
| 196 | + connected: true, |
| 197 | + }) |
| 198 | + .collect() |
| 199 | + } |
| 200 | +} |
| 201 | + |
| 202 | +#[cfg(test)] |
| 203 | +mod tests { |
| 204 | + use super::*; |
| 205 | + |
| 206 | + #[tokio::test] |
| 207 | + async fn test_network_manager_creation() { |
| 208 | + let (block_tx, _) = mpsc::channel(100); |
| 209 | + let (tx_tx, _) = mpsc::channel(100); |
| 210 | + |
| 211 | + let addr: Multiaddr = "/ip4/127.0.0.1/tcp/0".parse().unwrap(); |
| 212 | + let result = NetworkManager::new(addr, block_tx, tx_tx).await; |
| 213 | + |
| 214 | + assert!(result.is_ok()); |
| 215 | + } |
| 216 | +} |
0 commit comments