From dc33ebcf39effa581ad31bca90ef27e605ad9180 Mon Sep 17 00:00:00 2001 From: Ignotus Peverell Date: Tue, 20 Dec 2016 17:33:20 -0800 Subject: [PATCH] Network block broadcasting. --- p2p/src/peer.rs | 7 +++++++ p2p/src/server.rs | 12 ++++++++++++ p2p/src/types.rs | 3 ++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/p2p/src/peer.rs b/p2p/src/peer.rs index 732eaee7d..89660ac4e 100644 --- a/p2p/src/peer.rs +++ b/p2p/src/peer.rs @@ -72,6 +72,13 @@ impl Peer { self.proto.send_ping() } + /// Sends the provided block to the remote peer. The request may be dropped + /// if the remote peer is known to already have the block. + pub fn send_block(&self, b: &core::Block) -> Result<(), Error> { + // TODO do not send if the peer sent us the block in the first place + self.proto.send_block(b) + } + pub fn stop(&self) { self.proto.close(); } diff --git a/p2p/src/server.rs b/p2p/src/server.rs index 6ae2c04c3..62c0b1908 100644 --- a/p2p/src/server.rs +++ b/p2p/src/server.rs @@ -139,6 +139,18 @@ impl Server { Box::new(request) } + /// Broadcasts the provided block to all our peers. A peer implementation + /// may drop the broadcast request if it knows the remote peer already has + /// the block. + pub fn broadcast_block(&self, b: &core::Block) { + let peers = self.peers.write().unwrap(); + for p in peers.deref() { + if let Err(e) = p.send_block(b) { + debug!("Error sending block to peer: {}", e); + } + } + } + pub fn peers_count(&self) -> u32 { self.peers.read().unwrap().len() as u32 } diff --git a/p2p/src/types.rs b/p2p/src/types.rs index 79360bf5c..7035ca317 100644 --- a/p2p/src/types.rs +++ b/p2p/src/types.rs @@ -88,7 +88,8 @@ pub trait Protocol { } /// Bridge between the networking layer and the rest of the system. Handles the -/// forwarding or querying of blocks and transactions among other things. +/// forwarding or querying of blocks and transactions from the network among +/// other things. pub trait NetAdapter { /// A valid transaction has been received from one of our peers fn transaction_received(&self, tx: core::Transaction);