slog-rs logging (#171)
* added global slog instance, changed all logging macro formats to include logger instance * adding configuration to logging, allowing for multiple log outputs * updates to test, changes to build docs * rustfmt * moving logging functions into util crate
This commit is contained in:
committed by
Ignotus Peverell
parent
b85006ebe5
commit
8e382a7593
+48
-66
@@ -34,6 +34,7 @@ use core::ser;
|
||||
use msg::*;
|
||||
use types::Error;
|
||||
use rate_limit::*;
|
||||
use util::LOGGER;
|
||||
|
||||
/// Handler to provide to the connection, will be called back anytime a message
|
||||
/// is received. The provided sender can be use to immediately send back
|
||||
@@ -42,26 +43,22 @@ pub trait Handler: Sync + Send {
|
||||
/// Handle function to implement to process incoming messages. A sender to
|
||||
/// reply immediately as well as the message header and its unparsed body
|
||||
/// are provided.
|
||||
fn handle(
|
||||
&self,
|
||||
sender: UnboundedSender<Vec<u8>>,
|
||||
header: MsgHeader,
|
||||
body: Vec<u8>,
|
||||
) -> Result<Option<Hash>, ser::Error>;
|
||||
fn handle(&self,
|
||||
sender: UnboundedSender<Vec<u8>>,
|
||||
header: MsgHeader,
|
||||
body: Vec<u8>)
|
||||
-> Result<Option<Hash>, ser::Error>;
|
||||
}
|
||||
|
||||
impl<F> Handler for F
|
||||
where
|
||||
F: Fn(UnboundedSender<Vec<u8>>, MsgHeader, Vec<u8>)
|
||||
-> Result<Option<Hash>, ser::Error>,
|
||||
F: Sync + Send,
|
||||
where F: Fn(UnboundedSender<Vec<u8>>, MsgHeader, Vec<u8>) -> Result<Option<Hash>, ser::Error>,
|
||||
F: Sync + Send
|
||||
{
|
||||
fn handle(
|
||||
&self,
|
||||
sender: UnboundedSender<Vec<u8>>,
|
||||
header: MsgHeader,
|
||||
body: Vec<u8>,
|
||||
) -> Result<Option<Hash>, ser::Error> {
|
||||
fn handle(&self,
|
||||
sender: UnboundedSender<Vec<u8>>,
|
||||
header: MsgHeader,
|
||||
body: Vec<u8>)
|
||||
-> Result<Option<Hash>, ser::Error> {
|
||||
self(sender, header, body)
|
||||
}
|
||||
}
|
||||
@@ -91,12 +88,10 @@ impl Connection {
|
||||
/// Start listening on the provided connection and wraps it. Does not hang
|
||||
/// the current thread, instead just returns a future and the Connection
|
||||
/// itself.
|
||||
pub fn listen<F>(
|
||||
conn: TcpStream,
|
||||
handler: F,
|
||||
) -> (Connection, Box<Future<Item = (), Error = Error>>)
|
||||
where
|
||||
F: Handler + 'static,
|
||||
pub fn listen<F>(conn: TcpStream,
|
||||
handler: F)
|
||||
-> (Connection, Box<Future<Item = (), Error = Error>>)
|
||||
where F: Handler + 'static
|
||||
{
|
||||
|
||||
let (reader, writer) = conn.split();
|
||||
@@ -111,9 +106,9 @@ impl Connection {
|
||||
|
||||
// same for closing the connection
|
||||
let (close_tx, close_rx) = futures::sync::mpsc::channel(1);
|
||||
let close_conn = close_rx.for_each(|_| Ok(())).map_err(
|
||||
|_| Error::ConnectionClose,
|
||||
);
|
||||
let close_conn = close_rx
|
||||
.for_each(|_| Ok(()))
|
||||
.map_err(|_| Error::ConnectionClose);
|
||||
|
||||
let me = Connection {
|
||||
outbound_chan: tx.clone(),
|
||||
@@ -143,13 +138,11 @@ impl Connection {
|
||||
|
||||
/// Prepares the future that gets message data produced by our system and
|
||||
/// sends it to the peer connection
|
||||
fn write_msg<W>(
|
||||
&self,
|
||||
rx: UnboundedReceiver<Vec<u8>>,
|
||||
writer: W,
|
||||
) -> Box<Future<Item = W, Error = Error>>
|
||||
where
|
||||
W: AsyncWrite + 'static,
|
||||
fn write_msg<W>(&self,
|
||||
rx: UnboundedReceiver<Vec<u8>>,
|
||||
writer: W)
|
||||
-> Box<Future<Item = W, Error = Error>>
|
||||
where W: AsyncWrite + 'static
|
||||
{
|
||||
|
||||
let sent_bytes = self.sent_bytes.clone();
|
||||
@@ -170,15 +163,13 @@ impl Connection {
|
||||
|
||||
/// Prepares the future reading from the peer connection, parsing each
|
||||
/// message and forwarding them appropriately based on their type
|
||||
fn read_msg<F, R>(
|
||||
&self,
|
||||
sender: UnboundedSender<Vec<u8>>,
|
||||
reader: R,
|
||||
handler: F,
|
||||
) -> Box<Future<Item = R, Error = Error>>
|
||||
where
|
||||
F: Handler + 'static,
|
||||
R: AsyncRead + 'static,
|
||||
fn read_msg<F, R>(&self,
|
||||
sender: UnboundedSender<Vec<u8>>,
|
||||
reader: R,
|
||||
handler: F)
|
||||
-> Box<Future<Item = R, Error = Error>>
|
||||
where F: Handler + 'static,
|
||||
R: AsyncRead + 'static
|
||||
{
|
||||
|
||||
// infinite iterator stream so we repeat the message reading logic until the
|
||||
@@ -215,7 +206,7 @@ impl Connection {
|
||||
// and handle the different message types
|
||||
let msg_type = header.msg_type;
|
||||
if let Err(e) = handler.handle(sender_inner.clone(), header, buf) {
|
||||
debug!("Invalid {:?} message: {}", msg_type, e);
|
||||
debug!(LOGGER, "Invalid {:?} message: {}", msg_type, e);
|
||||
return Err(Error::Serialization(e));
|
||||
}
|
||||
|
||||
@@ -232,15 +223,12 @@ impl Connection {
|
||||
let mut body_data = vec![];
|
||||
try!(ser::serialize(&mut body_data, body));
|
||||
let mut data = vec![];
|
||||
try!(ser::serialize(
|
||||
&mut data,
|
||||
&MsgHeader::new(t, body_data.len() as u64),
|
||||
));
|
||||
try!(ser::serialize(&mut data, &MsgHeader::new(t, body_data.len() as u64)));
|
||||
data.append(&mut body_data);
|
||||
|
||||
self.outbound_chan.unbounded_send(data).map_err(
|
||||
|_| Error::ConnectionClose,
|
||||
)
|
||||
self.outbound_chan
|
||||
.unbounded_send(data)
|
||||
.map_err(|_| Error::ConnectionClose)
|
||||
}
|
||||
|
||||
/// Bytes sent and received by this peer to the remote peer.
|
||||
@@ -261,12 +249,10 @@ pub struct TimeoutConnection {
|
||||
|
||||
impl TimeoutConnection {
|
||||
/// Same as Connection
|
||||
pub fn listen<F>(
|
||||
conn: TcpStream,
|
||||
handler: F,
|
||||
) -> (TimeoutConnection, Box<Future<Item = (), Error = Error>>)
|
||||
where
|
||||
F: Handler + 'static,
|
||||
pub fn listen<F>(conn: TcpStream,
|
||||
handler: F)
|
||||
-> (TimeoutConnection, Box<Future<Item = (), Error = Error>>)
|
||||
where F: Handler + 'static
|
||||
{
|
||||
|
||||
let expects = Arc::new(Mutex::new(vec![]));
|
||||
@@ -310,21 +296,17 @@ impl TimeoutConnection {
|
||||
underlying: conn,
|
||||
expected_responses: expects,
|
||||
};
|
||||
(
|
||||
me,
|
||||
Box::new(fut.select(timer).map(|_| ()).map_err(|(e1, _)| e1)),
|
||||
)
|
||||
(me, Box::new(fut.select(timer).map(|_| ()).map_err(|(e1, _)| e1)))
|
||||
}
|
||||
|
||||
/// Sends a request and registers a timer on the provided message type and
|
||||
/// optionally the hash of the sent data.
|
||||
pub fn send_request<W: ser::Writeable>(
|
||||
&self,
|
||||
t: Type,
|
||||
rt: Type,
|
||||
body: &W,
|
||||
expect_h: Option<(Hash)>,
|
||||
) -> Result<(), Error> {
|
||||
pub fn send_request<W: ser::Writeable>(&self,
|
||||
t: Type,
|
||||
rt: Type,
|
||||
body: &W,
|
||||
expect_h: Option<(Hash)>)
|
||||
-> Result<(), Error> {
|
||||
let _sent = try!(self.underlying.send_msg(t, body));
|
||||
|
||||
let mut expects = self.expected_responses.lock().unwrap();
|
||||
|
||||
+14
-15
@@ -26,6 +26,7 @@ use core::ser;
|
||||
use msg::*;
|
||||
use types::*;
|
||||
use protocol::ProtocolV1;
|
||||
use util::LOGGER;
|
||||
|
||||
const NONCES_CAP: usize = 100;
|
||||
|
||||
@@ -47,13 +48,12 @@ impl Handshake {
|
||||
}
|
||||
|
||||
/// Handles connecting to a new remote peer, starting the version handshake.
|
||||
pub fn connect(
|
||||
&self,
|
||||
capab: Capabilities,
|
||||
total_difficulty: Difficulty,
|
||||
self_addr: SocketAddr,
|
||||
conn: TcpStream,
|
||||
) -> Box<Future<Item = (TcpStream, ProtocolV1, PeerInfo), Error = Error>> {
|
||||
pub fn connect(&self,
|
||||
capab: Capabilities,
|
||||
total_difficulty: Difficulty,
|
||||
self_addr: SocketAddr,
|
||||
conn: TcpStream)
|
||||
-> Box<Future<Item = (TcpStream, ProtocolV1, PeerInfo), Error = Error>> {
|
||||
// prepare the first part of the hanshake
|
||||
let nonce = self.next_nonce();
|
||||
let hand = Hand {
|
||||
@@ -85,7 +85,7 @@ impl Handshake {
|
||||
total_difficulty: shake.total_difficulty,
|
||||
};
|
||||
|
||||
info!("Connected to peer {:?}", peer_info);
|
||||
info!(LOGGER, "Connected to peer {:?}", peer_info);
|
||||
// when more than one protocol version is supported, choosing should go here
|
||||
Ok((conn, ProtocolV1::new(), peer_info))
|
||||
}
|
||||
@@ -95,12 +95,11 @@ impl Handshake {
|
||||
|
||||
/// Handles receiving a connection from a new remote peer that started the
|
||||
/// version handshake.
|
||||
pub fn handshake(
|
||||
&self,
|
||||
capab: Capabilities,
|
||||
total_difficulty: Difficulty,
|
||||
conn: TcpStream,
|
||||
) -> Box<Future<Item = (TcpStream, ProtocolV1, PeerInfo), Error = Error>> {
|
||||
pub fn handshake(&self,
|
||||
capab: Capabilities,
|
||||
total_difficulty: Difficulty,
|
||||
conn: TcpStream)
|
||||
-> Box<Future<Item = (TcpStream, ProtocolV1, PeerInfo), Error = Error>> {
|
||||
let nonces = self.nonces.clone();
|
||||
Box::new(
|
||||
read_msg::<Hand>(conn)
|
||||
@@ -139,7 +138,7 @@ impl Handshake {
|
||||
Ok((conn, shake, peer_info))
|
||||
})
|
||||
.and_then(|(conn, shake, peer_info)| {
|
||||
debug!("Success handshake with {}.", peer_info.addr);
|
||||
debug!(LOGGER, "Success handshake with {}.", peer_info.addr);
|
||||
write_msg(conn, shake, Type::Shake)
|
||||
// when more than one protocol version is supported, choosing should go here
|
||||
.map(|conn| (conn, ProtocolV1::new(), peer_info))
|
||||
|
||||
+1
-1
@@ -29,7 +29,7 @@ extern crate grin_core as core;
|
||||
extern crate grin_store;
|
||||
extern crate grin_util as util;
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
extern crate slog;
|
||||
extern crate futures;
|
||||
extern crate tokio_core;
|
||||
extern crate tokio_io;
|
||||
|
||||
+10
-21
@@ -70,8 +70,7 @@ enum_from_primitive! {
|
||||
/// the header first, handles its validation and then reads the Readable body,
|
||||
/// allocating buffers of the right size.
|
||||
pub fn read_msg<T>(conn: TcpStream) -> Box<Future<Item = (TcpStream, T), Error = Error>>
|
||||
where
|
||||
T: Readable + 'static,
|
||||
where T: Readable + 'static
|
||||
{
|
||||
let read_header = read_exact(conn, vec![0u8; HEADER_LEN as usize])
|
||||
.from_err()
|
||||
@@ -99,13 +98,11 @@ where
|
||||
/// Future combinator to write a full message from a Writeable payload.
|
||||
/// Serializes the payload first and then sends the message header and that
|
||||
/// payload.
|
||||
pub fn write_msg<T>(
|
||||
conn: TcpStream,
|
||||
msg: T,
|
||||
msg_type: Type,
|
||||
) -> Box<Future<Item = TcpStream, Error = Error>>
|
||||
where
|
||||
T: Writeable + 'static,
|
||||
pub fn write_msg<T>(conn: TcpStream,
|
||||
msg: T,
|
||||
msg_type: Type)
|
||||
-> Box<Future<Item = TcpStream, Error = Error>>
|
||||
where T: Writeable + 'static
|
||||
{
|
||||
let write_msg = ok((conn)).and_then(move |conn| {
|
||||
// prepare the body first so we know its serialized length
|
||||
@@ -226,9 +223,7 @@ impl Readable for Hand {
|
||||
let receiver_addr = try!(SockAddr::read(reader));
|
||||
let ua = try!(reader.read_vec());
|
||||
let user_agent = try!(String::from_utf8(ua).map_err(|_| ser::Error::CorruptedData));
|
||||
let capabilities = try!(Capabilities::from_bits(capab).ok_or(
|
||||
ser::Error::CorruptedData,
|
||||
));
|
||||
let capabilities = try!(Capabilities::from_bits(capab).ok_or(ser::Error::CorruptedData));
|
||||
Ok(Hand {
|
||||
version: version,
|
||||
capabilities: capabilities,
|
||||
@@ -275,9 +270,7 @@ impl Readable for Shake {
|
||||
let total_diff = try!(Difficulty::read(reader));
|
||||
let ua = try!(reader.read_vec());
|
||||
let user_agent = try!(String::from_utf8(ua).map_err(|_| ser::Error::CorruptedData));
|
||||
let capabilities = try!(Capabilities::from_bits(capab).ok_or(
|
||||
ser::Error::CorruptedData,
|
||||
));
|
||||
let capabilities = try!(Capabilities::from_bits(capab).ok_or(ser::Error::CorruptedData));
|
||||
Ok(Shake {
|
||||
version: version,
|
||||
capabilities: capabilities,
|
||||
@@ -302,9 +295,7 @@ impl Writeable for GetPeerAddrs {
|
||||
impl Readable for GetPeerAddrs {
|
||||
fn read(reader: &mut Reader) -> Result<GetPeerAddrs, ser::Error> {
|
||||
let capab = try!(reader.read_u32());
|
||||
let capabilities = try!(Capabilities::from_bits(capab).ok_or(
|
||||
ser::Error::CorruptedData,
|
||||
));
|
||||
let capabilities = try!(Capabilities::from_bits(capab).ok_or(ser::Error::CorruptedData));
|
||||
Ok(GetPeerAddrs { capabilities: capabilities })
|
||||
}
|
||||
}
|
||||
@@ -361,9 +352,7 @@ impl Writeable for PeerError {
|
||||
impl Readable for PeerError {
|
||||
fn read(reader: &mut Reader) -> Result<PeerError, ser::Error> {
|
||||
let (code, msg) = ser_multiread!(reader, read_u32, read_vec);
|
||||
let message = try!(String::from_utf8(msg).map_err(
|
||||
|_| ser::Error::CorruptedData,
|
||||
));
|
||||
let message = try!(String::from_utf8(msg).map_err(|_| ser::Error::CorruptedData));
|
||||
Ok(PeerError {
|
||||
code: code,
|
||||
message: message,
|
||||
|
||||
+41
-45
@@ -23,6 +23,7 @@ use core::core::hash::Hash;
|
||||
use core::core::target::Difficulty;
|
||||
use handshake::Handshake;
|
||||
use types::*;
|
||||
use util::LOGGER;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum State {
|
||||
@@ -42,58 +43,48 @@ unsafe impl Send for Peer {}
|
||||
|
||||
impl Peer {
|
||||
/// Initiates the handshake with another peer.
|
||||
pub fn connect(
|
||||
conn: TcpStream,
|
||||
capab: Capabilities,
|
||||
total_difficulty: Difficulty,
|
||||
self_addr: SocketAddr,
|
||||
hs: &Handshake,
|
||||
) -> Box<Future<Item = (TcpStream, Peer), Error = Error>> {
|
||||
pub fn connect(conn: TcpStream,
|
||||
capab: Capabilities,
|
||||
total_difficulty: Difficulty,
|
||||
self_addr: SocketAddr,
|
||||
hs: &Handshake)
|
||||
-> Box<Future<Item = (TcpStream, Peer), Error = Error>> {
|
||||
let connect_peer = hs.connect(capab, total_difficulty, self_addr, conn)
|
||||
.and_then(|(conn, proto, info)| {
|
||||
Ok((
|
||||
conn,
|
||||
Peer {
|
||||
info: info,
|
||||
proto: Box::new(proto),
|
||||
state: Arc::new(RwLock::new(State::Connected)),
|
||||
},
|
||||
))
|
||||
Ok((conn,
|
||||
Peer {
|
||||
info: info,
|
||||
proto: Box::new(proto),
|
||||
state: Arc::new(RwLock::new(State::Connected)),
|
||||
}))
|
||||
});
|
||||
Box::new(connect_peer)
|
||||
}
|
||||
|
||||
/// Accept a handshake initiated by another peer.
|
||||
pub fn accept(
|
||||
conn: TcpStream,
|
||||
capab: Capabilities,
|
||||
total_difficulty: Difficulty,
|
||||
hs: &Handshake,
|
||||
) -> Box<Future<Item = (TcpStream, Peer), Error = Error>> {
|
||||
let hs_peer = hs.handshake(capab, total_difficulty, conn).and_then(
|
||||
|(conn,
|
||||
proto,
|
||||
info)| {
|
||||
Ok((
|
||||
conn,
|
||||
Peer {
|
||||
info: info,
|
||||
proto: Box::new(proto),
|
||||
state: Arc::new(RwLock::new(State::Connected)),
|
||||
},
|
||||
))
|
||||
},
|
||||
);
|
||||
pub fn accept(conn: TcpStream,
|
||||
capab: Capabilities,
|
||||
total_difficulty: Difficulty,
|
||||
hs: &Handshake)
|
||||
-> Box<Future<Item = (TcpStream, Peer), Error = Error>> {
|
||||
let hs_peer = hs.handshake(capab, total_difficulty, conn)
|
||||
.and_then(|(conn, proto, info)| {
|
||||
Ok((conn,
|
||||
Peer {
|
||||
info: info,
|
||||
proto: Box::new(proto),
|
||||
state: Arc::new(RwLock::new(State::Connected)),
|
||||
}))
|
||||
});
|
||||
Box::new(hs_peer)
|
||||
}
|
||||
|
||||
/// Main peer loop listening for messages and forwarding to the rest of the
|
||||
/// system.
|
||||
pub fn run(
|
||||
&self,
|
||||
conn: TcpStream,
|
||||
na: Arc<NetAdapter>,
|
||||
) -> Box<Future<Item = (), Error = Error>> {
|
||||
pub fn run(&self,
|
||||
conn: TcpStream,
|
||||
na: Arc<NetAdapter>)
|
||||
-> Box<Future<Item = (), Error = Error>> {
|
||||
|
||||
let addr = self.info.addr;
|
||||
let state = self.state.clone();
|
||||
@@ -103,17 +94,17 @@ impl Peer {
|
||||
match res {
|
||||
Ok(_) => {
|
||||
*state = State::Disconnected;
|
||||
info!("Client {} disconnected.", addr);
|
||||
info!(LOGGER, "Client {} disconnected.", addr);
|
||||
Ok(())
|
||||
}
|
||||
Err(Error::Serialization(e)) => {
|
||||
*state = State::Banned;
|
||||
info!("Client {} corrupted, ban.", addr);
|
||||
info!(LOGGER, "Client {} corrupted, ban.", addr);
|
||||
Err(Error::Serialization(e))
|
||||
}
|
||||
Err(_) => {
|
||||
*state = State::Disconnected;
|
||||
info!("Client {} connection lost.", addr);
|
||||
info!(LOGGER, "Client {} connection lost.", addr);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -153,12 +144,17 @@ impl Peer {
|
||||
}
|
||||
|
||||
pub fn send_block_request(&self, h: Hash) -> Result<(), Error> {
|
||||
debug!("Requesting block {} from peer {}.", h, self.info.addr);
|
||||
debug!(
|
||||
LOGGER,
|
||||
"Requesting block {} from peer {}.",
|
||||
h,
|
||||
self.info.addr
|
||||
);
|
||||
self.proto.send_block_request(h)
|
||||
}
|
||||
|
||||
pub fn send_peer_request(&self, capab: Capabilities) -> Result<(), Error> {
|
||||
debug!("Asking {} for more peers.", self.info.addr);
|
||||
debug!(LOGGER, "Asking {} for more peers.", self.info.addr);
|
||||
self.proto.send_peer_request(capab)
|
||||
}
|
||||
|
||||
|
||||
+18
-23
@@ -24,6 +24,7 @@ use core::ser;
|
||||
use conn::TimeoutConnection;
|
||||
use msg::*;
|
||||
use types::*;
|
||||
use util::LOGGER;
|
||||
use util::OneTime;
|
||||
|
||||
#[allow(dead_code)]
|
||||
@@ -44,11 +45,10 @@ impl ProtocolV1 {
|
||||
|
||||
impl Protocol for ProtocolV1 {
|
||||
/// Sets up the protocol reading, writing and closing logic.
|
||||
fn handle(
|
||||
&self,
|
||||
conn: TcpStream,
|
||||
adapter: Arc<NetAdapter>,
|
||||
) -> Box<Future<Item = (), Error = Error>> {
|
||||
fn handle(&self,
|
||||
conn: TcpStream,
|
||||
adapter: Arc<NetAdapter>)
|
||||
-> Box<Future<Item = (), Error = Error>> {
|
||||
|
||||
let (conn, listener) = TimeoutConnection::listen(conn, move |sender, header, data| {
|
||||
let adapt = adapter.as_ref();
|
||||
@@ -114,23 +114,21 @@ impl ProtocolV1 {
|
||||
self.conn.borrow().send_msg(t, body)
|
||||
}
|
||||
|
||||
fn send_request<W: ser::Writeable>(
|
||||
&self,
|
||||
t: Type,
|
||||
rt: Type,
|
||||
body: &W,
|
||||
expect_resp: Option<Hash>,
|
||||
) -> Result<(), Error> {
|
||||
fn send_request<W: ser::Writeable>(&self,
|
||||
t: Type,
|
||||
rt: Type,
|
||||
body: &W,
|
||||
expect_resp: Option<Hash>)
|
||||
-> Result<(), Error> {
|
||||
self.conn.borrow().send_request(t, rt, body, expect_resp)
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_payload(
|
||||
adapter: &NetAdapter,
|
||||
sender: UnboundedSender<Vec<u8>>,
|
||||
header: MsgHeader,
|
||||
buf: Vec<u8>,
|
||||
) -> Result<Option<Hash>, ser::Error> {
|
||||
fn handle_payload(adapter: &NetAdapter,
|
||||
sender: UnboundedSender<Vec<u8>>,
|
||||
header: MsgHeader,
|
||||
buf: Vec<u8>)
|
||||
-> Result<Option<Hash>, ser::Error> {
|
||||
match header.msg_type {
|
||||
Type::Ping => {
|
||||
let data = ser::ser_vec(&MsgHeader::new(Type::Pong, 0))?;
|
||||
@@ -173,10 +171,7 @@ fn handle_payload(
|
||||
|
||||
// serialize and send all the headers over
|
||||
let mut body_data = vec![];
|
||||
try!(ser::serialize(
|
||||
&mut body_data,
|
||||
&Headers { headers: headers },
|
||||
));
|
||||
try!(ser::serialize(&mut body_data, &Headers { headers: headers }));
|
||||
let mut data = vec![];
|
||||
try!(ser::serialize(
|
||||
&mut data,
|
||||
@@ -220,7 +215,7 @@ fn handle_payload(
|
||||
Ok(None)
|
||||
}
|
||||
_ => {
|
||||
debug!("unknown message type {:?}", header.msg_type);
|
||||
debug!(LOGGER, "unknown message type {:?}", header.msg_type);
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,10 +77,7 @@ impl<R: AsyncRead> io::Read for ThrottledReader<R> {
|
||||
|
||||
// Check if Allowed
|
||||
if self.allowed < 1 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::WouldBlock,
|
||||
"Reached Allowed Read Limit",
|
||||
));
|
||||
return Err(io::Error::new(io::ErrorKind::WouldBlock, "Reached Allowed Read Limit"));
|
||||
}
|
||||
|
||||
// Read Max Allowed
|
||||
@@ -158,10 +155,7 @@ impl<W: AsyncWrite> io::Write for ThrottledWriter<W> {
|
||||
|
||||
// Check if Allowed
|
||||
if self.allowed < 1 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::WouldBlock,
|
||||
"Reached Allowed Write Limit",
|
||||
));
|
||||
return Err(io::Error::new(io::ErrorKind::WouldBlock, "Reached Allowed Write Limit"));
|
||||
}
|
||||
|
||||
// Write max allowed
|
||||
|
||||
+21
-25
@@ -34,6 +34,7 @@ use core::core::target::Difficulty;
|
||||
use handshake::Handshake;
|
||||
use peer::Peer;
|
||||
use types::*;
|
||||
use util::LOGGER;
|
||||
|
||||
/// A no-op network adapter used for testing.
|
||||
pub struct DummyAdapter {}
|
||||
@@ -88,7 +89,7 @@ impl Server {
|
||||
pub fn start(&self, h: reactor::Handle) -> Box<Future<Item = (), Error = Error>> {
|
||||
let addr = SocketAddr::new(self.config.host, self.config.port);
|
||||
let socket = TcpListener::bind(&addr, &h.clone()).unwrap();
|
||||
warn!("P2P server started on {}", addr);
|
||||
warn!(LOGGER, "P2P server started on {}", addr);
|
||||
|
||||
let hs = Arc::new(Handshake::new());
|
||||
let peers = self.peers.clone();
|
||||
@@ -118,7 +119,7 @@ impl Server {
|
||||
let server = peers.for_each(move |peer| {
|
||||
hs.spawn(peer.then(|res| {
|
||||
match res {
|
||||
Err(e) => info!("Client error: {:?}", e),
|
||||
Err(e) => info!(LOGGER, "Client error: {:?}", e),
|
||||
_ => {}
|
||||
}
|
||||
futures::finished(())
|
||||
@@ -143,11 +144,10 @@ impl Server {
|
||||
}
|
||||
|
||||
/// Asks the server to connect to a new peer.
|
||||
pub fn connect_peer(
|
||||
&self,
|
||||
addr: SocketAddr,
|
||||
h: reactor::Handle,
|
||||
) -> Box<Future<Item = Option<Arc<Peer>>, Error = Error>> {
|
||||
pub fn connect_peer(&self,
|
||||
addr: SocketAddr,
|
||||
h: reactor::Handle)
|
||||
-> Box<Future<Item = Option<Arc<Peer>>, Error = Error>> {
|
||||
if let Some(p) = self.get_peer(addr) {
|
||||
// if we're already connected to the addr, just return the peer
|
||||
return Box::new(future::ok(Some(p)));
|
||||
@@ -164,7 +164,7 @@ impl Server {
|
||||
let capab = self.capabilities.clone();
|
||||
let self_addr = SocketAddr::new(self.config.host, self.config.port);
|
||||
|
||||
debug!("{} connecting to {}", self_addr, addr);
|
||||
debug!(LOGGER, "{} connecting to {}", self_addr, addr);
|
||||
|
||||
let socket = TcpStream::connect(&addr, &h).map_err(|e| Error::Connection(e));
|
||||
let h2 = h.clone();
|
||||
@@ -182,7 +182,7 @@ impl Server {
|
||||
})
|
||||
.and_then(move |(socket, peer)| {
|
||||
h2.spawn(peer.run(socket, adapter2).map_err(|e| {
|
||||
error!("Peer error: {:?}", e);
|
||||
error!(LOGGER, "Peer error: {:?}", e);
|
||||
()
|
||||
}));
|
||||
Ok(Some(peer))
|
||||
@@ -264,7 +264,7 @@ impl Server {
|
||||
for p in peers.deref() {
|
||||
if p.is_connected() {
|
||||
if let Err(e) = p.send_block(b) {
|
||||
debug!("Error sending block to peer: {:?}", e);
|
||||
debug!(LOGGER, "Error sending block to peer: {:?}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -286,13 +286,11 @@ impl Server {
|
||||
}
|
||||
|
||||
// Adds the peer built by the provided future in the peers map
|
||||
fn add_to_peers<A>(
|
||||
peers: Arc<RwLock<Vec<Arc<Peer>>>>,
|
||||
adapter: Arc<NetAdapter>,
|
||||
peer_fut: A,
|
||||
) -> Box<Future<Item = Result<(TcpStream, Arc<Peer>), ()>, Error = Error>>
|
||||
where
|
||||
A: IntoFuture<Item = (TcpStream, Peer), Error = Error> + 'static,
|
||||
fn add_to_peers<A>(peers: Arc<RwLock<Vec<Arc<Peer>>>>,
|
||||
adapter: Arc<NetAdapter>,
|
||||
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)| {
|
||||
adapter.peer_connected(&peer.info);
|
||||
@@ -305,17 +303,15 @@ where
|
||||
}
|
||||
|
||||
// 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>> {
|
||||
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();
|
||||
let timed = fut.select(timeout.map(Err).from_err()).then(
|
||||
|res| match res {
|
||||
let timed = fut.select(timeout.map(Err).from_err())
|
||||
.then(|res| match res {
|
||||
Ok((Ok(inner), _timeout)) => Ok(inner),
|
||||
Ok((_, _accept)) => Err(Error::Timeout),
|
||||
Err((e, _other)) => Err(e),
|
||||
},
|
||||
);
|
||||
});
|
||||
Box::new(timed)
|
||||
}
|
||||
|
||||
+10
-14
@@ -67,10 +67,10 @@ impl Readable for PeerData {
|
||||
fn read(reader: &mut Reader) -> Result<PeerData, ser::Error> {
|
||||
let addr = SockAddr::read(reader)?;
|
||||
let (capab, ua, fl) = ser_multiread!(reader, read_u32, read_vec, read_u8);
|
||||
let user_agent = String::from_utf8(ua).map_err(|_| ser::Error::CorruptedData)?;
|
||||
let capabilities = Capabilities::from_bits(capab).ok_or(
|
||||
ser::Error::CorruptedData,
|
||||
)?;
|
||||
let user_agent = String::from_utf8(ua)
|
||||
.map_err(|_| ser::Error::CorruptedData)?;
|
||||
let capabilities = Capabilities::from_bits(capab)
|
||||
.ok_or(ser::Error::CorruptedData)?;
|
||||
match State::from_u8(fl) {
|
||||
Some(flags) => {
|
||||
Ok(PeerData {
|
||||
@@ -109,22 +109,18 @@ impl PeerStore {
|
||||
}
|
||||
|
||||
pub fn exists_peer(&self, peer_addr: SocketAddr) -> Result<bool, Error> {
|
||||
self.db.exists(
|
||||
&to_key(PEER_PREFIX, &mut format!("{}", peer_addr).into_bytes())[..],
|
||||
)
|
||||
self.db
|
||||
.exists(&to_key(PEER_PREFIX, &mut format!("{}", peer_addr).into_bytes())[..])
|
||||
}
|
||||
|
||||
pub fn delete_peer(&self, peer_addr: SocketAddr) -> Result<(), Error> {
|
||||
self.db.delete(
|
||||
&to_key(PEER_PREFIX, &mut format!("{}", peer_addr).into_bytes())[..],
|
||||
)
|
||||
self.db
|
||||
.delete(&to_key(PEER_PREFIX, &mut format!("{}", peer_addr).into_bytes())[..])
|
||||
}
|
||||
|
||||
pub fn find_peers(&self, state: State, cap: Capabilities, count: usize) -> Vec<PeerData> {
|
||||
let peers_iter = self.db.iter::<PeerData>(&to_key(
|
||||
PEER_PREFIX,
|
||||
&mut "".to_string().into_bytes(),
|
||||
));
|
||||
let peers_iter = self.db
|
||||
.iter::<PeerData>(&to_key(PEER_PREFIX, &mut "".to_string().into_bytes()));
|
||||
let mut peers = Vec::with_capacity(count);
|
||||
for p in peers_iter {
|
||||
if p.flags == state && p.capabilities.contains(cap) {
|
||||
|
||||
+1
-1
@@ -118,7 +118,7 @@ pub trait Protocol {
|
||||
/// block so needs to be called withing a coroutine. Should also be called
|
||||
/// only once.
|
||||
fn handle(&self, conn: TcpStream, na: Arc<NetAdapter>)
|
||||
-> Box<Future<Item = (), Error = Error>>;
|
||||
-> Box<Future<Item = (), Error = Error>>;
|
||||
|
||||
/// Sends a ping message to the remote peer.
|
||||
fn send_ping(&self) -> Result<(), Error>;
|
||||
|
||||
Reference in New Issue
Block a user