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.
|
|
|
|
|
2016-10-29 22:36:45 +03:00
|
|
|
use mioco::tcp::TcpStream;
|
2016-10-25 07:35:10 +03:00
|
|
|
|
2016-11-01 20:42:33 +03:00
|
|
|
use core::core;
|
2016-10-26 21:21:45 +03:00
|
|
|
use core::ser::Error;
|
2016-10-29 22:36:45 +03:00
|
|
|
use handshake::Handshake;
|
2016-10-26 08:06:13 +03:00
|
|
|
use types::*;
|
2016-10-25 07:35:10 +03:00
|
|
|
|
2016-10-29 22:36:45 +03:00
|
|
|
pub struct Peer {
|
2016-10-31 04:23:52 +03:00
|
|
|
info: PeerInfo,
|
|
|
|
proto: Box<Protocol>,
|
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 {
|
|
|
|
pub fn connect(conn: TcpStream, hs: &Handshake) -> Result<Peer, Error> {
|
|
|
|
let (proto, info) = try!(hs.connect(conn));
|
2016-10-31 04:23:52 +03:00
|
|
|
Ok(Peer {
|
|
|
|
info: info,
|
|
|
|
proto: proto,
|
|
|
|
})
|
|
|
|
}
|
2016-10-29 22:36:45 +03:00
|
|
|
|
|
|
|
pub fn accept(conn: TcpStream, hs: &Handshake) -> Result<Peer, Error> {
|
|
|
|
let (proto, info) = try!(hs.handshake(conn));
|
2016-10-31 04:23:52 +03:00
|
|
|
Ok(Peer {
|
|
|
|
info: info,
|
|
|
|
proto: proto,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2016-11-01 20:42:33 +03:00
|
|
|
pub fn run(&self, na: &NetAdapter) -> Result<(), Error> {
|
2016-10-31 04:23:52 +03:00
|
|
|
self.proto.handle(na)
|
|
|
|
}
|
|
|
|
|
2016-11-01 20:42:33 +03:00
|
|
|
pub fn send_ping(&self) -> Result<(), Error> {
|
2016-10-31 04:23:52 +03:00
|
|
|
self.proto.send_ping()
|
|
|
|
}
|
|
|
|
|
2016-11-01 20:42:33 +03:00
|
|
|
pub fn send_block(&self, b: &core::Block) -> Result<(), Error> {
|
|
|
|
// TODO don't send if we already got the block from peer
|
|
|
|
self.proto.send_block(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn send_transaction(&self, tx: &core::Transaction) -> Result<(), Error> {
|
|
|
|
// TODO don't relay if we already got the tx from peer
|
|
|
|
self.proto.send_transaction(tx)
|
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
pub fn stop(&self) {
|
|
|
|
self.proto.as_ref().close()
|
|
|
|
}
|
2016-10-25 07:35:10 +03:00
|
|
|
}
|