2016-10-24 00:02:02 +03:00
|
|
|
// Copyright 2016 The Grin Developers
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
|
|
|
//! Grin server implementation, accepts incoming connections and connects to
|
2016-10-25 07:35:10 +03:00
|
|
|
//! other peers in the network.
|
2016-10-24 00:02:02 +03:00
|
|
|
|
2016-10-29 22:36:45 +03:00
|
|
|
use std::cell::RefCell;
|
2016-12-11 06:11:49 +03:00
|
|
|
use std::net::SocketAddr;
|
2016-10-30 18:24:19 +03:00
|
|
|
use std::ops::Deref;
|
2016-10-29 22:36:45 +03:00
|
|
|
use std::sync::{Arc, RwLock};
|
2016-12-11 06:11:49 +03:00
|
|
|
use std::time::Duration;
|
2016-10-26 08:06:13 +03:00
|
|
|
|
2016-12-11 06:11:49 +03:00
|
|
|
use futures;
|
|
|
|
use futures::{Future, Stream};
|
2017-02-19 05:42:34 +03:00
|
|
|
use futures::future::{self, IntoFuture};
|
2017-02-08 00:52:17 +03:00
|
|
|
use rand::{self, Rng};
|
2016-12-11 06:11:49 +03:00
|
|
|
use tokio_core::net::{TcpListener, TcpStream};
|
|
|
|
use tokio_core::reactor;
|
2016-10-24 00:02:02 +03:00
|
|
|
|
2016-11-01 20:42:33 +03:00
|
|
|
use core::core;
|
2017-02-08 00:52:17 +03:00
|
|
|
use core::core::hash::Hash;
|
|
|
|
use core::core::target::Difficulty;
|
2016-10-26 08:06:13 +03:00
|
|
|
use handshake::Handshake;
|
2016-10-29 22:36:45 +03:00
|
|
|
use peer::Peer;
|
2016-10-26 08:06:13 +03:00
|
|
|
use types::*;
|
2016-10-24 00:02:02 +03:00
|
|
|
|
2016-12-16 01:57:04 +03:00
|
|
|
/// A no-op network adapter used for testing.
|
2016-10-31 04:23:52 +03:00
|
|
|
pub struct DummyAdapter {}
|
2016-11-03 00:19:40 +03:00
|
|
|
impl NetAdapter for DummyAdapter {
|
2017-02-08 00:52:17 +03:00
|
|
|
fn total_difficulty(&self) -> Difficulty {
|
|
|
|
Difficulty::one()
|
|
|
|
}
|
2016-11-03 00:19:40 +03:00
|
|
|
fn transaction_received(&self, tx: core::Transaction) {}
|
|
|
|
fn block_received(&self, b: core::Block) {}
|
2017-02-08 00:52:17 +03:00
|
|
|
fn headers_received(&self, bh: Vec<core::BlockHeader>) {}
|
|
|
|
fn locate_headers(&self, locator: Vec<Hash>) -> Vec<core::BlockHeader> {
|
|
|
|
vec![]
|
|
|
|
}
|
|
|
|
fn get_block(&self, h: Hash) -> Option<core::Block> {
|
|
|
|
None
|
|
|
|
}
|
2017-02-19 05:42:34 +03:00
|
|
|
fn find_peer_addrs(&self, capab: Capabilities) -> Vec<SocketAddr> {
|
|
|
|
vec![]
|
|
|
|
}
|
|
|
|
fn peer_addrs_received(&self, peer_addrs: Vec<SocketAddr>) {}
|
|
|
|
fn peer_connected(&self, pi: &PeerInfo) {}
|
2016-11-03 00:19:40 +03:00
|
|
|
}
|
2016-10-26 08:06:13 +03:00
|
|
|
|
2016-10-29 22:36:45 +03:00
|
|
|
/// P2P server implementation, handling bootstrapping to find and connect to
|
|
|
|
/// peers, receiving connections from other peers and keep track of all of them.
|
2016-10-24 00:02:02 +03:00
|
|
|
pub struct Server {
|
2016-11-30 05:49:03 +03:00
|
|
|
config: P2PConfig,
|
2017-02-19 05:42:34 +03:00
|
|
|
capabilities: Capabilities,
|
2016-12-11 06:11:49 +03:00
|
|
|
peers: Arc<RwLock<Vec<Arc<Peer>>>>,
|
2016-12-19 02:51:54 +03:00
|
|
|
adapter: Arc<NetAdapter>,
|
2016-12-11 06:11:49 +03:00
|
|
|
stop: RefCell<Option<futures::sync::oneshot::Sender<()>>>,
|
2016-10-24 00:02:02 +03:00
|
|
|
}
|
|
|
|
|
2016-10-31 04:23:52 +03:00
|
|
|
unsafe impl Sync for Server {}
|
|
|
|
unsafe impl Send for Server {}
|
|
|
|
|
2016-10-29 22:36:45 +03:00
|
|
|
// TODO TLS
|
2016-10-24 00:02:02 +03:00
|
|
|
impl Server {
|
2016-11-01 20:42:33 +03:00
|
|
|
/// Creates a new idle p2p server with no peers
|
2017-02-19 05:42:34 +03:00
|
|
|
pub fn new(capab: Capabilities, config: P2PConfig, adapter: Arc<NetAdapter>) -> Server {
|
2016-10-31 04:23:52 +03:00
|
|
|
Server {
|
2016-11-30 05:49:03 +03:00
|
|
|
config: config,
|
2017-02-19 05:42:34 +03:00
|
|
|
capabilities: capab,
|
2016-12-11 06:11:49 +03:00
|
|
|
peers: Arc::new(RwLock::new(Vec::new())),
|
2016-12-19 02:51:54 +03:00
|
|
|
adapter: adapter,
|
2016-12-11 06:11:49 +03:00
|
|
|
stop: RefCell::new(None),
|
2016-10-31 04:23:52 +03:00
|
|
|
}
|
|
|
|
}
|
2016-12-11 06:11:49 +03:00
|
|
|
|
2016-10-31 04:23:52 +03:00
|
|
|
/// Starts the p2p server. Opens a TCP port to allow incoming
|
2016-10-24 00:02:02 +03:00
|
|
|
/// connections and starts the bootstrapping process to find peers.
|
2016-12-11 06:11:49 +03:00
|
|
|
pub fn start(&self, h: reactor::Handle) -> Box<Future<Item = (), Error = Error>> {
|
2016-11-30 05:49:03 +03:00
|
|
|
let addr = SocketAddr::new(self.config.host, self.config.port);
|
2016-12-11 06:11:49 +03:00
|
|
|
let socket = TcpListener::bind(&addr, &h.clone()).unwrap();
|
2016-10-31 04:23:52 +03:00
|
|
|
warn!("P2P server started on {}", addr);
|
2016-10-24 00:02:02 +03:00
|
|
|
|
2016-10-31 04:23:52 +03:00
|
|
|
let hs = Arc::new(Handshake::new());
|
2016-12-11 06:11:49 +03:00
|
|
|
let peers = self.peers.clone();
|
2016-12-19 02:51:54 +03:00
|
|
|
let adapter = self.adapter.clone();
|
2017-02-19 05:42:34 +03:00
|
|
|
let capab = self.capabilities.clone();
|
2016-12-11 06:11:49 +03:00
|
|
|
|
|
|
|
// main peer acceptance future handling handshake
|
|
|
|
let hp = h.clone();
|
2017-02-27 07:08:40 +03:00
|
|
|
let peers = socket.incoming().map_err(From::from).map(move |(conn, addr)| {
|
2016-12-19 02:51:54 +03:00
|
|
|
let adapter = adapter.clone();
|
2017-02-08 00:52:17 +03:00
|
|
|
let total_diff = adapter.total_difficulty();
|
2016-12-11 06:11:49 +03:00
|
|
|
let peers = peers.clone();
|
2016-12-12 00:04:52 +03:00
|
|
|
|
2016-12-11 06:11:49 +03:00
|
|
|
// accept the peer and add it to the server map
|
2017-02-27 07:08:40 +03:00
|
|
|
let accept = Peer::accept(conn, capab, total_diff, &hs.clone());
|
|
|
|
let added = add_to_peers(peers, adapter.clone(), accept);
|
2016-11-30 05:49:03 +03:00
|
|
|
|
2016-12-11 06:11:49 +03:00
|
|
|
// wire in a future to timeout the accept after 5 secs
|
2017-02-27 07:08:40 +03:00
|
|
|
let timed_peer = with_timeout(Box::new(added), &hp);
|
2016-12-11 06:11:49 +03:00
|
|
|
|
|
|
|
// run the main peer protocol
|
2016-12-19 02:51:54 +03:00
|
|
|
timed_peer.and_then(move |(conn, peer)| peer.clone().run(conn, adapter))
|
2016-12-11 06:11:49 +03:00
|
|
|
});
|
|
|
|
|
|
|
|
// spawn each peer future to its own task
|
|
|
|
let hs = h.clone();
|
|
|
|
let server = peers.for_each(move |peer| {
|
|
|
|
hs.spawn(peer.then(|res| {
|
|
|
|
match res {
|
2017-02-27 07:08:40 +03:00
|
|
|
Err(e) => info!("Client error: {:?}", e),
|
2016-12-11 06:11:49 +03:00
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
futures::finished(())
|
|
|
|
}));
|
|
|
|
Ok(())
|
|
|
|
});
|
|
|
|
|
|
|
|
// setup the stopping oneshot on the server and join it with the peer future
|
|
|
|
let (stop, stop_rx) = futures::sync::oneshot::channel();
|
|
|
|
{
|
|
|
|
let mut stop_mut = self.stop.borrow_mut();
|
|
|
|
*stop_mut = Some(stop);
|
2016-11-01 20:42:33 +03:00
|
|
|
}
|
2017-02-27 07:08:40 +03:00
|
|
|
Box::new(server.select(stop_rx.map_err(|_| Error::ConnectionClose)).then(|res| {
|
2016-12-11 06:11:49 +03:00
|
|
|
match res {
|
|
|
|
Ok((_, _)) => Ok(()),
|
|
|
|
Err((e, _)) => Err(e),
|
|
|
|
}
|
|
|
|
}))
|
2016-11-06 02:31:45 +03:00
|
|
|
}
|
|
|
|
|
2016-12-12 00:04:52 +03:00
|
|
|
/// Asks the server to connect to a new peer.
|
2016-12-11 06:11:49 +03:00
|
|
|
pub fn connect_peer(&self,
|
|
|
|
addr: SocketAddr,
|
|
|
|
h: reactor::Handle)
|
2017-02-19 05:42:34 +03:00
|
|
|
-> Box<Future<Item = Option<Arc<Peer>>, Error = Error>> {
|
|
|
|
for p in self.peers.read().unwrap().deref() {
|
|
|
|
// if we're already connected to the addr, just return the peer
|
|
|
|
if p.info.addr == addr {
|
|
|
|
return Box::new(future::ok(Some((*p).clone())));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// asked to connect to ourselves
|
|
|
|
if addr.ip() == self.config.host && addr.port() == self.config.port {
|
|
|
|
return Box::new(future::ok(None));
|
|
|
|
}
|
2016-12-11 06:11:49 +03:00
|
|
|
let peers = self.peers.clone();
|
2017-02-03 02:51:48 +03:00
|
|
|
let adapter1 = self.adapter.clone();
|
|
|
|
let adapter2 = self.adapter.clone();
|
2017-02-19 05:42:34 +03:00
|
|
|
let capab = self.capabilities.clone();
|
|
|
|
let self_addr = SocketAddr::new(self.config.host, self.config.port);
|
|
|
|
|
|
|
|
debug!("{} connecting to {}", self_addr, addr);
|
2016-12-19 02:51:54 +03:00
|
|
|
|
2017-02-27 07:08:40 +03:00
|
|
|
let socket = TcpStream::connect(&addr, &h).map_err(|e| Error::Connection(e));
|
2017-02-19 05:42:34 +03:00
|
|
|
let h2 = h.clone();
|
2016-12-11 06:11:49 +03:00
|
|
|
let request = socket.and_then(move |socket| {
|
|
|
|
let peers = peers.clone();
|
2017-02-19 05:42:34 +03:00
|
|
|
let total_diff = adapter1.clone().total_difficulty();
|
2016-12-12 00:04:52 +03:00
|
|
|
|
|
|
|
// connect to the peer and add it to the server map, wiring it a timeout for
|
|
|
|
// the handhake
|
2017-02-27 07:08:40 +03:00
|
|
|
let connect =
|
|
|
|
Peer::connect(socket, capab, total_diff, self_addr, &Handshake::new());
|
|
|
|
let added = add_to_peers(peers, adapter1, connect);
|
|
|
|
with_timeout(Box::new(added), &h)
|
2016-12-11 06:11:49 +03:00
|
|
|
})
|
2017-02-19 05:42:34 +03:00
|
|
|
.and_then(move |(socket, peer)| {
|
|
|
|
h2.spawn(peer.run(socket, adapter2).map_err(|e| {
|
|
|
|
error!("Peer error: {:?}", e);
|
|
|
|
()
|
|
|
|
}));
|
|
|
|
Ok(Some(peer))
|
|
|
|
});
|
2016-12-11 06:11:49 +03:00
|
|
|
Box::new(request)
|
2016-11-06 02:31:45 +03:00
|
|
|
}
|
|
|
|
|
2017-02-28 01:17:53 +03:00
|
|
|
/// Have the server iterate over its peer list and prune all peers we have
|
|
|
|
/// lost connection to or have been deemed problematic. The removed peers
|
|
|
|
/// are returned.
|
|
|
|
pub fn clean_peers(&self) -> Vec<Arc<Peer>> {
|
|
|
|
let mut peers = self.peers.write().unwrap();
|
|
|
|
|
|
|
|
let (keep, rm) = peers.iter().fold((vec![], vec![]), |mut acc, ref p| {
|
|
|
|
if p.clone().is_connected() {
|
|
|
|
acc.0.push((*p).clone());
|
|
|
|
} else {
|
|
|
|
acc.1.push((*p).clone());
|
|
|
|
}
|
|
|
|
acc
|
|
|
|
});
|
|
|
|
*peers = keep;
|
|
|
|
rm
|
|
|
|
}
|
|
|
|
|
2017-02-08 00:52:17 +03:00
|
|
|
/// Returns the peer with the most worked branch, showing the highest total
|
|
|
|
/// difficulty.
|
|
|
|
pub fn most_work_peer(&self) -> Option<Arc<Peer>> {
|
|
|
|
let peers = self.peers.read().unwrap();
|
|
|
|
if peers.len() == 0 {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
let mut res = peers[0].clone();
|
|
|
|
for p in peers.deref() {
|
2017-02-28 01:17:53 +03:00
|
|
|
if p.is_connected() && res.info.total_difficulty < p.info.total_difficulty {
|
2017-02-08 00:52:17 +03:00
|
|
|
res = (*p).clone();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Some(res)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a random peer we're connected to.
|
|
|
|
pub fn random_peer(&self) -> Option<Arc<Peer>> {
|
|
|
|
let peers = self.peers.read().unwrap();
|
|
|
|
if peers.len() == 0 {
|
|
|
|
None
|
|
|
|
} else {
|
|
|
|
let idx = rand::thread_rng().gen_range(0, peers.len());
|
|
|
|
Some(peers[idx].clone())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-21 04:33:20 +03:00
|
|
|
/// 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() {
|
2017-02-28 01:17:53 +03:00
|
|
|
if p.is_connected() {
|
|
|
|
if let Err(e) = p.send_block(b) {
|
|
|
|
debug!("Error sending block to peer: {:?}", e);
|
|
|
|
}
|
2016-12-21 04:33:20 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-30 02:52:01 +03:00
|
|
|
/// Number of peers we're currently connected to.
|
2017-02-08 00:52:17 +03:00
|
|
|
pub fn peer_count(&self) -> u32 {
|
2016-12-14 03:05:24 +03:00
|
|
|
self.peers.read().unwrap().len() as u32
|
|
|
|
}
|
|
|
|
|
2016-11-01 20:42:33 +03:00
|
|
|
/// Stops the server. Disconnect from all peers at the same time.
|
2016-12-11 06:11:49 +03:00
|
|
|
pub fn stop(self) {
|
2016-10-31 04:23:52 +03:00
|
|
|
let peers = self.peers.write().unwrap();
|
|
|
|
for p in peers.deref() {
|
|
|
|
p.stop();
|
|
|
|
}
|
2016-12-11 06:11:49 +03:00
|
|
|
self.stop.into_inner().unwrap().complete(());
|
2016-10-31 04:23:52 +03:00
|
|
|
}
|
2016-10-24 00:02:02 +03:00
|
|
|
}
|
2016-12-12 00:04:52 +03:00
|
|
|
|
|
|
|
// Adds the peer built by the provided future in the peers map
|
|
|
|
fn add_to_peers<A>(peers: Arc<RwLock<Vec<Arc<Peer>>>>,
|
2017-02-19 05:42:34 +03:00
|
|
|
adapter: Arc<NetAdapter>,
|
2016-12-12 00:04:52 +03:00
|
|
|
peer_fut: A)
|
|
|
|
-> Box<Future<Item = Result<(TcpStream, Arc<Peer>), ()>, Error = Error>>
|
|
|
|
where A: IntoFuture<Item = (TcpStream, Peer), Error = Error> + 'static
|
|
|
|
{
|
|
|
|
let peer_add = peer_fut.into_future().map(move |(conn, peer)| {
|
2017-02-19 05:42:34 +03:00
|
|
|
adapter.peer_connected(&peer.info);
|
2016-12-12 00:04:52 +03:00
|
|
|
let apeer = Arc::new(peer);
|
|
|
|
let mut peers = peers.write().unwrap();
|
|
|
|
peers.push(apeer.clone());
|
|
|
|
Ok((conn, apeer))
|
|
|
|
});
|
|
|
|
Box::new(peer_add)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Adds a timeout to a future
|
|
|
|
fn with_timeout<T: 'static>(fut: Box<Future<Item = Result<T, ()>, Error = Error>>,
|
|
|
|
h: &reactor::Handle)
|
|
|
|
-> Box<Future<Item = T, Error = Error>> {
|
|
|
|
let timeout = reactor::Timeout::new(Duration::new(5, 0), h).unwrap();
|
2017-02-27 07:08:40 +03:00
|
|
|
let timed = fut.select(timeout.map(Err).from_err())
|
2016-12-12 00:04:52 +03:00
|
|
|
.then(|res| {
|
|
|
|
match res {
|
|
|
|
Ok((Ok(inner), _timeout)) => Ok(inner),
|
2017-02-27 07:08:40 +03:00
|
|
|
Ok((_, _accept)) => Err(Error::Timeout),
|
2016-12-12 00:04:52 +03:00
|
|
|
Err((e, _other)) => Err(e),
|
|
|
|
}
|
|
|
|
});
|
|
|
|
Box::new(timed)
|
|
|
|
}
|