2016-10-25 07:35:10 +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.
|
|
|
|
|
2017-02-19 05:42:34 +03:00
|
|
|
use std::net::SocketAddr;
|
2017-11-01 02:32:33 +03:00
|
|
|
use std::sync::{Arc, RwLock};
|
2016-12-16 01:57:04 +03:00
|
|
|
|
2016-12-11 06:11:49 +03:00
|
|
|
use futures::Future;
|
2017-12-14 15:19:43 +03:00
|
|
|
use futures_cpupool::CpuPool;
|
2016-12-11 06:11:49 +03:00
|
|
|
use tokio_core::net::TcpStream;
|
2016-10-25 07:35:10 +03:00
|
|
|
|
2016-11-01 20:42:33 +03:00
|
|
|
use core::core;
|
2017-10-26 20:48:51 +03:00
|
|
|
use core::core::hash::{Hash, Hashed};
|
2017-02-08 00:52:17 +03:00
|
|
|
use core::core::target::Difficulty;
|
2016-10-29 22:36:45 +03:00
|
|
|
use handshake::Handshake;
|
2016-10-26 08:06:13 +03:00
|
|
|
use types::*;
|
2017-10-12 19:56:44 +03:00
|
|
|
use util::LOGGER;
|
2016-10-25 07:35:10 +03:00
|
|
|
|
2017-10-26 20:48:51 +03:00
|
|
|
const MAX_TRACK_SIZE: usize = 30;
|
|
|
|
|
2017-02-28 01:17:53 +03:00
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
2017-02-27 07:08:40 +03:00
|
|
|
enum State {
|
|
|
|
Connected,
|
|
|
|
Disconnected,
|
|
|
|
Banned,
|
|
|
|
}
|
|
|
|
|
2016-10-29 22:36:45 +03:00
|
|
|
pub struct Peer {
|
2017-02-08 00:52:17 +03:00
|
|
|
pub info: PeerInfo,
|
2016-10-31 04:23:52 +03:00
|
|
|
proto: Box<Protocol>,
|
2017-02-27 07:08:40 +03:00
|
|
|
state: Arc<RwLock<State>>,
|
2017-10-26 20:48:51 +03:00
|
|
|
// set of all hashes known to this peer (so no need to send)
|
|
|
|
tracking_adapter: TrackingAdapter,
|
2016-10-26 08:06:13 +03:00
|
|
|
}
|
2016-10-25 07:35:10 +03:00
|
|
|
|
2016-10-29 22:36:45 +03:00
|
|
|
unsafe impl Sync for Peer {}
|
|
|
|
unsafe impl Send for Peer {}
|
|
|
|
|
|
|
|
impl Peer {
|
2017-10-26 20:48:51 +03:00
|
|
|
// Only accept and connect can be externally used to build a peer
|
|
|
|
fn new(info: PeerInfo, proto: Box<Protocol>, na: Arc<NetAdapter>) -> Peer {
|
|
|
|
Peer {
|
|
|
|
info: info,
|
|
|
|
proto: proto,
|
|
|
|
state: Arc::new(RwLock::new(State::Connected)),
|
|
|
|
tracking_adapter: TrackingAdapter::new(na),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-30 02:52:01 +03:00
|
|
|
/// Initiates the handshake with another peer.
|
2017-10-26 20:48:51 +03:00
|
|
|
pub fn connect(
|
|
|
|
conn: TcpStream,
|
|
|
|
capab: Capabilities,
|
|
|
|
total_difficulty: Difficulty,
|
|
|
|
self_addr: SocketAddr,
|
2017-11-14 21:57:16 +03:00
|
|
|
hs: Arc<Handshake>,
|
2017-10-26 20:48:51 +03:00
|
|
|
na: Arc<NetAdapter>,
|
|
|
|
) -> Box<Future<Item = (TcpStream, Peer), Error = Error>> {
|
2017-02-19 05:42:34 +03:00
|
|
|
let connect_peer = hs.connect(capab, total_difficulty, self_addr, conn)
|
|
|
|
.and_then(|(conn, proto, info)| {
|
2017-10-26 20:48:51 +03:00
|
|
|
Ok((conn, Peer::new(info, Box::new(proto), na)))
|
2017-02-19 05:42:34 +03:00
|
|
|
});
|
2016-12-11 06:11:49 +03:00
|
|
|
Box::new(connect_peer)
|
2016-10-31 04:23:52 +03:00
|
|
|
}
|
2016-10-29 22:36:45 +03:00
|
|
|
|
2017-01-30 02:52:01 +03:00
|
|
|
/// Accept a handshake initiated by another peer.
|
2017-10-26 20:48:51 +03:00
|
|
|
pub fn accept(
|
|
|
|
conn: TcpStream,
|
|
|
|
capab: Capabilities,
|
|
|
|
total_difficulty: Difficulty,
|
|
|
|
hs: &Handshake,
|
|
|
|
na: Arc<NetAdapter>,
|
|
|
|
) -> Box<Future<Item = (TcpStream, Peer), Error = Error>> {
|
2017-11-01 02:32:33 +03:00
|
|
|
let hs_peer = hs.handshake(capab, total_difficulty, conn)
|
|
|
|
.and_then(|(conn, proto, info)| {
|
2017-10-26 20:48:51 +03:00
|
|
|
Ok((conn, Peer::new(info, Box::new(proto), na)))
|
2017-11-01 02:32:33 +03:00
|
|
|
});
|
2016-12-11 06:11:49 +03:00
|
|
|
Box::new(hs_peer)
|
2016-10-31 04:23:52 +03:00
|
|
|
}
|
|
|
|
|
2017-01-30 02:52:01 +03:00
|
|
|
/// Main peer loop listening for messages and forwarding to the rest of the
|
|
|
|
/// system.
|
2017-12-14 15:19:43 +03:00
|
|
|
pub fn run(&self, conn: TcpStream, pool: CpuPool) -> Box<Future<Item = (), Error = Error>> {
|
2017-02-08 00:52:17 +03:00
|
|
|
let addr = self.info.addr;
|
2017-02-27 07:08:40 +03:00
|
|
|
let state = self.state.clone();
|
2017-10-26 20:48:51 +03:00
|
|
|
let adapter = Arc::new(self.tracking_adapter.clone());
|
2017-11-20 04:33:45 +03:00
|
|
|
|
2017-12-14 15:19:43 +03:00
|
|
|
Box::new(self.proto.handle(conn, adapter, addr, pool).then(move |res| {
|
2017-02-28 01:17:53 +03:00
|
|
|
// handle disconnection, standard disconnections aren't considered an error
|
2017-02-27 07:08:40 +03:00
|
|
|
let mut state = state.write().unwrap();
|
|
|
|
match res {
|
2017-08-10 03:54:10 +03:00
|
|
|
Ok(_) => {
|
2017-02-27 07:08:40 +03:00
|
|
|
*state = State::Disconnected;
|
2017-10-12 19:56:44 +03:00
|
|
|
info!(LOGGER, "Client {} disconnected.", addr);
|
2017-02-27 07:08:40 +03:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
Err(Error::Serialization(e)) => {
|
|
|
|
*state = State::Banned;
|
2017-10-12 19:56:44 +03:00
|
|
|
info!(LOGGER, "Client {} corrupted, ban.", addr);
|
2017-02-27 07:08:40 +03:00
|
|
|
Err(Error::Serialization(e))
|
|
|
|
}
|
2017-10-12 22:26:10 +03:00
|
|
|
Err(e) => {
|
2017-02-27 07:08:40 +03:00
|
|
|
*state = State::Disconnected;
|
2017-12-18 16:17:11 +03:00
|
|
|
debug!(LOGGER, "Client {} connection lost: {:?}", addr, e);
|
2017-02-27 07:08:40 +03:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
2017-02-08 00:52:17 +03:00
|
|
|
}))
|
2016-11-01 20:42:33 +03:00
|
|
|
}
|
|
|
|
|
2018-01-31 00:44:13 +03:00
|
|
|
pub fn is_denied(config: P2PConfig, peer_addr: SocketAddr) -> bool {
|
|
|
|
let peer = format!("{}:{}", peer_addr.ip(), peer_addr.port());
|
|
|
|
if let Some(ref denied) = config.peers_deny {
|
|
|
|
if denied.contains(&peer) {
|
|
|
|
debug!(LOGGER, "checking peer allowed/denied: {:?} explicitly denied", peer_addr);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if let Some(ref allowed) = config.peers_allow {
|
|
|
|
if allowed.contains(&peer) {
|
|
|
|
debug!(LOGGER, "checking peer allowed/denied: {:?} explicitly allowed", peer_addr);
|
|
|
|
return false;
|
|
|
|
} else {
|
|
|
|
debug!(LOGGER, "checking peer allowed/denied: {:?} not explicitly allowed, denying", peer_addr);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// default to allowing peer connection if we do not explicitly allow or deny the peer
|
|
|
|
false
|
|
|
|
}
|
|
|
|
|
2017-02-28 01:17:53 +03:00
|
|
|
/// Whether this peer is still connected.
|
|
|
|
pub fn is_connected(&self) -> bool {
|
|
|
|
let state = self.state.read().unwrap();
|
|
|
|
*state == State::Connected
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Whether this peer has been banned.
|
|
|
|
pub fn is_banned(&self) -> bool {
|
|
|
|
let state = self.state.read().unwrap();
|
|
|
|
*state == State::Banned
|
|
|
|
}
|
|
|
|
|
2017-11-28 07:44:33 +03:00
|
|
|
/// Set this peer status to banned
|
|
|
|
pub fn set_banned(&self) {
|
|
|
|
let mut state = self.state.write().unwrap();
|
|
|
|
*state = State::Banned;
|
|
|
|
}
|
|
|
|
|
2017-01-30 02:52:01 +03:00
|
|
|
/// Bytes sent and received by this peer to the remote peer.
|
2016-10-31 22:29:08 +03:00
|
|
|
pub fn transmitted_bytes(&self) -> (u64, u64) {
|
|
|
|
self.proto.transmitted_bytes()
|
2016-10-31 04:23:52 +03:00
|
|
|
}
|
|
|
|
|
2017-12-14 00:52:21 +03:00
|
|
|
pub fn send_ping(&self, total_difficulty: Difficulty, height: u64) -> Result<(), Error> {
|
|
|
|
self.proto.send_ping(total_difficulty, height)
|
2016-12-11 06:11:49 +03:00
|
|
|
}
|
|
|
|
|
2016-12-21 04:33:20 +03:00
|
|
|
/// 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> {
|
2017-10-26 20:48:51 +03:00
|
|
|
if !self.tracking_adapter.has(b.hash()) {
|
2017-12-14 00:52:21 +03:00
|
|
|
debug!(LOGGER, "Send block {} to {}", b.hash(), self.info.addr);
|
2017-10-26 20:48:51 +03:00
|
|
|
self.proto.send_block(b)
|
|
|
|
} else {
|
2018-01-30 17:42:04 +03:00
|
|
|
debug!(
|
|
|
|
LOGGER,
|
|
|
|
"Suppress block send {} to {} (already seen)",
|
|
|
|
b.hash(),
|
|
|
|
self.info.addr,
|
|
|
|
);
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn send_header(&self, bh: &core::BlockHeader) -> Result<(), Error> {
|
|
|
|
if !self.tracking_adapter.has(bh.hash()) {
|
|
|
|
debug!(LOGGER, "Send header {} to {}", bh.hash(), self.info.addr);
|
|
|
|
self.proto.send_header(bh)
|
|
|
|
} else {
|
|
|
|
debug!(
|
|
|
|
LOGGER,
|
|
|
|
"Suppress header send {} to {} (already seen)",
|
|
|
|
bh.hash(),
|
|
|
|
self.info.addr,
|
|
|
|
);
|
2017-10-26 20:48:51 +03:00
|
|
|
Ok(())
|
|
|
|
}
|
2016-12-21 04:33:20 +03:00
|
|
|
}
|
|
|
|
|
2017-10-26 00:06:24 +03:00
|
|
|
/// Sends the provided transaction to the remote peer. The request may be
|
|
|
|
/// dropped if the remote peer is known to already have the transaction.
|
|
|
|
pub fn send_transaction(&self, tx: &core::Transaction) -> Result<(), Error> {
|
2017-10-26 20:48:51 +03:00
|
|
|
if !self.tracking_adapter.has(tx.hash()) {
|
2018-01-30 17:42:04 +03:00
|
|
|
debug!(LOGGER, "Send tx {} to {}", tx.hash(), self.info.addr);
|
2017-10-26 20:48:51 +03:00
|
|
|
self.proto.send_transaction(tx)
|
|
|
|
} else {
|
2018-01-30 17:42:04 +03:00
|
|
|
debug!(LOGGER, "Not sending tx {} to {} (already seen)", tx.hash(), self.info.addr);
|
2017-10-26 20:48:51 +03:00
|
|
|
Ok(())
|
|
|
|
}
|
2017-10-26 00:06:24 +03:00
|
|
|
}
|
|
|
|
|
2017-02-08 00:52:17 +03:00
|
|
|
pub fn send_header_request(&self, locator: Vec<Hash>) -> Result<(), Error> {
|
|
|
|
self.proto.send_header_request(locator)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn send_block_request(&self, h: Hash) -> Result<(), Error> {
|
2018-01-30 17:42:04 +03:00
|
|
|
debug!(LOGGER, "Requesting block {} from {}", h, self.info.addr);
|
2017-02-08 00:52:17 +03:00
|
|
|
self.proto.send_block_request(h)
|
|
|
|
}
|
|
|
|
|
2017-02-19 05:42:34 +03:00
|
|
|
pub fn send_peer_request(&self, capab: Capabilities) -> Result<(), Error> {
|
2017-10-12 19:56:44 +03:00
|
|
|
debug!(LOGGER, "Asking {} for more peers.", self.info.addr);
|
2017-02-19 05:42:34 +03:00
|
|
|
self.proto.send_peer_request(capab)
|
|
|
|
}
|
|
|
|
|
2016-10-31 04:23:52 +03:00
|
|
|
pub fn stop(&self) {
|
2016-12-11 06:11:49 +03:00
|
|
|
self.proto.close();
|
2016-10-31 04:23:52 +03:00
|
|
|
}
|
2016-10-25 07:35:10 +03:00
|
|
|
}
|
2017-10-26 20:48:51 +03:00
|
|
|
|
|
|
|
/// Adapter implementation that forwards everything to an underlying adapter
|
|
|
|
/// but keeps track of the block and transaction hashes that were received.
|
|
|
|
#[derive(Clone)]
|
|
|
|
struct TrackingAdapter {
|
|
|
|
adapter: Arc<NetAdapter>,
|
|
|
|
known: Arc<RwLock<Vec<Hash>>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TrackingAdapter {
|
|
|
|
fn new(adapter: Arc<NetAdapter>) -> TrackingAdapter {
|
|
|
|
TrackingAdapter {
|
|
|
|
adapter: adapter,
|
|
|
|
known: Arc::new(RwLock::new(vec![])),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn has(&self, hash: Hash) -> bool {
|
|
|
|
let known = self.known.read().unwrap();
|
|
|
|
// may become too slow, an ordered set (by timestamp for eviction) may
|
2018-01-30 17:42:04 +03:00
|
|
|
// end up being a better choice
|
2017-10-26 20:48:51 +03:00
|
|
|
known.contains(&hash)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn push(&self, hash: Hash) {
|
|
|
|
let mut known = self.known.write().unwrap();
|
|
|
|
if known.len() > MAX_TRACK_SIZE {
|
|
|
|
known.truncate(MAX_TRACK_SIZE);
|
|
|
|
}
|
|
|
|
known.insert(0, hash);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-12 19:40:26 +03:00
|
|
|
impl ChainAdapter for TrackingAdapter {
|
2017-10-26 20:48:51 +03:00
|
|
|
fn total_difficulty(&self) -> Difficulty {
|
|
|
|
self.adapter.total_difficulty()
|
|
|
|
}
|
|
|
|
|
2017-12-14 00:52:21 +03:00
|
|
|
fn total_height(&self) -> u64 {
|
|
|
|
self.adapter.total_height()
|
|
|
|
}
|
|
|
|
|
2017-10-26 20:48:51 +03:00
|
|
|
fn transaction_received(&self, tx: core::Transaction) {
|
|
|
|
self.push(tx.hash());
|
|
|
|
self.adapter.transaction_received(tx)
|
|
|
|
}
|
|
|
|
|
2017-12-12 19:40:26 +03:00
|
|
|
fn block_received(&self, b: core::Block, addr: SocketAddr) -> bool {
|
2017-10-26 20:48:51 +03:00
|
|
|
self.push(b.hash());
|
2017-11-28 07:44:33 +03:00
|
|
|
self.adapter.block_received(b, addr)
|
2017-10-26 20:48:51 +03:00
|
|
|
}
|
|
|
|
|
2018-01-30 17:42:04 +03:00
|
|
|
fn header_received(&self, bh: core::BlockHeader, addr: SocketAddr) -> bool {
|
|
|
|
self.push(bh.hash());
|
|
|
|
self.adapter.header_received(bh, addr)
|
|
|
|
}
|
|
|
|
|
2017-11-30 18:27:50 +03:00
|
|
|
fn headers_received(&self, bh: Vec<core::BlockHeader>, addr: SocketAddr) {
|
|
|
|
self.adapter.headers_received(bh, addr)
|
2017-10-26 20:48:51 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
fn locate_headers(&self, locator: Vec<Hash>) -> Vec<core::BlockHeader> {
|
|
|
|
self.adapter.locate_headers(locator)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_block(&self, h: Hash) -> Option<core::Block> {
|
|
|
|
self.adapter.get_block(h)
|
|
|
|
}
|
2017-12-12 19:40:26 +03:00
|
|
|
}
|
2017-10-26 20:48:51 +03:00
|
|
|
|
2017-12-12 19:40:26 +03:00
|
|
|
impl NetAdapter for TrackingAdapter {
|
2017-10-26 20:48:51 +03:00
|
|
|
fn find_peer_addrs(&self, capab: Capabilities) -> Vec<SocketAddr> {
|
|
|
|
self.adapter.find_peer_addrs(capab)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn peer_addrs_received(&self, addrs: Vec<SocketAddr>) {
|
|
|
|
self.adapter.peer_addrs_received(addrs)
|
|
|
|
}
|
|
|
|
|
2017-12-14 00:52:21 +03:00
|
|
|
fn peer_difficulty(&self, addr: SocketAddr, diff: Difficulty, height:u64) {
|
|
|
|
self.adapter.peer_difficulty(addr, diff, height)
|
2017-11-21 17:24:29 +03:00
|
|
|
}
|
2017-10-26 20:48:51 +03:00
|
|
|
}
|