[1.1.0] Merge master into 1.1.0 (#2720)
* cleanup legacy "3 dot" check (#2625)
* Allow to peers behind NAT to get up to preferred_max connections (#2543)
Allow to peers behind NAT to get up to preffered_max connections
If peer has only outbound connections it's mot likely behind NAT and we should not stop it from getting more outbound connections
* Reduce usage of unwrap in p2p crate (#2627)
Also change store crate a bit
* Simplify (and fix) output_pos cleanup during chain compaction (#2609)
* expose leaf pos iterator
use it for various things in txhashset when iterating over outputs
* fix
* cleanup
* rebuild output_pos index (and clear it out first) when compacting the chain
* fixup tests
* refactor to match on (output, proof) tuple
* add comments to compact() to explain what is going on.
* get rid of some boxing around the leaf_set iterator
* cleanup
* [docs] Add switch commitment documentation (#2526)
* remove references to no-longer existing switch commitment hash
(as switch commitments were removed in ca8447f3bd
and moved into the blinding factor of the Pedersen Commitment)
* some rewording (points vs curves) and fix of small formatting issues
* Add switch commitment documentation
* [docs] Documents in grin repo had translated in Korean. (#2604)
* Start to M/W intro translate in Korean
* translate in Korean
* add korean translation on intro
* table_of_content.md translate in Korean.
* table_of_content_KR.md finish translate in Korean, start to translate State_KR.md
* add state_KR.md & commit some translation in State_KR.md
* WIP stat_KR.md translation
* add build_KR.md && stratum_KR.md
* finish translate stratum_KR.md & table_of_content_KR.md
* rename intro.KR.md to intro_KR.md
* add intro_KR.md file path each language's intro.md
* add Korean translation file path to stratum.md & table_of_contents.md
* fix difference with grin/master
* Fix TxHashSet file filter for Windows. (#2641)
* Fix TxHashSet file filter for Windows.
* rustfmt
* Updating regexp
* Adding in test case
* Display the current download rate rather than the average when syncing the chain (#2633)
* When syncing the chain, calculate the displayed download speed using the current rate from the most recent iteration, rather than the average download speed from the entire syncing process.
* Replace the explicitly ignored variables in the pattern with an implicit ignore
* remove root = true from editorconfig (#2655)
* Add Medium post to intro (#2654)
Spoke to @yeastplume who agreed it makes sense to add the "Grin Transactions Explained, Step-by-Step" Medium post to intro.md
Open for suggestions on a better location.
* add a new configure item for log_max_files (#2601)
* add a new configure item for log_max_files
* rustfmt
* use a constant instead of multiple 32
* rustfmt
* Fix the build warning of deprecated trim_right_matches (#2662)
* [DOC] state.md, build.md and chain directory documents translate in Korean. (#2649)
* add md files for translation.
* start to translation fast-sync, code_structure. add file build_KR.md, states_KR.md
* add dandelion_KR.md && simulation_KR.md for Korean translation.
* add md files for translation.
* start to translation fast-sync, code_structure. add file build_KR.md, states_KR.md
* add dandelion_KR.md && simulation_KR.md for Korean translation.
* remove some useless md files for translation. this is rearrange set up translation order.
* add dot end of sentence & translate build.md in korean
* remove fast-sync_KR.md
* finish build_KR.md translation
* finish build_KR.md translation
* finish translation state_KR.md & add phrase in state.md to move other language md file
* translate blocks_and_headers.md && chain_sync.md in Korean
* add . in chain_sync.md , translation finished in doc/chain dir.
* fix some miss typos
* Api documentation fixes (#2646)
* Fix the API documentation for Chain Validate (v1/chain/validate). It was documented as a POST, but it is actually a GET request, which can be seen in its handler ChainValidationHandler
* Update the API V1 route list response to include the headers and merkleproof routes. Also clarify that for the chain/outputs route you must specify either byids or byheight to select outputs.
* refactor(ci): reorganize CI related code (#2658)
Break-down the CI related code into smaller more maintainable pieces.
* Specify grin or nanogrins in API docs where applicable (#2642)
* Set Content-Type in API client (#2680)
* Reduce number of unwraps in chain crate (#2679)
* fix: the restart of state sync doesn't work sometimes (#2687)
* let check_txhashset_needed return true on abnormal case (#2684)
* Reduce number of unwwaps in api crate (#2681)
* Reduce number of unwwaps in api crate
* Format use section
* Small QoL improvements for wallet developers (#2651)
* Small changes for wallet devs
* Move create_nonce into Keychain trait
* Replace match by map_err
* Add flag to Slate to skip fee check
* Fix secp dependency
* Remove check_fee flag in Slate
* Add Japanese edition of build.md (#2697)
* catch the panic to avoid peer thread quit early (#2686)
* catch the panic to avoid peer thread quit before taking the chance to ban
* move catch wrapper logic down into the util crate
* log the panic info
* keep txhashset.rs untouched
* remove a warning
* [DOC] dandelion.md, simulation.md ,fast-sync.md and pruning.md documents translate in Korean. (#2678)
* Show response code in API client error message (#2683)
It's hard to investigate what happens when an API client error is
printed out
* Add some better logging for get_outputs_by_id failure states (#2705)
* Switch commitment doc fixes (#2645)
Fix some typos and remove the use of parentheses in a
couple of places to make the reading flow a bit better.
* docs: update/add new README.md badges (#2708)
Replace existing badges with SVG counterparts and add a bunch of new ones.
* Update intro.md (#2702)
Add mention of censoring attack prevented by range proofs
* use sandbox folder for txhashset validation on state sync (#2685)
* use sandbox folder for txhashset validation on state sync
* rustfmt
* use temp directory as the sandbox instead actual db_root txhashset dir
* rustfmt
* move txhashset overwrite to the end of full validation
* fix travis-ci test
* rustfmt
* fix: hashset have 2 folders including txhashset and header
* rustfmt
*
(1)switch to rebuild_header_mmr instead of copy the sandbox header mmr
(2)lock txhashset when overwriting and opening and rebuild
* minor improve on sandbox_dir
* add Japanese edition of state.md (#2703)
* Attempt to fix broken TUI locale (#2713)
Can confirm that on the same machine 1.0.2 TUI looks great and is broken on
the current master. Bump of `cursive` version fixed it for me.
Fixes #2676
* clean the header folder in sandbox (#2716)
* forgot to clean the header folder in sandbox in #2685
* Reduce number of unwraps in servers crate (#2707)
It doesn't include stratum server which is sufficiently changed in 1.1
branch and adapters, which is big enough for a separate PR.
* rustfmt
* change version to beta
This commit is contained in:
+6
-7
@@ -113,19 +113,18 @@ impl<'a> Response<'a> {
|
||||
resp_type: Type,
|
||||
body: T,
|
||||
stream: &'a mut dyn Write,
|
||||
) -> Response<'a> {
|
||||
let body = ser::ser_vec(&body).unwrap();
|
||||
Response {
|
||||
) -> Result<Response<'a>, Error> {
|
||||
let body = ser::ser_vec(&body)?;
|
||||
Ok(Response {
|
||||
resp_type,
|
||||
body,
|
||||
stream,
|
||||
attachment: None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn write(mut self, sent_bytes: Arc<RwLock<RateCounter>>) -> Result<(), Error> {
|
||||
let mut msg =
|
||||
ser::ser_vec(&MsgHeader::new(self.resp_type, self.body.len() as u64)).unwrap();
|
||||
let mut msg = ser::ser_vec(&MsgHeader::new(self.resp_type, self.body.len() as u64))?;
|
||||
msg.append(&mut self.body);
|
||||
write_all(&mut self.stream, &msg[..], time::Duration::from_secs(10))?;
|
||||
// Increase sent bytes counter
|
||||
@@ -177,7 +176,7 @@ impl Tracker {
|
||||
where
|
||||
T: ser::Writeable,
|
||||
{
|
||||
let buf = write_to_buf(body, msg_type);
|
||||
let buf = write_to_buf(body, msg_type)?;
|
||||
let buf_len = buf.len();
|
||||
self.send_channel.try_send(buf)?;
|
||||
|
||||
|
||||
+19
-19
@@ -160,18 +160,18 @@ pub fn read_message<T: Readable>(stream: &mut dyn Read, msg_type: Type) -> Resul
|
||||
read_body(&header, stream)
|
||||
}
|
||||
|
||||
pub fn write_to_buf<T: Writeable>(msg: T, msg_type: Type) -> Vec<u8> {
|
||||
pub fn write_to_buf<T: Writeable>(msg: T, msg_type: Type) -> Result<Vec<u8>, Error> {
|
||||
// prepare the body first so we know its serialized length
|
||||
let mut body_buf = vec![];
|
||||
ser::serialize(&mut body_buf, &msg).unwrap();
|
||||
ser::serialize(&mut body_buf, &msg)?;
|
||||
|
||||
// build and serialize the header using the body size
|
||||
let mut msg_buf = vec![];
|
||||
let blen = body_buf.len() as u64;
|
||||
ser::serialize(&mut msg_buf, &MsgHeader::new(msg_type, blen)).unwrap();
|
||||
ser::serialize(&mut msg_buf, &MsgHeader::new(msg_type, blen))?;
|
||||
msg_buf.append(&mut body_buf);
|
||||
|
||||
msg_buf
|
||||
Ok(msg_buf)
|
||||
}
|
||||
|
||||
pub fn write_message<T: Writeable>(
|
||||
@@ -179,7 +179,7 @@ pub fn write_message<T: Writeable>(
|
||||
msg: T,
|
||||
msg_type: Type,
|
||||
) -> Result<(), Error> {
|
||||
let buf = write_to_buf(msg, msg_type);
|
||||
let buf = write_to_buf(msg, msg_type)?;
|
||||
stream.write_all(&buf[..])?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -268,11 +268,11 @@ impl Writeable for Hand {
|
||||
[write_u32, self.capabilities.bits()],
|
||||
[write_u64, self.nonce]
|
||||
);
|
||||
self.total_difficulty.write(writer).unwrap();
|
||||
self.sender_addr.write(writer).unwrap();
|
||||
self.receiver_addr.write(writer).unwrap();
|
||||
writer.write_bytes(&self.user_agent).unwrap();
|
||||
self.genesis.write(writer).unwrap();
|
||||
self.total_difficulty.write(writer)?;
|
||||
self.sender_addr.write(writer)?;
|
||||
self.receiver_addr.write(writer)?;
|
||||
writer.write_bytes(&self.user_agent)?;
|
||||
self.genesis.write(writer)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -323,9 +323,9 @@ impl Writeable for Shake {
|
||||
[write_u32, self.version],
|
||||
[write_u32, self.capabilities.bits()]
|
||||
);
|
||||
self.total_difficulty.write(writer).unwrap();
|
||||
writer.write_bytes(&self.user_agent).unwrap();
|
||||
self.genesis.write(writer).unwrap();
|
||||
self.total_difficulty.write(writer)?;
|
||||
writer.write_bytes(&self.user_agent)?;
|
||||
self.genesis.write(writer)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -379,7 +379,7 @@ impl Writeable for PeerAddrs {
|
||||
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
|
||||
writer.write_u32(self.peers.len() as u32)?;
|
||||
for p in &self.peers {
|
||||
p.write(writer).unwrap();
|
||||
p.write(writer)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -484,8 +484,8 @@ pub struct Ping {
|
||||
|
||||
impl Writeable for Ping {
|
||||
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
|
||||
self.total_difficulty.write(writer).unwrap();
|
||||
self.height.write(writer).unwrap();
|
||||
self.total_difficulty.write(writer)?;
|
||||
self.height.write(writer)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -511,8 +511,8 @@ pub struct Pong {
|
||||
|
||||
impl Writeable for Pong {
|
||||
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
|
||||
self.total_difficulty.write(writer).unwrap();
|
||||
self.height.write(writer).unwrap();
|
||||
self.total_difficulty.write(writer)?;
|
||||
self.height.write(writer)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -537,7 +537,7 @@ pub struct BanReason {
|
||||
impl Writeable for BanReason {
|
||||
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
|
||||
let ban_reason_i32 = self.ban_reason as i32;
|
||||
ban_reason_i32.write(writer).unwrap();
|
||||
ban_reason_i32.write(writer)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
+32
-73
@@ -55,6 +55,15 @@ pub struct Peer {
|
||||
connection: Option<Mutex<conn::Tracker>>,
|
||||
}
|
||||
|
||||
macro_rules! connection {
|
||||
($holder:expr) => {
|
||||
match $holder.connection.as_ref() {
|
||||
Some(conn) => conn.lock(),
|
||||
None => return Err(Error::Internal),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl fmt::Debug for Peer {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Peer({:?})", &self.info)
|
||||
@@ -240,29 +249,15 @@ impl Peer {
|
||||
total_difficulty,
|
||||
height,
|
||||
};
|
||||
self.connection
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.send(ping_msg, msg::Type::Ping)
|
||||
connection!(self).send(ping_msg, msg::Type::Ping)
|
||||
}
|
||||
|
||||
/// Send the ban reason before banning
|
||||
pub fn send_ban_reason(&self, ban_reason: ReasonForBan) {
|
||||
pub fn send_ban_reason(&self, ban_reason: ReasonForBan) -> Result<(), Error> {
|
||||
let ban_reason_msg = BanReason { ban_reason };
|
||||
match self
|
||||
.connection
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.lock()
|
||||
connection!(self)
|
||||
.send(ban_reason_msg, msg::Type::BanReason)
|
||||
{
|
||||
Ok(_) => debug!("Sent ban reason {:?} to {}", ban_reason, self.info.addr),
|
||||
Err(e) => error!(
|
||||
"Could not send ban reason {:?} to {}: {:?}",
|
||||
ban_reason, self.info.addr, e
|
||||
),
|
||||
};
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// Sends the provided block to the remote peer. The request may be dropped
|
||||
@@ -270,11 +265,7 @@ impl Peer {
|
||||
pub fn send_block(&self, b: &core::Block) -> Result<bool, Error> {
|
||||
if !self.tracking_adapter.has_recv(b.hash()) {
|
||||
trace!("Send block {} to {}", b.hash(), self.info.addr);
|
||||
self.connection
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.send(b, msg::Type::Block)?;
|
||||
connection!(self).send(b, msg::Type::Block)?;
|
||||
Ok(true)
|
||||
} else {
|
||||
debug!(
|
||||
@@ -289,11 +280,7 @@ impl Peer {
|
||||
pub fn send_compact_block(&self, b: &core::CompactBlock) -> Result<bool, Error> {
|
||||
if !self.tracking_adapter.has_recv(b.hash()) {
|
||||
trace!("Send compact block {} to {}", b.hash(), self.info.addr);
|
||||
self.connection
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.send(b, msg::Type::CompactBlock)?;
|
||||
connection!(self).send(b, msg::Type::CompactBlock)?;
|
||||
Ok(true)
|
||||
} else {
|
||||
debug!(
|
||||
@@ -308,11 +295,7 @@ impl Peer {
|
||||
pub fn send_header(&self, bh: &core::BlockHeader) -> Result<bool, Error> {
|
||||
if !self.tracking_adapter.has_recv(bh.hash()) {
|
||||
debug!("Send header {} to {}", bh.hash(), self.info.addr);
|
||||
self.connection
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.send(bh, msg::Type::Header)?;
|
||||
connection!(self).send(bh, msg::Type::Header)?;
|
||||
Ok(true)
|
||||
} else {
|
||||
debug!(
|
||||
@@ -327,11 +310,7 @@ impl Peer {
|
||||
pub fn send_tx_kernel_hash(&self, h: Hash) -> Result<bool, Error> {
|
||||
if !self.tracking_adapter.has_recv(h) {
|
||||
debug!("Send tx kernel hash {} to {}", h, self.info.addr);
|
||||
self.connection
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.send(h, msg::Type::TransactionKernel)?;
|
||||
connection!(self).send(h, msg::Type::TransactionKernel)?;
|
||||
Ok(true)
|
||||
} else {
|
||||
debug!(
|
||||
@@ -359,11 +338,7 @@ impl Peer {
|
||||
|
||||
if !self.tracking_adapter.has_recv(kernel.hash()) {
|
||||
debug!("Send full tx {} to {}", tx.hash(), self.info.addr);
|
||||
self.connection
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.send(tx, msg::Type::Transaction)?;
|
||||
connection!(self).send(tx, msg::Type::Transaction)?;
|
||||
Ok(true)
|
||||
} else {
|
||||
debug!(
|
||||
@@ -380,21 +355,12 @@ impl Peer {
|
||||
/// embargo).
|
||||
pub fn send_stem_transaction(&self, tx: &core::Transaction) -> Result<(), Error> {
|
||||
debug!("Send (stem) tx {} to {}", tx.hash(), self.info.addr);
|
||||
self.connection
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.send(tx, msg::Type::StemTransaction)?;
|
||||
Ok(())
|
||||
connection!(self).send(tx, msg::Type::StemTransaction)
|
||||
}
|
||||
|
||||
/// Sends a request for block headers from the provided block locator
|
||||
pub fn send_header_request(&self, locator: Vec<Hash>) -> Result<(), Error> {
|
||||
self.connection
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.send(&Locator { hashes: locator }, msg::Type::GetHeaders)
|
||||
connection!(self).send(&Locator { hashes: locator }, msg::Type::GetHeaders)
|
||||
}
|
||||
|
||||
pub fn send_tx_request(&self, h: Hash) -> Result<(), Error> {
|
||||
@@ -402,37 +368,25 @@ impl Peer {
|
||||
"Requesting tx (kernel hash) {} from peer {}.",
|
||||
h, self.info.addr
|
||||
);
|
||||
self.connection
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.send(&h, msg::Type::GetTransaction)
|
||||
connection!(self).send(&h, msg::Type::GetTransaction)
|
||||
}
|
||||
|
||||
/// Sends a request for a specific block by hash
|
||||
pub fn send_block_request(&self, h: Hash) -> Result<(), Error> {
|
||||
debug!("Requesting block {} from peer {}.", h, self.info.addr);
|
||||
self.tracking_adapter.push_req(h);
|
||||
self.connection
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.send(&h, msg::Type::GetBlock)
|
||||
connection!(self).send(&h, msg::Type::GetBlock)
|
||||
}
|
||||
|
||||
/// Sends a request for a specific compact block by hash
|
||||
pub fn send_compact_block_request(&self, h: Hash) -> Result<(), Error> {
|
||||
debug!("Requesting compact block {} from {}", h, self.info.addr);
|
||||
self.connection
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.send(&h, msg::Type::GetCompactBlock)
|
||||
connection!(self).send(&h, msg::Type::GetCompactBlock)
|
||||
}
|
||||
|
||||
pub fn send_peer_request(&self, capab: Capabilities) -> Result<(), Error> {
|
||||
trace!("Asking {} for more peers {:?}", self.info.addr, capab);
|
||||
self.connection.as_ref().unwrap().lock().send(
|
||||
connection!(self).send(
|
||||
&GetPeerAddrs {
|
||||
capabilities: capab,
|
||||
},
|
||||
@@ -445,7 +399,7 @@ impl Peer {
|
||||
"Asking {} for txhashset archive at {} {}.",
|
||||
self.info.addr, height, hash
|
||||
);
|
||||
self.connection.as_ref().unwrap().lock().send(
|
||||
connection!(self).send(
|
||||
&TxHashSetRequest { hash, height },
|
||||
msg::Type::TxHashSetRequest,
|
||||
)
|
||||
@@ -453,11 +407,16 @@ impl Peer {
|
||||
|
||||
/// Stops the peer, closing its connection
|
||||
pub fn stop(&self) {
|
||||
stop_with_connection(&self.connection.as_ref().unwrap().lock());
|
||||
if let Some(conn) = self.connection.as_ref() {
|
||||
stop_with_connection(&conn.lock());
|
||||
}
|
||||
}
|
||||
|
||||
fn check_connection(&self) -> bool {
|
||||
let connection = self.connection.as_ref().unwrap().lock();
|
||||
let connection = match self.connection.as_ref() {
|
||||
Some(conn) => conn.lock(),
|
||||
None => return false,
|
||||
};
|
||||
match connection.error_channel.try_recv() {
|
||||
Ok(Error::Serialization(e)) => {
|
||||
let need_stop = {
|
||||
|
||||
+28
-13
@@ -182,11 +182,10 @@ impl Peers {
|
||||
return vec![];
|
||||
}
|
||||
|
||||
let max_total_difficulty = peers
|
||||
.iter()
|
||||
.map(|x| x.info.total_difficulty())
|
||||
.max()
|
||||
.unwrap();
|
||||
let max_total_difficulty = match peers.iter().map(|x| x.info.total_difficulty()).max() {
|
||||
Some(v) => v,
|
||||
None => return vec![],
|
||||
};
|
||||
|
||||
let mut max_peers = peers
|
||||
.into_iter()
|
||||
@@ -221,7 +220,10 @@ impl Peers {
|
||||
if let Some(peer) = self.get_connected_peer(peer_addr) {
|
||||
debug!("Banning peer {}", peer_addr);
|
||||
// setting peer status will get it removed at the next clean_peer
|
||||
peer.send_ban_reason(ban_reason);
|
||||
match peer.send_ban_reason(ban_reason) {
|
||||
Err(e) => error!("failed to send a ban reason to{}: {:?}", peer_addr, e),
|
||||
Ok(_) => debug!("ban reason {:?} was sent to {}", ban_reason, peer_addr),
|
||||
};
|
||||
peer.set_banned();
|
||||
peer.stop();
|
||||
}
|
||||
@@ -328,12 +330,24 @@ impl Peers {
|
||||
|
||||
/// All peer information we have in storage
|
||||
pub fn all_peers(&self) -> Vec<PeerData> {
|
||||
self.store.all_peers()
|
||||
match self.store.all_peers() {
|
||||
Ok(peers) => peers,
|
||||
Err(e) => {
|
||||
error!("all_peers failed: {:?}", e);
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Find peers in store (not necessarily connected) and return their data
|
||||
pub fn find_peers(&self, state: State, cap: Capabilities, count: usize) -> Vec<PeerData> {
|
||||
self.store.find_peers(state, cap, count)
|
||||
match self.store.find_peers(state, cap, count) {
|
||||
Ok(peers) => peers,
|
||||
Err(e) => {
|
||||
error!("failed to find peers: {:?}", e);
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get peer in store by address
|
||||
@@ -373,11 +387,12 @@ impl Peers {
|
||||
debug!("clean_peers {:?}, not connected", peer.info.addr);
|
||||
rm.push(peer.info.addr.clone());
|
||||
} else if peer.is_abusive() {
|
||||
let counts = peer.last_min_message_counts().unwrap();
|
||||
debug!(
|
||||
"clean_peers {:?}, abusive ({} sent, {} recv)",
|
||||
peer.info.addr, counts.0, counts.1,
|
||||
);
|
||||
if let Some(counts) = peer.last_min_message_counts() {
|
||||
debug!(
|
||||
"clean_peers {:?}, abusive ({} sent, {} recv)",
|
||||
peer.info.addr, counts.0, counts.1,
|
||||
);
|
||||
}
|
||||
let _ = self.update_state(peer.info.addr, State::Banned);
|
||||
rm.push(peer.info.addr.clone());
|
||||
} else {
|
||||
|
||||
+11
-8
@@ -72,7 +72,7 @@ impl MessageHandler for Protocol {
|
||||
height: adapter.total_height(),
|
||||
},
|
||||
writer,
|
||||
)))
|
||||
)?))
|
||||
}
|
||||
|
||||
Type::Pong => {
|
||||
@@ -105,7 +105,7 @@ impl MessageHandler for Protocol {
|
||||
);
|
||||
let tx = adapter.get_transaction(h);
|
||||
if let Some(tx) = tx {
|
||||
Ok(Some(Response::new(Type::Transaction, tx, writer)))
|
||||
Ok(Some(Response::new(Type::Transaction, tx, writer)?))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
@@ -141,7 +141,7 @@ impl MessageHandler for Protocol {
|
||||
|
||||
let bo = adapter.get_block(h);
|
||||
if let Some(b) = bo {
|
||||
return Ok(Some(Response::new(Type::Block, b, writer)));
|
||||
return Ok(Some(Response::new(Type::Block, b, writer)?));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
@@ -163,7 +163,7 @@ impl MessageHandler for Protocol {
|
||||
let h: Hash = msg.body()?;
|
||||
if let Some(b) = adapter.get_block(h) {
|
||||
let cb: CompactBlock = b.into();
|
||||
Ok(Some(Response::new(Type::CompactBlock, cb, writer)))
|
||||
Ok(Some(Response::new(Type::CompactBlock, cb, writer)?))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
@@ -190,7 +190,7 @@ impl MessageHandler for Protocol {
|
||||
Type::Headers,
|
||||
Headers { headers },
|
||||
writer,
|
||||
)))
|
||||
)?))
|
||||
}
|
||||
|
||||
// "header first" block propagation - if we have not yet seen this block
|
||||
@@ -235,7 +235,7 @@ impl MessageHandler for Protocol {
|
||||
Type::PeerAddrs,
|
||||
PeerAddrs { peers },
|
||||
writer,
|
||||
)))
|
||||
)?))
|
||||
}
|
||||
|
||||
Type::PeerAddrs => {
|
||||
@@ -263,7 +263,7 @@ impl MessageHandler for Protocol {
|
||||
bytes: file_sz,
|
||||
},
|
||||
writer,
|
||||
);
|
||||
)?;
|
||||
resp.add_attachment(txhashset.reader);
|
||||
Ok(Some(resp))
|
||||
} else {
|
||||
@@ -312,7 +312,10 @@ impl MessageHandler for Protocol {
|
||||
received_bytes.inc_quiet(size as u64);
|
||||
}
|
||||
}
|
||||
tmp_zip.into_inner().unwrap().sync_all()?;
|
||||
tmp_zip
|
||||
.into_inner()
|
||||
.map_err(|_| Error::Internal)?
|
||||
.sync_all()?;
|
||||
Ok(())
|
||||
};
|
||||
|
||||
|
||||
+19
-11
@@ -83,10 +83,9 @@ impl Readable for PeerData {
|
||||
let lc = reader.read_i64();
|
||||
// this only works because each PeerData is read in its own vector and this
|
||||
// is the last data element
|
||||
let last_connected = if let Err(_) = lc {
|
||||
Utc::now().timestamp()
|
||||
} else {
|
||||
lc.unwrap()
|
||||
let last_connected = match lc {
|
||||
Err(_) => Utc::now().timestamp(),
|
||||
Ok(lc) => lc,
|
||||
};
|
||||
|
||||
let user_agent = String::from_utf8(ua).map_err(|_| ser::Error::CorruptedData)?;
|
||||
@@ -147,22 +146,31 @@ impl PeerStore {
|
||||
batch.commit()
|
||||
}
|
||||
|
||||
pub fn find_peers(&self, state: State, cap: Capabilities, count: usize) -> Vec<PeerData> {
|
||||
pub fn find_peers(
|
||||
&self,
|
||||
state: State,
|
||||
cap: Capabilities,
|
||||
count: usize,
|
||||
) -> Result<Vec<PeerData>, Error> {
|
||||
let mut peers = self
|
||||
.db
|
||||
.iter::<PeerData>(&to_key(PEER_PREFIX, &mut "".to_string().into_bytes()))
|
||||
.unwrap()
|
||||
.iter::<PeerData>(&to_key(PEER_PREFIX, &mut "".to_string().into_bytes()))?
|
||||
.map(|(_, v)| v)
|
||||
.filter(|p| p.flags == state && p.capabilities.contains(cap))
|
||||
.collect::<Vec<_>>();
|
||||
thread_rng().shuffle(&mut peers[..]);
|
||||
peers.iter().take(count).cloned().collect()
|
||||
Ok(peers.iter().take(count).cloned().collect())
|
||||
}
|
||||
|
||||
/// List all known peers
|
||||
/// Used for /v1/peers/all api endpoint
|
||||
pub fn all_peers(&self) -> Vec<PeerData> {
|
||||
pub fn all_peers(&self) -> Result<Vec<PeerData>, Error> {
|
||||
let key = to_key(PEER_PREFIX, &mut "".to_string().into_bytes());
|
||||
self.db.iter::<PeerData>(&key).unwrap().collect::<Vec<_>>()
|
||||
Ok(self
|
||||
.db
|
||||
.iter::<PeerData>(&key)?
|
||||
.map(|(_, v)| v)
|
||||
.collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// Convenience method to load a peer data, update its status and save it
|
||||
@@ -190,7 +198,7 @@ impl PeerStore {
|
||||
{
|
||||
let mut to_remove = vec![];
|
||||
|
||||
for x in self.all_peers() {
|
||||
for x in self.all_peers()? {
|
||||
if predicate(&x) {
|
||||
to_remove.push(x)
|
||||
}
|
||||
|
||||
@@ -75,6 +75,7 @@ pub enum Error {
|
||||
},
|
||||
Send(String),
|
||||
PeerException,
|
||||
Internal,
|
||||
}
|
||||
|
||||
impl From<ser::Error> for Error {
|
||||
|
||||
Reference in New Issue
Block a user