Light `clippy(fy)` (#9473)

* wasm tests

* `clippyfy` light-client

* Revert inefficient change `collect_ready()`
This commit is contained in:
Niklas Adolfsson 2018-09-06 15:44:40 +02:00 committed by Afri Schoedon
parent 4e8e5bbb86
commit 6888a968f9
22 changed files with 323 additions and 345 deletions

View File

@ -31,7 +31,7 @@ use ethereum_types::{H256, U256};
use memory_cache::MemoryLruCache;
/// Configuration for how much data to cache.
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct CacheSizes {
/// Maximum size, in bytes, of cached headers.
pub headers: usize,
@ -83,33 +83,33 @@ impl Cache {
receipts: MemoryLruCache::new(sizes.receipts),
chain_score: MemoryLruCache::new(sizes.chain_score),
corpus: None,
corpus_expiration: corpus_expiration,
corpus_expiration,
}
}
/// Query header by hash.
pub fn block_header(&mut self, hash: &H256) -> Option<encoded::Header> {
self.headers.get_mut(hash).map(|x| x.clone())
self.headers.get_mut(hash).cloned()
}
/// Query hash by number.
pub fn block_hash(&mut self, num: &BlockNumber) -> Option<H256> {
self.canon_hashes.get_mut(num).map(|x| x.clone())
pub fn block_hash(&mut self, num: BlockNumber) -> Option<H256> {
self.canon_hashes.get_mut(&num).map(|h| *h)
}
/// Query block body by block hash.
pub fn block_body(&mut self, hash: &H256) -> Option<encoded::Body> {
self.bodies.get_mut(hash).map(|x| x.clone())
self.bodies.get_mut(hash).cloned()
}
/// Query block receipts by block hash.
pub fn block_receipts(&mut self, hash: &H256) -> Option<Vec<Receipt>> {
self.receipts.get_mut(hash).map(|x| x.clone())
self.receipts.get_mut(hash).cloned()
}
/// Query chain score by block hash.
pub fn chain_score(&mut self, hash: &H256) -> Option<U256> {
self.chain_score.get_mut(hash).map(|x| x.clone())
self.chain_score.get_mut(hash).map(|h| *h)
}
/// Cache the given header.

View File

@ -92,7 +92,7 @@ pub struct BlockInfo {
/// Build an in-memory CHT from a closure which provides necessary information
/// about blocks. If the fetcher ever fails to provide the info, the CHT
/// will not be generated.
pub fn build<F>(cht_num: u64, mut fetcher: F) -> Option<CHT<MemoryDB<KeccakHasher>>>
pub fn build<F>(cht_num: u64, mut fetcher: F) -> Option<CHT<MemoryDB<KeccakHasher>>>
where F: FnMut(BlockId) -> Option<BlockInfo>
{
let mut db = MemoryDB::<KeccakHasher>::new();
@ -118,8 +118,8 @@ pub fn build<F>(cht_num: u64, mut fetcher: F) -> Option<CHT<MemoryDB<KeccakHash
}
Some(CHT {
db: db,
root: root,
db,
root,
number: cht_num,
})
}

View File

@ -51,10 +51,10 @@ use smallvec::SmallVec;
const HISTORY: u64 = 2048;
/// The best block key. Maps to an RLP list: [best_era, last_era]
const CURRENT_KEY: &'static [u8] = &*b"best_and_latest";
const CURRENT_KEY: &[u8] = &*b"best_and_latest";
/// Key storing the last canonical epoch transition.
const LAST_CANONICAL_TRANSITION: &'static [u8] = &*b"canonical_transition";
const LAST_CANONICAL_TRANSITION: &[u8] = &*b"canonical_transition";
/// Information about a block.
#[derive(Debug, Clone)]
@ -97,9 +97,10 @@ struct Entry {
impl HeapSizeOf for Entry {
fn heap_size_of_children(&self) -> usize {
match self.candidates.spilled() {
false => 0,
true => self.candidates.capacity() * ::std::mem::size_of::<Candidate>(),
if self.candidates.spilled() {
self.candidates.capacity() * ::std::mem::size_of::<Candidate>()
} else {
0
}
}
}
@ -134,7 +135,7 @@ impl Decodable for Entry {
// rely on the invariant that the canonical entry is always first.
let canon_hash = candidates[0].hash;
Ok(Entry {
candidates: candidates,
candidates,
canonical_hash: canon_hash,
})
}
@ -269,9 +270,9 @@ impl HeaderChain {
best_block: RwLock::new(best_block),
candidates: RwLock::new(candidates),
live_epoch_proofs: RwLock::new(live_epoch_proofs),
db: db,
col: col,
cache: cache,
db,
col,
cache,
}
} else {
@ -285,8 +286,8 @@ impl HeaderChain {
candidates: RwLock::new(BTreeMap::new()),
live_epoch_proofs: RwLock::new(live_epoch_proofs),
db: db.clone(),
col: col,
cache: cache,
col,
cache,
};
// insert the hardcoded sync into the database.
@ -302,9 +303,8 @@ impl HeaderChain {
let decoded_header_num = decoded_header.number();
// write the block in the DB.
info!(target: "chain", "Inserting hardcoded block #{} in chain",
decoded_header_num);
let pending = chain.insert_with_td(&mut batch, decoded_header,
info!(target: "chain", "Inserting hardcoded block #{} in chain", decoded_header_num);
let pending = chain.insert_with_td(&mut batch, &decoded_header,
hardcoded_sync.total_difficulty, None)?;
// check that we have enough hardcoded CHT roots. avoids panicking later.
@ -324,7 +324,7 @@ impl HeaderChain {
};
// instantiate genesis epoch data if it doesn't exist.
if let None = chain.db.get(col, LAST_CANONICAL_TRANSITION)? {
if chain.db.get(col, LAST_CANONICAL_TRANSITION)?.is_none() {
let genesis_data = spec.genesis_epoch_data()?;
{
@ -349,7 +349,7 @@ impl HeaderChain {
pub fn insert(
&self,
transaction: &mut DBTransaction,
header: Header,
header: &Header,
transition_proof: Option<Vec<u8>>,
) -> Result<PendingChanges, BlockImportError> {
self.insert_inner(transaction, header, None, transition_proof)
@ -361,7 +361,7 @@ impl HeaderChain {
pub fn insert_with_td(
&self,
transaction: &mut DBTransaction,
header: Header,
header: &Header,
total_difficulty: U256,
transition_proof: Option<Vec<u8>>,
) -> Result<PendingChanges, BlockImportError> {
@ -371,7 +371,7 @@ impl HeaderChain {
fn insert_inner(
&self,
transaction: &mut DBTransaction,
header: Header,
header: &Header,
total_difficulty: Option<U256>,
transition_proof: Option<Vec<u8>>,
) -> Result<PendingChanges, BlockImportError> {
@ -381,7 +381,7 @@ impl HeaderChain {
let transition = transition_proof.map(|proof| EpochTransition {
block_hash: hash,
block_number: number,
proof: proof,
proof,
});
let mut pending = PendingChanges {
@ -415,9 +415,9 @@ impl HeaderChain {
let cur_era = candidates.entry(number)
.or_insert_with(|| Entry { candidates: SmallVec::new(), canonical_hash: hash });
cur_era.candidates.push(Candidate {
hash: hash,
parent_hash: parent_hash,
total_difficulty: total_difficulty,
hash,
parent_hash,
total_difficulty,
});
// fix ordering of era before writing.
@ -479,9 +479,9 @@ impl HeaderChain {
trace!(target: "chain", "New best block: ({}, {}), TD {}", number, hash, total_difficulty);
pending.best_block = Some(BlockDescriptor {
hash: hash,
number: number,
total_difficulty: total_difficulty,
hash,
number,
total_difficulty,
});
// produce next CHT root if it's time.
@ -651,7 +651,7 @@ impl HeaderChain {
Ok(db_value) => {
db_value.map(|x| x.into_vec()).map(encoded::Header::new)
.and_then(|header| {
cache.insert_block_header(hash.clone(), header.clone());
cache.insert_block_header(hash, header.clone());
Some(header)
})
},
@ -772,16 +772,17 @@ impl HeaderChain {
/// Get block status.
pub fn status(&self, hash: &H256) -> BlockStatus {
match self.db.get(self.col, &*hash).ok().map_or(false, |x| x.is_some()) {
true => BlockStatus::InChain,
false => BlockStatus::Unknown,
if self.db.get(self.col, hash).ok().map_or(false, |x| x.is_some()) {
BlockStatus::InChain
} else {
BlockStatus::Unknown
}
}
/// Insert a pending transition.
pub fn insert_pending_transition(&self, batch: &mut DBTransaction, hash: H256, t: PendingEpochTransition) {
pub fn insert_pending_transition(&self, batch: &mut DBTransaction, hash: H256, t: &PendingEpochTransition) {
let key = pending_transition_key(hash);
batch.put(self.col, &*key, &*::rlp::encode(&t));
batch.put(self.col, &*key, &*::rlp::encode(t));
}
/// Get pending transition for a specific block hash.
@ -865,7 +866,7 @@ mod tests {
use ethcore::ids::BlockId;
use ethcore::header::Header;
use ethcore::spec::Spec;
use cache::Cache;
use cache::Cache;
use kvdb::KeyValueDB;
use kvdb_memorydb;
@ -897,7 +898,7 @@ mod tests {
parent_hash = header.hash();
let mut tx = db.transaction();
let pending = chain.insert(&mut tx, header, None).unwrap();
let pending = chain.insert(&mut tx, &header, None).unwrap();
db.write(tx).unwrap();
chain.apply_pending(pending);
@ -930,7 +931,7 @@ mod tests {
parent_hash = header.hash();
let mut tx = db.transaction();
let pending = chain.insert(&mut tx, header, None).unwrap();
let pending = chain.insert(&mut tx, &header, None).unwrap();
db.write(tx).unwrap();
chain.apply_pending(pending);
@ -949,7 +950,7 @@ mod tests {
parent_hash = header.hash();
let mut tx = db.transaction();
let pending = chain.insert(&mut tx, header, None).unwrap();
let pending = chain.insert(&mut tx, &header, None).unwrap();
db.write(tx).unwrap();
chain.apply_pending(pending);
@ -973,7 +974,7 @@ mod tests {
parent_hash = header.hash();
let mut tx = db.transaction();
let pending = chain.insert(&mut tx, header, None).unwrap();
let pending = chain.insert(&mut tx, &header, None).unwrap();
db.write(tx).unwrap();
chain.apply_pending(pending);
@ -1026,7 +1027,7 @@ mod tests {
parent_hash = header.hash();
let mut tx = db.transaction();
let pending = chain.insert(&mut tx, header, None).unwrap();
let pending = chain.insert(&mut tx, &header, None).unwrap();
db.write(tx).unwrap();
chain.apply_pending(pending);
@ -1066,7 +1067,7 @@ mod tests {
parent_hash = header.hash();
let mut tx = db.transaction();
let pending = chain.insert(&mut tx, header, None).unwrap();
let pending = chain.insert(&mut tx, &header, None).unwrap();
db.write(tx).unwrap();
chain.apply_pending(pending);
@ -1083,7 +1084,7 @@ mod tests {
parent_hash = header.hash();
let mut tx = db.transaction();
let pending = chain.insert(&mut tx, header, None).unwrap();
let pending = chain.insert(&mut tx, &header, None).unwrap();
db.write(tx).unwrap();
chain.apply_pending(pending);
@ -1141,7 +1142,7 @@ mod tests {
None
};
let pending = chain.insert(&mut tx, header, epoch_proof).unwrap();
let pending = chain.insert(&mut tx, &header, epoch_proof).unwrap();
db.write(tx).unwrap();
chain.apply_pending(pending);
@ -1169,7 +1170,7 @@ mod tests {
parent_hash = header.hash();
let mut tx = db.transaction();
let pending = chain.insert(&mut tx, header, None).unwrap();
let pending = chain.insert(&mut tx, &header, None).unwrap();
db.write(tx).unwrap();
chain.apply_pending(pending);
@ -1208,7 +1209,7 @@ mod tests {
parent_hash = header.hash();
let mut tx = db.transaction();
let pending = chain.insert(&mut tx, header, None).expect("failed inserting a transaction");
let pending = chain.insert(&mut tx, &header, None).expect("failed inserting a transaction");
db.write(tx).unwrap();
chain.apply_pending(pending);

View File

@ -176,7 +176,7 @@ impl<T: ChainDataFetcher> Client<T> {
io_channel: IoChannel<ClientIoMessage>,
cache: Arc<Mutex<Cache>>
) -> Result<Self, Error> {
Ok(Client {
Ok(Self {
queue: HeaderQueue::new(config.queue, spec.engine.clone(), io_channel, config.check_seal),
engine: spec.engine.clone(),
chain: {
@ -185,9 +185,9 @@ impl<T: ChainDataFetcher> Client<T> {
},
report: RwLock::new(ClientReport::default()),
import_lock: Mutex::new(()),
db: db,
db,
listeners: RwLock::new(vec![]),
fetcher: fetcher,
fetcher,
verify_full: config.verify_full,
})
}
@ -229,7 +229,7 @@ impl<T: ChainDataFetcher> Client<T> {
BlockChainInfo {
total_difficulty: best_td,
pending_total_difficulty: best_td + self.queue.total_difficulty(),
genesis_hash: genesis_hash,
genesis_hash,
best_block_hash: best_hdr.hash(),
best_block_number: best_hdr.number(),
best_block_timestamp: best_hdr.timestamp(),
@ -313,14 +313,14 @@ impl<T: ChainDataFetcher> Client<T> {
The node may not be able to synchronize further.", e);
}
let epoch_proof = self.engine.is_epoch_end(
let epoch_proof = self.engine.is_epoch_end(
&verified_header,
&|h| self.chain.block_header(BlockId::Hash(h)).and_then(|hdr| hdr.decode().ok()),
&|h| self.chain.pending_transition(h),
);
let mut tx = self.db.transaction();
let pending = match self.chain.insert(&mut tx, verified_header, epoch_proof) {
let pending = match self.chain.insert(&mut tx, &verified_header, epoch_proof) {
Ok(pending) => {
good.push(hash);
self.report.write().blocks_imported += 1;
@ -511,8 +511,8 @@ impl<T: ChainDataFetcher> Client<T> {
};
let mut batch = self.db.transaction();
self.chain.insert_pending_transition(&mut batch, header.hash(), epoch::PendingTransition {
proof: proof,
self.chain.insert_pending_transition(&mut batch, header.hash(), &epoch::PendingTransition {
proof,
});
self.db.write_buffered(batch);
Ok(())
@ -602,7 +602,7 @@ impl<T: ChainDataFetcher> ::ethcore::client::EngineClient for Client<T> {
self.chain.epoch_transition_for(parent_hash).map(|(hdr, proof)| EpochTransition {
block_hash: hdr.hash(),
block_number: hdr.number(),
proof: proof,
proof,
})
}

View File

@ -79,8 +79,8 @@ impl<T: ChainDataFetcher> Service<T> {
spec.engine.register_client(Arc::downgrade(&client) as _);
Ok(Service {
client: client,
io_service: io_service,
client,
io_service,
})
}

View File

@ -126,7 +126,7 @@ impl<'a> BasicContext for TickCtx<'a> {
}
fn request_from(&self, peer: PeerId, requests: Requests) -> Result<ReqId, Error> {
self.proto.request_from(self.io, &peer, requests)
self.proto.request_from(self.io, peer, requests)
}
fn make_announcement(&self, announcement: Announcement) {
@ -159,7 +159,7 @@ impl<'a> BasicContext for Ctx<'a> {
}
fn request_from(&self, peer: PeerId, requests: Requests) -> Result<ReqId, Error> {
self.proto.request_from(self.io, &peer, requests)
self.proto.request_from(self.io, peer, requests)
}
fn make_announcement(&self, announcement: Announcement) {

View File

@ -108,9 +108,9 @@ impl LoadDistribution {
LoadTimer {
start: Instant::now(),
n: n,
n,
dist: self,
kind: kind,
kind,
}
}

View File

@ -77,7 +77,7 @@ const UPDATE_INTERVAL: Duration = Duration::from_millis(5000);
const PACKET_COUNT_V1: u8 = 9;
/// Supported protocol versions.
pub const PROTOCOL_VERSIONS: &'static [(u8, u8)] = &[
pub const PROTOCOL_VERSIONS: &[(u8, u8)] = &[
(1, PACKET_COUNT_V1),
];
@ -309,9 +309,9 @@ mod id_guard {
/// (for forming responses, triggering handlers) until defused
pub fn new(peers: RwLockReadGuard<'a, PeerMap>, peer_id: PeerId, req_id: ReqId) -> Self {
IdGuard {
peers: peers,
peer_id: peer_id,
req_id: req_id,
peers,
peer_id,
req_id,
active: true,
}
}
@ -375,9 +375,9 @@ impl LightProtocol {
);
LightProtocol {
provider: provider,
provider,
config: params.config,
genesis_hash: genesis_hash,
genesis_hash,
network_id: params.network_id,
pending_peers: RwLock::new(HashMap::new()),
peers: RwLock::new(HashMap::new()),
@ -385,13 +385,13 @@ impl LightProtocol {
flow_params: RwLock::new(Arc::new(flow_params)),
handlers: Vec::new(),
req_id: AtomicUsize::new(0),
sample_store: sample_store,
load_distribution: load_distribution,
sample_store,
load_distribution,
}
}
/// Attempt to get peer status.
pub fn peer_status(&self, peer: &PeerId) -> Option<Status> {
pub fn peer_status(&self, peer: PeerId) -> Option<Status> {
self.peers.read().get(&peer)
.map(|peer| peer.lock().status.clone())
}
@ -412,9 +412,9 @@ impl LightProtocol {
/// insufficient credits. Does not check capabilities before sending.
/// On success, returns a request id which can later be coordinated
/// with an event.
pub fn request_from(&self, io: &IoContext, peer_id: &PeerId, requests: Requests) -> Result<ReqId, Error> {
pub fn request_from(&self, io: &IoContext, peer_id: PeerId, requests: Requests) -> Result<ReqId, Error> {
let peers = self.peers.read();
let peer = match peers.get(peer_id) {
let peer = match peers.get(&peer_id) {
Some(peer) => peer,
None => return Err(Error::UnknownPeer),
};
@ -442,7 +442,7 @@ impl LightProtocol {
peer_id, cost, pre_creds);
let req_id = ReqId(self.req_id.fetch_add(1, Ordering::SeqCst));
io.send(*peer_id, packet::REQUEST, {
io.send(peer_id, packet::REQUEST, {
let mut stream = RlpStream::new_list(2);
stream.append(&req_id.0).append_list(&requests.requests());
stream.out()
@ -471,7 +471,7 @@ impl LightProtocol {
// TODO: "urgent" announcements like new blocks?
// the timer approach will skip 1 (possibly 2) in rare occasions.
if peer_info.sent_head == announcement.head_hash ||
peer_info.status.head_num >= announcement.head_num ||
peer_info.status.head_num >= announcement.head_num ||
now - peer_info.last_update < UPDATE_INTERVAL {
continue
}
@ -528,18 +528,18 @@ impl LightProtocol {
// - check whether peer exists
// - check whether request was made
// - check whether request kinds match
fn pre_verify_response(&self, peer: &PeerId, raw: &Rlp) -> Result<IdGuard, Error> {
fn pre_verify_response(&self, peer: PeerId, raw: &Rlp) -> Result<IdGuard, Error> {
let req_id = ReqId(raw.val_at(0)?);
let cur_credits: U256 = raw.val_at(1)?;
trace!(target: "pip", "pre-verifying response for {} from peer {}", req_id, peer);
let peers = self.peers.read();
let res = match peers.get(peer) {
let res = match peers.get(&peer) {
Some(peer_info) => {
let mut peer_info = peer_info.lock();
let peer_info: &mut Peer = &mut *peer_info;
let req_info = peer_info.pending_requests.remove(&req_id, Instant::now());
let req_info = peer_info.pending_requests.remove(req_id, Instant::now());
let last_batched = peer_info.pending_requests.is_empty();
let flow_info = peer_info.remote_flow.as_mut();
@ -565,29 +565,29 @@ impl LightProtocol {
None => Err(Error::UnknownPeer), // probably only occurs in a race of some kind.
};
res.map(|_| IdGuard::new(peers, *peer, req_id))
res.map(|_| IdGuard::new(peers, peer, req_id))
}
/// Handle a packet using the given io context.
/// Packet data is _untrusted_, which means that invalid data won't lead to
/// issues.
pub fn handle_packet(&self, io: &IoContext, peer: &PeerId, packet_id: u8, data: &[u8]) {
pub fn handle_packet(&self, io: &IoContext, peer: PeerId, packet_id: u8, data: &[u8]) {
let rlp = Rlp::new(data);
trace!(target: "pip", "Incoming packet {} from peer {}", packet_id, peer);
// handle the packet
let res = match packet_id {
packet::STATUS => self.status(peer, io, rlp),
packet::ANNOUNCE => self.announcement(peer, io, rlp),
packet::STATUS => self.status(peer, io, &rlp),
packet::ANNOUNCE => self.announcement(peer, io, &rlp),
packet::REQUEST => self.request(peer, io, rlp),
packet::RESPONSE => self.response(peer, io, rlp),
packet::REQUEST => self.request(peer, io, &rlp),
packet::RESPONSE => self.response(peer, io, &rlp),
packet::UPDATE_CREDITS => self.update_credits(peer, io, rlp),
packet::ACKNOWLEDGE_UPDATE => self.acknowledge_update(peer, io, rlp),
packet::UPDATE_CREDITS => self.update_credits(peer, io, &rlp),
packet::ACKNOWLEDGE_UPDATE => self.acknowledge_update(peer, io, &rlp),
packet::SEND_TRANSACTIONS => self.relay_transactions(peer, io, rlp),
packet::SEND_TRANSACTIONS => self.relay_transactions(peer, io, &rlp),
other => {
Err(Error::UnrecognizedPacket(other))
@ -595,7 +595,7 @@ impl LightProtocol {
};
if let Err(e) = res {
punish(*peer, io, e);
punish(peer, io, &e);
}
}
@ -682,14 +682,14 @@ impl LightProtocol {
}
/// called when a peer connects.
pub fn on_connect(&self, peer: &PeerId, io: &IoContext) {
let proto_version = match io.protocol_version(*peer).ok_or(Error::WrongNetwork) {
pub fn on_connect(&self, peer: PeerId, io: &IoContext) {
let proto_version = match io.protocol_version(peer).ok_or(Error::WrongNetwork) {
Ok(pv) => pv,
Err(e) => { punish(*peer, io, e); return }
Err(e) => { punish(peer, io, &e); return }
};
if PROTOCOL_VERSIONS.iter().find(|x| x.0 == proto_version).is_none() {
punish(*peer, io, Error::UnsupportedProtocolVersion(proto_version));
punish(peer, io, &Error::UnsupportedProtocolVersion(proto_version));
return;
}
@ -705,17 +705,17 @@ impl LightProtocol {
last_head: None,
};
let capabilities = self.capabilities.read().clone();
let capabilities = self.capabilities.read();
let local_flow = self.flow_params.read();
let status_packet = status::write_handshake(&status, &capabilities, Some(&**local_flow));
self.pending_peers.write().insert(*peer, PendingPeer {
self.pending_peers.write().insert(peer, PendingPeer {
sent_head: chain_info.best_block_hash,
last_update: Instant::now(),
});
trace!(target: "pip", "Sending status to peer {}", peer);
io.send(*peer, packet::STATUS, status_packet);
io.send(peer, packet::STATUS, status_packet);
}
/// called when a peer disconnects.
@ -736,8 +736,8 @@ impl LightProtocol {
for handler in &self.handlers {
handler.on_disconnect(&Ctx {
peer: peer,
io: io,
peer,
io,
proto: self,
}, &unfulfilled)
}
@ -748,7 +748,7 @@ impl LightProtocol {
where F: FnOnce(&BasicContext) -> T
{
f(&TickCtx {
io: io,
io,
proto: self,
})
}
@ -756,7 +756,7 @@ impl LightProtocol {
fn tick_handlers(&self, io: &IoContext) {
for handler in &self.handlers {
handler.tick(&TickCtx {
io: io,
io,
proto: self,
})
}
@ -787,15 +787,15 @@ impl LightProtocol {
let mut peer_info = peer_info.lock();
io.send(*peer_id, packet::UPDATE_CREDITS, packet_body.clone());
peer_info.awaiting_acknowledge = Some((now.clone(), new_params.clone()));
peer_info.awaiting_acknowledge = Some((now, new_params.clone()));
}
}
}
impl LightProtocol {
// Handle status message from peer.
fn status(&self, peer: &PeerId, io: &IoContext, data: Rlp) -> Result<(), Error> {
let pending = match self.pending_peers.write().remove(peer) {
fn status(&self, peer: PeerId, io: &IoContext, data: &Rlp) -> Result<(), Error> {
let pending = match self.pending_peers.write().remove(&peer) {
Some(pending) => pending,
None => {
return Err(Error::UnexpectedHandshake);
@ -813,33 +813,33 @@ impl LightProtocol {
return Err(Error::WrongNetwork);
}
if Some(status.protocol_version as u8) != io.protocol_version(*peer) {
if Some(status.protocol_version as u8) != io.protocol_version(peer) {
return Err(Error::BadProtocolVersion);
}
let remote_flow = flow_params.map(|params| (params.create_credits(), params));
let local_flow = self.flow_params.read().clone();
self.peers.write().insert(*peer, Mutex::new(Peer {
self.peers.write().insert(peer, Mutex::new(Peer {
local_credits: local_flow.create_credits(),
status: status.clone(),
capabilities,
remote_flow: remote_flow,
remote_flow,
sent_head: pending.sent_head,
last_update: pending.last_update,
pending_requests: RequestSet::default(),
failed_requests: Vec::new(),
propagated_transactions: HashSet::new(),
skip_update: false,
local_flow: local_flow,
local_flow,
awaiting_acknowledge: None,
}));
let any_kept = self.handlers.iter().map(
|handler| handler.on_connect(
&Ctx {
peer: *peer,
io: io,
peer,
io,
proto: self,
},
&status,
@ -855,8 +855,8 @@ impl LightProtocol {
}
// Handle an announcement.
fn announcement(&self, peer: &PeerId, io: &IoContext, data: Rlp) -> Result<(), Error> {
if !self.peers.read().contains_key(peer) {
fn announcement(&self, peer: PeerId, io: &IoContext, data: &Rlp) -> Result<(), Error> {
if !self.peers.read().contains_key(&peer) {
debug!(target: "pip", "Ignoring announcement from unknown peer");
return Ok(())
}
@ -866,7 +866,7 @@ impl LightProtocol {
// scope to ensure locks are dropped before moving into handler-space.
{
let peers = self.peers.read();
let peer_info = match peers.get(peer) {
let peer_info = match peers.get(&peer) {
Some(info) => info,
None => return Ok(()),
};
@ -890,8 +890,8 @@ impl LightProtocol {
for handler in &self.handlers {
handler.on_announcement(&Ctx {
peer: *peer,
io: io,
peer,
io,
proto: self,
}, &announcement);
}
@ -900,7 +900,7 @@ impl LightProtocol {
}
// Receive requests from a peer.
fn request(&self, peer_id: &PeerId, io: &IoContext, raw: Rlp) -> Result<(), Error> {
fn request(&self, peer_id: PeerId, io: &IoContext, raw: &Rlp) -> Result<(), Error> {
// the maximum amount of requests we'll fill in a single packet.
const MAX_REQUESTS: usize = 256;
@ -908,7 +908,7 @@ impl LightProtocol {
use ::request::CompleteRequest;
let peers = self.peers.read();
let peer = match peers.get(peer_id) {
let peer = match peers.get(&peer_id) {
Some(peer) => peer,
None => {
debug!(target: "pip", "Ignoring request from unknown peer");
@ -968,7 +968,7 @@ impl LightProtocol {
}
// handle a packet with responses.
fn response(&self, peer: &PeerId, io: &IoContext, raw: Rlp) -> Result<(), Error> {
fn response(&self, peer: PeerId, io: &IoContext, raw: &Rlp) -> Result<(), Error> {
let (req_id, responses) = {
let id_guard = self.pre_verify_response(peer, &raw)?;
let responses: Vec<Response> = raw.list_at(2)?;
@ -977,9 +977,9 @@ impl LightProtocol {
for handler in &self.handlers {
handler.on_responses(&Ctx {
io: io,
io,
proto: self,
peer: *peer,
peer,
}, req_id, &responses);
}
@ -987,10 +987,10 @@ impl LightProtocol {
}
// handle an update of request credits parameters.
fn update_credits(&self, peer_id: &PeerId, io: &IoContext, raw: Rlp) -> Result<(), Error> {
fn update_credits(&self, peer_id: PeerId, io: &IoContext, raw: &Rlp) -> Result<(), Error> {
let peers = self.peers.read();
let peer = peers.get(peer_id).ok_or(Error::UnknownPeer)?;
let peer = peers.get(&peer_id).ok_or(Error::UnknownPeer)?;
let mut peer = peer.lock();
trace!(target: "pip", "Received an update to request credit params from peer {}", peer_id);
@ -1022,9 +1022,9 @@ impl LightProtocol {
}
// handle an acknowledgement of request credits update.
fn acknowledge_update(&self, peer_id: &PeerId, _io: &IoContext, _raw: Rlp) -> Result<(), Error> {
fn acknowledge_update(&self, peer_id: PeerId, _io: &IoContext, _raw: &Rlp) -> Result<(), Error> {
let peers = self.peers.read();
let peer = peers.get(peer_id).ok_or(Error::UnknownPeer)?;
let peer = peers.get(&peer_id).ok_or(Error::UnknownPeer)?;
let mut peer = peer.lock();
trace!(target: "pip", "Received an acknowledgement for new request credit params from peer {}", peer_id);
@ -1041,7 +1041,7 @@ impl LightProtocol {
}
// Receive a set of transactions to relay.
fn relay_transactions(&self, peer: &PeerId, io: &IoContext, data: Rlp) -> Result<(), Error> {
fn relay_transactions(&self, peer: PeerId, io: &IoContext, data: &Rlp) -> Result<(), Error> {
const MAX_TRANSACTIONS: usize = 256;
let txs: Vec<_> = data.iter()
@ -1053,8 +1053,8 @@ impl LightProtocol {
for handler in &self.handlers {
handler.on_transactions(&Ctx {
peer: *peer,
io: io,
peer,
io,
proto: self,
}, &txs);
}
@ -1064,7 +1064,7 @@ impl LightProtocol {
}
// if something went wrong, figure out how much to punish the peer.
fn punish(peer: PeerId, io: &IoContext, e: Error) {
fn punish(peer: PeerId, io: &IoContext, e: &Error) {
match e.punishment() {
Punishment::None => {}
Punishment::Disconnect => {
@ -1091,11 +1091,11 @@ impl NetworkProtocolHandler for LightProtocol {
}
fn read(&self, io: &NetworkContext, peer: &PeerId, packet_id: u8, data: &[u8]) {
self.handle_packet(&io, peer, packet_id, data);
self.handle_packet(&io, *peer, packet_id, data);
}
fn connected(&self, io: &NetworkContext, peer: &PeerId) {
self.on_connect(peer, &io);
self.on_connect(*peer, &io);
}
fn disconnected(&self, io: &NetworkContext, peer: &PeerId) {

View File

@ -46,7 +46,7 @@ pub struct Credits {
impl Credits {
/// Get the current amount of credits..
pub fn current(&self) -> U256 { self.estimate.clone() }
pub fn current(&self) -> U256 { self.estimate }
/// Make a definitive update.
/// This will be the value obtained after receiving
@ -68,12 +68,11 @@ impl Credits {
/// If unsuccessful, the structure will be unaltered an an
/// error will be produced.
pub fn deduct_cost(&mut self, cost: U256) -> Result<(), Error> {
match cost > self.estimate {
true => Err(Error::NoCredits),
false => {
self.estimate = self.estimate - cost;
Ok(())
}
if cost > self.estimate {
Err(Error::NoCredits)
} else {
self.estimate = self.estimate - cost;
Ok(())
}
}
}
@ -121,7 +120,7 @@ impl Default for CostTable {
fn default() -> Self {
// arbitrarily chosen constants.
CostTable {
base: 100000.into(),
base: 100_000.into(),
headers: Some(10000.into()),
transaction_index: Some(10000.into()),
body: Some(15000.into()),
@ -193,17 +192,17 @@ impl Decodable for CostTable {
}
let table = CostTable {
base: base,
headers: headers,
transaction_index: transaction_index,
body: body,
receipts: receipts,
account: account,
storage: storage,
code: code,
header_proof: header_proof,
transaction_proof: transaction_proof,
epoch_signal: epoch_signal,
base,
headers,
transaction_index,
body,
receipts,
account,
storage,
code,
header_proof,
transaction_proof,
epoch_signal,
};
if table.costs_set() == 0 {
@ -227,9 +226,9 @@ impl FlowParams {
/// credit limit, and (minimum) rate of recharge.
pub fn new(limit: U256, costs: CostTable, recharge: U256) -> Self {
FlowParams {
costs: costs,
limit: limit,
recharge: recharge,
costs,
limit,
recharge,
}
}
@ -283,7 +282,7 @@ impl FlowParams {
};
FlowParams {
costs: costs,
costs,
limit: max.into(),
recharge: recharge.into(),
}
@ -293,19 +292,19 @@ impl FlowParams {
pub fn free() -> Self {
let free_cost: Option<U256> = Some(0.into());
FlowParams {
limit: (!0u64).into(),
limit: (!0_u64).into(),
recharge: 1.into(),
costs: CostTable {
base: 0.into(),
headers: free_cost.clone(),
transaction_index: free_cost.clone(),
body: free_cost.clone(),
receipts: free_cost.clone(),
account: free_cost.clone(),
storage: free_cost.clone(),
code: free_cost.clone(),
header_proof: free_cost.clone(),
transaction_proof: free_cost.clone(),
headers: free_cost,
transaction_index: free_cost,
body: free_cost,
receipts: free_cost,
account: free_cost,
storage: free_cost,
code: free_cost,
header_proof: free_cost,
transaction_proof: free_cost,
epoch_signal: free_cost,
}
}
@ -370,7 +369,7 @@ impl FlowParams {
// recompute and update only in terms of full seconds elapsed
// in order to keep the estimate as an underestimate.
let elapsed = (now - credits.recharge_point).as_secs();
credits.recharge_point = credits.recharge_point + Duration::from_secs(elapsed);
credits.recharge_point += Duration::from_secs(elapsed);
let elapsed: U256 = elapsed.into();
@ -418,7 +417,7 @@ mod tests {
use std::time::Duration;
let flow_params = FlowParams::new(100.into(), Default::default(), 20.into());
let mut credits = flow_params.create_credits();
let mut credits = flow_params.create_credits();
assert!(credits.deduct_cost(101.into()).is_err());
assert!(credits.deduct_cost(10.into()).is_ok());

View File

@ -73,7 +73,7 @@ impl RequestSet {
}
/// Remove a set of requests from the stack.
pub fn remove(&mut self, req_id: &ReqId, now: Instant) -> Option<Requests> {
pub fn remove(&mut self, req_id: ReqId, now: Instant) -> Option<Requests> {
let id = match self.ids.remove(&req_id) {
Some(id) => id,
None => return None,
@ -165,7 +165,7 @@ mod tests {
let test_end = test_begin + req_time;
assert!(req_set.check_timeout(test_end));
req_set.remove(&ReqId(0), test_begin + Duration::from_secs(1)).unwrap();
req_set.remove(ReqId(0), test_begin + Duration::from_secs(1)).unwrap();
assert!(!req_set.check_timeout(test_end));
assert!(req_set.check_timeout(test_end + Duration::from_secs(1)));
}
@ -183,7 +183,7 @@ mod tests {
}
for i in (0..5).rev() {
assert!(req_set.remove(&ReqId(i), test_end).is_some());
assert!(req_set.remove(ReqId(i), test_end).is_some());
assert_eq!(req_set.cumulative_cost, i.into());
}
}

View File

@ -43,8 +43,8 @@ enum Key {
impl Key {
// get the string value of this key.
fn as_str(&self) -> &'static str {
match *self {
fn as_str(self) -> &'static str {
match self {
Key::ProtocolVersion => "protocolVersion",
Key::NetworkId => "networkId",
Key::HeadTD => "headTd",
@ -85,7 +85,7 @@ impl Key {
// helper for decoding key-value pairs in the handshake or an announcement.
struct Parser<'a> {
pos: usize,
rlp: Rlp<'a>,
rlp: &'a Rlp<'a>,
}
impl<'a> Parser<'a> {
@ -208,10 +208,10 @@ impl Capabilities {
/// - chain status
/// - serving capabilities
/// - request credit parameters
pub fn parse_handshake(rlp: Rlp) -> Result<(Status, Capabilities, Option<FlowParams>), DecoderError> {
pub fn parse_handshake(rlp: &Rlp) -> Result<(Status, Capabilities, Option<FlowParams>), DecoderError> {
let mut parser = Parser {
pos: 0,
rlp: rlp,
rlp,
};
let status = Status {
@ -304,7 +304,7 @@ pub struct Announcement {
}
/// Parse an announcement.
pub fn parse_announcement(rlp: Rlp) -> Result<Announcement, DecoderError> {
pub fn parse_announcement(rlp: &Rlp) -> Result<Announcement, DecoderError> {
let mut last_key = None;
let mut announcement = Announcement {
@ -320,7 +320,7 @@ pub fn parse_announcement(rlp: Rlp) -> Result<Announcement, DecoderError> {
let mut parser = Parser {
pos: 4,
rlp: rlp,
rlp,
};
while let Some((key, item)) = parser.get_next()? {
@ -404,7 +404,7 @@ mod tests {
let handshake = write_handshake(&status, &capabilities, Some(&flow_params));
let (read_status, read_capabilities, read_flow)
= parse_handshake(Rlp::new(&handshake)).unwrap();
= parse_handshake(&Rlp::new(&handshake)).unwrap();
assert_eq!(read_status, status);
assert_eq!(read_capabilities, capabilities);
@ -439,7 +439,7 @@ mod tests {
let handshake = write_handshake(&status, &capabilities, Some(&flow_params));
let (read_status, read_capabilities, read_flow)
= parse_handshake(Rlp::new(&handshake)).unwrap();
= parse_handshake(&Rlp::new(&handshake)).unwrap();
assert_eq!(read_status, status);
assert_eq!(read_capabilities, capabilities);
@ -489,7 +489,7 @@ mod tests {
};
let (read_status, read_capabilities, read_flow)
= parse_handshake(Rlp::new(&interleaved)).unwrap();
= parse_handshake(&Rlp::new(&interleaved)).unwrap();
assert_eq!(read_status, status);
assert_eq!(read_capabilities, capabilities);
@ -510,7 +510,7 @@ mod tests {
};
let serialized = write_announcement(&announcement);
let read = parse_announcement(Rlp::new(&serialized)).unwrap();
let read = parse_announcement(&Rlp::new(&serialized)).unwrap();
assert_eq!(read, announcement);
}
@ -522,26 +522,26 @@ mod tests {
let mut stream = RlpStream::new_list(6);
stream
.append(&H256::zero())
.append(&10u64)
.append(&100_000u64)
.append(&2u64)
.append_raw(&encode_pair(Key::ServeStateSince, &44u64), 1)
.append(&10_u64)
.append(&100_000_u64)
.append(&2_u64)
.append_raw(&encode_pair(Key::ServeStateSince, &44_u64), 1)
.append_raw(&encode_flag(Key::ServeHeaders), 1);
let out = stream.drain();
assert!(parse_announcement(Rlp::new(&out)).is_err());
assert!(parse_announcement(&Rlp::new(&out)).is_err());
let mut stream = RlpStream::new_list(6);
stream
.append(&H256::zero())
.append(&10u64)
.append(&100_000u64)
.append(&2u64)
.append(&10_u64)
.append(&100_000_u64)
.append(&2_u64)
.append_raw(&encode_flag(Key::ServeHeaders), 1)
.append_raw(&encode_pair(Key::ServeStateSince, &44u64), 1);
.append_raw(&encode_pair(Key::ServeStateSince, &44_u64), 1);
let out = stream.drain();
assert!(parse_announcement(Rlp::new(&out)).is_ok());
assert!(parse_announcement(&Rlp::new(&out)).is_ok());
}
#[test]
@ -566,7 +566,7 @@ mod tests {
let handshake = write_handshake(&status, &capabilities, None);
let (read_status, read_capabilities, read_flow)
= parse_handshake(Rlp::new(&handshake)).unwrap();
= parse_handshake(&Rlp::new(&handshake)).unwrap();
assert_eq!(read_status, status);
assert_eq!(read_capabilities, capabilities);

View File

@ -228,7 +228,7 @@ fn handshake_expected() {
let packet_body = write_handshake(&status, &capabilities, &proto);
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body));
proto.on_connect(1, &Expect::Send(1, packet::STATUS, packet_body));
}
#[test]
@ -243,7 +243,7 @@ fn genesis_mismatch() {
let packet_body = write_handshake(&status, &capabilities, &proto);
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body));
proto.on_connect(1, &Expect::Send(1, packet::STATUS, packet_body));
}
#[test]
@ -256,12 +256,12 @@ fn credit_overflow() {
{
let packet_body = write_handshake(&status, &capabilities, &proto);
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body));
proto.on_connect(1, &Expect::Send(1, packet::STATUS, packet_body));
}
{
let my_status = write_handshake(&status, &capabilities, &proto);
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &my_status);
proto.handle_packet(&Expect::Nothing, 1, packet::STATUS, &my_status);
}
// 1 billion requests is far too many for the default flow params.
@ -273,7 +273,7 @@ fn credit_overflow() {
}));
let request = make_packet(111, &requests);
proto.handle_packet(&Expect::Punish(1), &1, packet::REQUEST, &request);
proto.handle_packet(&Expect::Punish(1), 1, packet::REQUEST, &request);
}
// test the basic request types -- these just make sure that requests are parsed
@ -295,8 +295,8 @@ fn get_block_headers() {
{
let packet_body = write_handshake(&cur_status, &capabilities, &proto);
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body));
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &my_status);
proto.on_connect(1, &Expect::Send(1, packet::STATUS, packet_body));
proto.handle_packet(&Expect::Nothing, 1, packet::STATUS, &my_status);
}
let request = Request::Headers(IncompleteHeadersRequest {
@ -317,9 +317,7 @@ fn get_block_headers() {
let new_creds = *flow_params.limit() - flow_params.compute_cost_multi(requests.requests()).unwrap();
let response = vec![Response::Headers(HeadersResponse {
headers: headers,
})];
let response = vec![Response::Headers(HeadersResponse { headers })];
let mut stream = RlpStream::new_list(3);
stream.append(&req_id).append(&new_creds).append_list(&response);
@ -328,7 +326,7 @@ fn get_block_headers() {
};
let expected = Expect::Respond(packet::RESPONSE, response);
proto.handle_packet(&expected, &1, packet::REQUEST, &request_body);
proto.handle_packet(&expected, 1, packet::REQUEST, &request_body);
}
#[test]
@ -347,8 +345,8 @@ fn get_block_bodies() {
{
let packet_body = write_handshake(&cur_status, &capabilities, &proto);
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body));
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &my_status);
proto.on_connect(1, &Expect::Send(1, packet::STATUS, packet_body));
proto.handle_packet(&Expect::Nothing, 1, packet::STATUS, &my_status);
}
let mut builder = Builder::default();
@ -376,7 +374,7 @@ fn get_block_bodies() {
};
let expected = Expect::Respond(packet::RESPONSE, response);
proto.handle_packet(&expected, &1, packet::REQUEST, &request_body);
proto.handle_packet(&expected, 1, packet::REQUEST, &request_body);
}
#[test]
@ -395,8 +393,8 @@ fn get_block_receipts() {
{
let packet_body = write_handshake(&cur_status, &capabilities, &proto);
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body));
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &my_status);
proto.on_connect(1, &Expect::Send(1, packet::STATUS, packet_body));
proto.handle_packet(&Expect::Nothing, 1, packet::STATUS, &my_status);
}
// find the first 10 block hashes starting with `f` because receipts are only provided
@ -431,7 +429,7 @@ fn get_block_receipts() {
};
let expected = Expect::Respond(packet::RESPONSE, response);
proto.handle_packet(&expected, &1, packet::REQUEST, &request_body);
proto.handle_packet(&expected, 1, packet::REQUEST, &request_body);
}
#[test]
@ -447,8 +445,8 @@ fn get_state_proofs() {
{
let packet_body = write_handshake(&cur_status, &capabilities, &proto);
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body.clone()));
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &packet_body);
proto.on_connect(1, &Expect::Send(1, packet::STATUS, packet_body.clone()));
proto.handle_packet(&Expect::Nothing, 1, packet::STATUS, &packet_body);
}
let req_id = 112;
@ -490,7 +488,7 @@ fn get_state_proofs() {
};
let expected = Expect::Respond(packet::RESPONSE, response);
proto.handle_packet(&expected, &1, packet::REQUEST, &request_body);
proto.handle_packet(&expected, 1, packet::REQUEST, &request_body);
}
#[test]
@ -504,8 +502,8 @@ fn get_contract_code() {
{
let packet_body = write_handshake(&cur_status, &capabilities, &proto);
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body.clone()));
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &packet_body);
proto.on_connect(1, &Expect::Send(1, packet::STATUS, packet_body.clone()));
proto.handle_packet(&Expect::Nothing, 1, packet::STATUS, &packet_body);
}
let req_id = 112;
@ -533,7 +531,7 @@ fn get_contract_code() {
};
let expected = Expect::Respond(packet::RESPONSE, response);
proto.handle_packet(&expected, &1, packet::REQUEST, &request_body);
proto.handle_packet(&expected, 1, packet::REQUEST, &request_body);
}
#[test]
@ -547,8 +545,8 @@ fn epoch_signal() {
{
let packet_body = write_handshake(&cur_status, &capabilities, &proto);
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body.clone()));
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &packet_body);
proto.on_connect(1, &Expect::Send(1, packet::STATUS, packet_body.clone()));
proto.handle_packet(&Expect::Nothing, 1, packet::STATUS, &packet_body);
}
let req_id = 112;
@ -576,7 +574,7 @@ fn epoch_signal() {
};
let expected = Expect::Respond(packet::RESPONSE, response);
proto.handle_packet(&expected, &1, packet::REQUEST, &request_body);
proto.handle_packet(&expected, 1, packet::REQUEST, &request_body);
}
#[test]
@ -590,8 +588,8 @@ fn proof_of_execution() {
{
let packet_body = write_handshake(&cur_status, &capabilities, &proto);
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body.clone()));
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &packet_body);
proto.on_connect(1, &Expect::Send(1, packet::STATUS, packet_body.clone()));
proto.handle_packet(&Expect::Nothing, 1, packet::STATUS, &packet_body);
}
let req_id = 112;
@ -622,7 +620,7 @@ fn proof_of_execution() {
};
let expected = Expect::Respond(packet::RESPONSE, response);
proto.handle_packet(&expected, &1, packet::REQUEST, &request_body);
proto.handle_packet(&expected, 1, packet::REQUEST, &request_body);
// next: way too much requested gas.
if let Request::Execution(ref mut req) = request {
@ -633,7 +631,7 @@ fn proof_of_execution() {
let request_body = make_packet(req_id, &requests);
let expected = Expect::Punish(1);
proto.handle_packet(&expected, &1, packet::REQUEST, &request_body);
proto.handle_packet(&expected, 1, packet::REQUEST, &request_body);
}
#[test]
@ -682,33 +680,33 @@ fn id_guard() {
{
let mut stream = RlpStream::new_list(3);
stream.append(&req_id_1.0);
stream.append(&4_000_000usize);
stream.begin_list(2).append(&125usize).append(&3usize);
stream.append(&4_000_000_usize);
stream.begin_list(2).append(&125_usize).append(&3_usize);
let packet = stream.out();
assert!(proto.response(&peer_id, &Expect::Nothing, Rlp::new(&packet)).is_err());
assert!(proto.response(peer_id, &Expect::Nothing, &Rlp::new(&packet)).is_err());
}
// next, do an unexpected response.
{
let mut stream = RlpStream::new_list(3);
stream.append(&10000usize);
stream.append(&3_000_000usize);
stream.append(&10000_usize);
stream.append(&3_000_000_usize);
stream.begin_list(0);
let packet = stream.out();
assert!(proto.response(&peer_id, &Expect::Nothing, Rlp::new(&packet)).is_err());
assert!(proto.response(peer_id, &Expect::Nothing, &Rlp::new(&packet)).is_err());
}
// lastly, do a valid (but empty) response.
{
let mut stream = RlpStream::new_list(3);
stream.append(&req_id_2.0);
stream.append(&3_000_000usize);
stream.append(&3_000_000_usize);
stream.begin_list(0);
let packet = stream.out();
assert!(proto.response(&peer_id, &Expect::Nothing, Rlp::new(&packet)).is_ok());
assert!(proto.response(peer_id, &Expect::Nothing, &Rlp::new(&packet)).is_ok());
}
let peers = proto.peers.read();
@ -730,8 +728,8 @@ fn get_transaction_index() {
{
let packet_body = write_handshake(&cur_status, &capabilities, &proto);
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body.clone()));
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &packet_body);
proto.on_connect(1, &Expect::Send(1, packet::STATUS, packet_body.clone()));
proto.handle_packet(&Expect::Nothing, 1, packet::STATUS, &packet_body);
}
let req_id = 112;
@ -759,5 +757,5 @@ fn get_transaction_index() {
};
let expected = Expect::Respond(packet::RESPONSE, response);
proto.handle_packet(&expected, &1, packet::REQUEST, &request_body);
proto.handle_packet(&expected, 1, packet::REQUEST, &request_body);
}

View File

@ -69,8 +69,8 @@ impl Peer {
};
local_caps.serve_headers >= request.serve_headers &&
can_serve_since(request.serve_chain_since, local_caps.serve_chain_since) &&
can_serve_since(request.serve_state_since, local_caps.serve_state_since)
can_serve_since(request.serve_chain_since, local_caps.serve_chain_since) &&
can_serve_since(request.serve_state_since, local_caps.serve_state_since)
}
}
@ -111,19 +111,16 @@ impl Pending {
// verification.
// `idx` is the index of the request the response corresponds to.
fn update_header_refs(&mut self, idx: usize, response: &Response) {
match *response {
Response::HeaderByHash(ref hdr) => {
if let Response::HeaderByHash(ref hdr) = *response {
// fill the header for all requests waiting on this one.
// TODO: could be faster if we stored a map usize => Vec<usize>
// but typical use just has one header request that others
// depend on.
for r in self.requests.iter_mut().skip(idx + 1) {
if r.needs_header().map_or(false, |(i, _)| i == idx) {
r.provide_header(hdr.clone())
}
for r in self.requests.iter_mut().skip(idx + 1) {
if r.needs_header().map_or(false, |(i, _)| i == idx) {
r.provide_header(hdr.clone())
}
}
_ => {}, // no other responses produce headers.
}
}
@ -265,7 +262,7 @@ impl OnDemand {
pending: RwLock::new(Vec::new()),
peers: RwLock::new(HashMap::new()),
in_transit: RwLock::new(HashMap::new()),
cache: cache,
cache,
no_immediate_dispatch: false,
}
}
@ -312,7 +309,7 @@ impl OnDemand {
}
}
if let CheckedRequest::HeaderByHash(ref req, _) = request {
header_producers.insert(i, req.0.clone());
header_producers.insert(i, req.0);
}
builder.push(request)?;
@ -323,11 +320,11 @@ impl OnDemand {
let capabilities = guess_capabilities(requests.requests());
self.submit_pending(ctx, Pending {
requests: requests,
net_requests: net_requests,
requests,
net_requests,
required_capabilities: capabilities,
responses: responses,
sender: sender,
responses,
sender,
});
Ok(receiver)

View File

@ -224,7 +224,7 @@ impl HeaderRef {
fn field(&self) -> Field<H256> {
match *self {
HeaderRef::Stored(ref hdr) => Field::Scalar(hdr.hash()),
HeaderRef::Unresolved(_, ref field) => field.clone(),
HeaderRef::Unresolved(_, field) => field,
}
}
@ -232,7 +232,7 @@ impl HeaderRef {
fn needs_header(&self) -> Option<(usize, Field<H256>)> {
match *self {
HeaderRef::Stored(_) => None,
HeaderRef::Unresolved(idx, ref field) => Some((idx, field.clone())),
HeaderRef::Unresolved(idx, field) => Some((idx, field)),
}
}
}
@ -292,7 +292,7 @@ impl From<Request> for CheckedRequest {
}
Request::TransactionIndex(req) => {
let net_req = net_request::IncompleteTransactionIndexRequest {
hash: req.0.clone(),
hash: req.0,
};
trace!(target: "on_demand", "TransactionIndex Request, {:?}", net_req);
CheckedRequest::TransactionIndex(req, net_req)
@ -322,7 +322,7 @@ impl From<Request> for CheckedRequest {
Request::Code(req) => {
let net_req = net_request::IncompleteCodeRequest {
block_hash: req.header.field(),
code_hash: req.code_hash.into(),
code_hash: req.code_hash,
};
trace!(target: "on_demand", "Code Request, {:?}", net_req);
CheckedRequest::Code(req, net_req)
@ -404,7 +404,7 @@ impl CheckedRequest {
match *self {
CheckedRequest::HeaderProof(ref check, _) => {
let mut cache = cache.lock();
cache.block_hash(&check.num)
cache.block_hash(check.num)
.and_then(|h| cache.chain_score(&h).map(|s| (h, s)))
.map(|(h, s)| Response::HeaderProof((h, s)))
}
@ -448,7 +448,7 @@ impl CheckedRequest {
}
CheckedRequest::Body(ref check, ref req) => {
// check for empty body.
if let Some(hdr) = check.0.as_ref().ok() {
if let Ok(hdr) = check.0.as_ref() {
if hdr.transactions_root() == KECCAK_NULL_RLP && hdr.uncles_hash() == KECCAK_EMPTY_LIST_RLP {
let mut stream = RlpStream::new_list(3);
stream.append_raw(hdr.rlp().as_raw(), 1);
@ -769,9 +769,9 @@ impl HeaderProof {
/// Provide the expected CHT root to compare against.
pub fn new(num: u64, cht_root: H256) -> Option<Self> {
::cht::block_to_cht_number(num).map(|cht_num| HeaderProof {
num: num,
cht_num: cht_num,
cht_root: cht_root,
num,
cht_num,
cht_root,
})
}
@ -817,9 +817,9 @@ impl HeaderWithAncestors {
headers: &[encoded::Header]
) -> Result<Vec<encoded::Header>, Error> {
let expected_hash = match (self.block_hash, start) {
(Field::Scalar(ref h), &net_request::HashOrNumber::Hash(ref h2)) => {
if h != h2 { return Err(Error::WrongHash(*h, *h2)) }
*h
(Field::Scalar(h), &net_request::HashOrNumber::Hash(h2)) => {
if h != h2 { return Err(Error::WrongHash(h, h2)) }
h
}
(_, &net_request::HashOrNumber::Hash(h2)) => h2,
_ => return Err(Error::HeaderByNumber),
@ -871,9 +871,9 @@ impl HeaderByHash {
headers: &[encoded::Header]
) -> Result<encoded::Header, Error> {
let expected_hash = match (self.0, start) {
(Field::Scalar(ref h), &net_request::HashOrNumber::Hash(ref h2)) => {
if h != h2 { return Err(Error::WrongHash(*h, *h2)) }
*h
(Field::Scalar(h), &net_request::HashOrNumber::Hash(h2)) => {
if h != h2 { return Err(Error::WrongHash(h, h2)) }
h
}
(_, &net_request::HashOrNumber::Hash(h2)) => h2,
_ => return Err(Error::HeaderByNumber),
@ -881,12 +881,11 @@ impl HeaderByHash {
let header = headers.get(0).ok_or(Error::Empty)?;
let hash = header.hash();
match hash == expected_hash {
true => {
cache.lock().insert_block_header(hash, header.clone());
Ok(header.clone())
}
false => Err(Error::WrongHash(expected_hash, hash)),
if hash == expected_hash {
cache.lock().insert_block_header(hash, header.clone());
Ok(header.clone())
} else {
Err(Error::WrongHash(expected_hash, hash))
}
}
}
@ -957,15 +956,12 @@ impl BlockReceipts {
let receipts_root = self.0.as_ref()?.receipts_root();
let found_root = ::triehash::ordered_trie_root(receipts.iter().map(|r| ::rlp::encode(r)));
match receipts_root == found_root {
true => {
cache.lock().insert_block_receipts(receipts_root, receipts.to_vec());
Ok(receipts.to_vec())
}
false => {
trace!(target: "on_demand", "Receipt Reponse: \"WrongTrieRoot\" receipts_root: {:?} found_root: {:?}", receipts_root, found_root);
Err(Error::WrongTrieRoot(receipts_root, found_root))
}
if receipts_root == found_root {
cache.lock().insert_block_receipts(receipts_root, receipts.to_vec());
Ok(receipts.to_vec())
} else {
trace!(target: "on_demand", "Receipt Reponse: \"WrongTrieRoot\" receipts_root: {:?} found_root: {:?}", receipts_root, found_root);
Err(Error::WrongTrieRoot(receipts_root, found_root))
}
}
}
@ -1052,7 +1048,7 @@ impl TransactionProof {
let root = self.header.as_ref()?.state_root();
let mut env_info = self.env_info.clone();
env_info.gas_limit = self.tx.gas.clone();
env_info.gas_limit = self.tx.gas;
let proved_execution = state::check_proof(
state_items,

View File

@ -87,9 +87,9 @@ pub trait Provider: Send + Sync {
let max = ::std::cmp::min(MAX_HEADERS_PER_REQUEST, req.max);
let headers: Vec<_> = (0u64..max)
let headers: Vec<_> = (0_u64..max)
.map(|x: u64| x.saturating_mul(req.skip.saturating_add(1)))
.take_while(|x| if req.reverse { x < &start_num } else { best_num.saturating_sub(start_num) >= *x })
.take_while(|&x| if req.reverse { x < start_num } else { best_num.saturating_sub(start_num) >= x })
.map(|x| if req.reverse { start_num.saturating_sub(x) } else { start_num.saturating_add(x) })
.map(|x| self.block_header(BlockId::Number(x)))
.take_while(|x| x.is_some())
@ -99,7 +99,7 @@ pub trait Provider: Send + Sync {
if headers.is_empty() {
None
} else {
Some(::request::HeadersResponse { headers: headers })
Some(::request::HeadersResponse { headers })
}
}
@ -172,7 +172,7 @@ impl<T: ProvingBlockChainClient + ?Sized> Provider for T {
fn block_body(&self, req: request::CompleteBodyRequest) -> Option<request::BodyResponse> {
BlockChainClient::block_body(self, BlockId::Hash(req.hash))
.map(|body| ::request::BodyResponse { body: body })
.map(|body| ::request::BodyResponse { body })
}
fn block_receipts(&self, req: request::CompleteReceiptsRequest) -> Option<request::ReceiptsResponse> {
@ -183,7 +183,7 @@ impl<T: ProvingBlockChainClient + ?Sized> Provider for T {
fn account_proof(&self, req: request::CompleteAccountRequest) -> Option<request::AccountResponse> {
self.prove_account(req.address_hash, BlockId::Hash(req.block_hash)).map(|(proof, acc)| {
::request::AccountResponse {
proof: proof,
proof,
nonce: acc.nonce,
balance: acc.balance,
code_hash: acc.code_hash,
@ -195,7 +195,7 @@ impl<T: ProvingBlockChainClient + ?Sized> Provider for T {
fn storage_proof(&self, req: request::CompleteStorageRequest) -> Option<request::StorageResponse> {
self.prove_storage(req.address_hash, req.key_hash, BlockId::Hash(req.block_hash)).map(|(proof, item) | {
::request::StorageResponse {
proof: proof,
proof,
value: item,
}
})
@ -203,7 +203,7 @@ impl<T: ProvingBlockChainClient + ?Sized> Provider for T {
fn contract_code(&self, req: request::CompleteCodeRequest) -> Option<request::CodeResponse> {
self.state_data(&req.code_hash)
.map(|code| ::request::CodeResponse { code: code })
.map(|code| ::request::CodeResponse { code })
}
fn header_proof(&self, req: request::CompleteHeaderProofRequest) -> Option<request::HeaderProofResponse> {
@ -252,7 +252,7 @@ impl<T: ProvingBlockChainClient + ?Sized> Provider for T {
// prove our result.
match cht.prove(req.num, 0) {
Ok(Some(proof)) => Some(::request::HeaderProofResponse {
proof: proof,
proof,
hash: needed_hdr.hash(),
td: needed_td,
}),
@ -268,12 +268,12 @@ impl<T: ProvingBlockChainClient + ?Sized> Provider for T {
use transaction::Transaction;
let id = BlockId::Hash(req.block_hash);
let nonce = match self.nonce(&req.from, id.clone()) {
let nonce = match self.nonce(&req.from, id) {
Some(nonce) => nonce,
None => return None,
};
let transaction = Transaction {
nonce: nonce,
nonce,
gas: req.gas,
gas_price: req.gas_price,
action: req.action,
@ -294,7 +294,7 @@ impl<T: ProvingBlockChainClient + ?Sized> Provider for T {
fn epoch_signal(&self, req: request::CompleteSignalRequest) -> Option<request::SignalResponse> {
self.epoch_signal(req.block_hash).map(|signal| request::SignalResponse {
signal: signal,
signal,
})
}
}
@ -310,8 +310,8 @@ impl<L> LightProvider<L> {
/// Create a new `LightProvider` from the given client and transaction queue.
pub fn new(client: Arc<L>, txqueue: Arc<RwLock<TransactionQueue>>) -> Self {
LightProvider {
client: client,
txqueue: txqueue,
client,
txqueue,
}
}
}

View File

@ -74,7 +74,7 @@ impl<'a> From<&'a PendingTransaction> for TransactionInfo {
fn from(tx: &'a PendingTransaction) -> Self {
TransactionInfo {
hash: tx.hash(),
nonce: tx.nonce.clone(),
nonce: tx.nonce,
condition: tx.condition.clone(),
}
}
@ -104,15 +104,9 @@ impl AccountTransactions {
let mut promoted = Vec::new();
let mut next_nonce = self.next_nonce();
loop {
match self.future.remove(&next_nonce) {
Some(tx) => {
promoted.push(tx.hash);
self.current.push(tx)
},
None => break,
}
while let Some(tx) = self.future.remove(&next_nonce) {
promoted.push(tx.hash);
self.current.push(tx);
next_nonce = next_nonce + 1;
}
@ -154,7 +148,7 @@ impl fmt::Debug for TransactionQueue {
impl TransactionQueue {
/// Import a pending transaction to be queued.
pub fn import(&mut self, tx: PendingTransaction) -> Result<ImportDestination, transaction::Error> {
pub fn import(&mut self, tx: PendingTransaction) -> Result<ImportDestination, transaction::Error> {
let sender = tx.sender();
let hash = tx.hash();
let nonce = tx.nonce;
@ -174,7 +168,7 @@ impl TransactionQueue {
}
Entry::Occupied(mut entry) => {
let acct_txs = entry.get_mut();
if &nonce < acct_txs.cur_nonce.value() {
if nonce < *acct_txs.cur_nonce.value() {
// don't accept txs from before known current nonce.
if acct_txs.cur_nonce.is_known() {
return Err(transaction::Error::Old)

View File

@ -764,9 +764,7 @@ pub mod header {
headers.push(encoded::Header::new(item.as_raw().to_owned()));
}
Ok(Response {
headers: headers,
})
Ok(Response { headers })
}
}
@ -814,7 +812,7 @@ pub mod header_proof {
fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> {
if let Field::BackReference(req, idx) = self.num {
self.num = match oracle(req, idx) {
Ok(Output::Number(num)) => Field::Scalar(num.into()),
Ok(Output::Number(num)) => Field::Scalar(num),
_ => Field::BackReference(req, idx),
}
}
@ -1053,7 +1051,7 @@ pub mod block_body {
fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> {
if let Field::BackReference(req, idx) = self.hash {
self.hash = match oracle(req, idx) {
Ok(Output::Hash(hash)) => Field::Scalar(hash.into()),
Ok(Output::Hash(hash)) => Field::Scalar(hash),
_ => Field::BackReference(req, idx),
}
}
@ -1152,14 +1150,14 @@ pub mod account {
fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> {
if let Field::BackReference(req, idx) = self.block_hash {
self.block_hash = match oracle(req, idx) {
Ok(Output::Hash(block_hash)) => Field::Scalar(block_hash.into()),
Ok(Output::Hash(block_hash)) => Field::Scalar(block_hash),
_ => Field::BackReference(req, idx),
}
}
if let Field::BackReference(req, idx) = self.address_hash {
self.address_hash = match oracle(req, idx) {
Ok(Output::Hash(address_hash)) => Field::Scalar(address_hash.into()),
Ok(Output::Hash(address_hash)) => Field::Scalar(address_hash),
_ => Field::BackReference(req, idx),
}
}
@ -1257,21 +1255,21 @@ pub mod storage {
fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> {
if let Field::BackReference(req, idx) = self.block_hash {
self.block_hash = match oracle(req, idx) {
Ok(Output::Hash(block_hash)) => Field::Scalar(block_hash.into()),
Ok(Output::Hash(block_hash)) => Field::Scalar(block_hash),
_ => Field::BackReference(req, idx),
}
}
if let Field::BackReference(req, idx) = self.address_hash {
self.address_hash = match oracle(req, idx) {
Ok(Output::Hash(address_hash)) => Field::Scalar(address_hash.into()),
Ok(Output::Hash(address_hash)) => Field::Scalar(address_hash),
_ => Field::BackReference(req, idx),
}
}
if let Field::BackReference(req, idx) = self.key_hash {
self.key_hash = match oracle(req, idx) {
Ok(Output::Hash(key_hash)) => Field::Scalar(key_hash.into()),
Ok(Output::Hash(key_hash)) => Field::Scalar(key_hash),
_ => Field::BackReference(req, idx),
}
}
@ -1357,14 +1355,14 @@ pub mod contract_code {
fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> {
if let Field::BackReference(req, idx) = self.block_hash {
self.block_hash = match oracle(req, idx) {
Ok(Output::Hash(block_hash)) => Field::Scalar(block_hash.into()),
Ok(Output::Hash(block_hash)) => Field::Scalar(block_hash),
_ => Field::BackReference(req, idx),
}
}
if let Field::BackReference(req, idx) = self.code_hash {
self.code_hash = match oracle(req, idx) {
Ok(Output::Hash(code_hash)) => Field::Scalar(code_hash.into()),
Ok(Output::Hash(code_hash)) => Field::Scalar(code_hash),
_ => Field::BackReference(req, idx),
}
}
@ -1452,7 +1450,7 @@ pub mod execution {
fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> {
if let Field::BackReference(req, idx) = self.block_hash {
self.block_hash = match oracle(req, idx) {
Ok(Output::Hash(block_hash)) => Field::Scalar(block_hash.into()),
Ok(Output::Hash(block_hash)) => Field::Scalar(block_hash),
_ => Field::BackReference(req, idx),
}
}
@ -1514,9 +1512,7 @@ pub mod execution {
items.push(item);
}
Ok(Response {
items: items,
})
Ok(Response { items })
}
}
@ -1578,7 +1574,7 @@ pub mod epoch_signal {
fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> {
if let Field::BackReference(req, idx) = self.block_hash {
self.block_hash = match oracle(req, idx) {
Ok(Output::Hash(block_hash)) => Field::Scalar(block_hash.into()),
Ok(Output::Hash(block_hash)) => Field::Scalar(block_hash),
_ => Field::BackReference(req, idx),
}
}

View File

@ -362,7 +362,7 @@ impl SyncProvider for EthSync {
remote_address: session_info.remote_address,
local_address: session_info.local_address,
eth_info: eth_sync.peer_info(&peer_id),
pip_info: light_proto.as_ref().and_then(|lp| lp.peer_status(&peer_id)).map(Into::into),
pip_info: light_proto.as_ref().and_then(|lp| lp.peer_status(peer_id)).map(Into::into),
})
}).collect()
}).unwrap_or_else(Vec::new)
@ -922,7 +922,7 @@ impl LightSyncProvider for LightSync {
remote_address: session_info.remote_address,
local_address: session_info.local_address,
eth_info: None,
pip_info: self.proto.peer_status(&peer_id).map(Into::into),
pip_info: self.proto.peer_status(peer_id).map(Into::into),
})
}).collect()
}).unwrap_or_else(Vec::new)

View File

@ -183,7 +183,7 @@ impl Fetcher {
let headers = ctx.data();
if headers.len() == 0 {
if headers.is_empty() {
trace!(target: "sync", "Punishing peer {} for empty response", ctx.responder());
ctx.punish_responder();
@ -204,20 +204,19 @@ impl Fetcher {
Ok(headers) => {
let mut parent_hash = None;
for header in headers {
if parent_hash.as_ref().map_or(false, |h| h != &header.hash()) {
trace!(target: "sync", "Punishing peer {} for parent mismatch", ctx.responder());
ctx.punish_responder();
self.requests.push(request);
return SyncRound::Fetch(self);
if let Some(hash) = parent_hash.as_ref() {
if *hash != header.hash() {
trace!(target: "sync", "Punishing peer {} for parent mismatch", ctx.responder());
ctx.punish_responder();
self.requests.push(request);
return SyncRound::Fetch(self);
}
}
// incrementally update the frame request as we go so we can
// return at any time in the loop.
parent_hash = Some(header.parent_hash().clone());
parent_hash = Some(*header.parent_hash());
request.headers_request.start = header.parent_hash().clone().into();
request.headers_request.max -= 1;
request.downloaded.push_front(header);
}
@ -379,7 +378,7 @@ impl RoundStart {
match response::verify(ctx.data(), &req) {
Ok(headers) => {
if self.sparse_headers.len() == 0
if self.sparse_headers.is_empty()
&& headers.get(0).map_or(false, |x| x.parent_hash() != &self.start_block.1) {
trace!(target: "sync", "Wrong parent for first header in round");
ctx.punish_responder(); // or should we reset?

View File

@ -164,7 +164,7 @@ impl PeerLike for Peer {
fn on_connect(&self, other: PeerId) {
let io = self.io(Some(other));
self.proto.on_connect(&other, &io);
self.proto.on_connect(other, &io);
}
fn on_disconnect(&self, other: PeerId){
@ -174,7 +174,7 @@ impl PeerLike for Peer {
fn receive_message(&self, from: PeerId, msg: TestPacket) -> HashSet<PeerId> {
let io = self.io(Some(from));
self.proto.handle_packet(&io, &from, msg.packet_id, &msg.data);
self.proto.handle_packet(&io, from, msg.packet_id, &msg.data);
io.to_disconnect.into_inner()
}

View File

@ -423,16 +423,14 @@ pub fn pending_logs<M>(miner: &M, best_block: EthBlockNumber, filter: &EthcoreFi
.flat_map(|(hash, r)| r.logs.into_iter().map(|l| (hash.clone(), l)).collect::<Vec<(H256, LogEntry)>>())
.collect::<Vec<(H256, LogEntry)>>();
let result = pending_logs.into_iter()
pending_logs.into_iter()
.filter(|pair| filter.matches(&pair.1))
.map(|pair| {
let mut log = Log::from(pair.1);
log.transaction_hash = Some(pair.0.into());
log
})
.collect();
result
.collect()
}
fn check_known<C>(client: &C, number: BlockNumber) -> Result<()> where C: BlockChainClient {

View File

@ -52,7 +52,7 @@ use v1::types::{
};
use v1::metadata::Metadata;
const NO_INVALID_BACK_REFS: &'static str = "Fails only on invalid back-references; back-references here known to be valid; qed";
const NO_INVALID_BACK_REFS: &str = "Fails only on invalid back-references; back-references here known to be valid; qed";
/// Light client `ETH` (and filter) RPC.
pub struct EthClient<T> {
@ -168,7 +168,7 @@ impl<T: LightChainClient + 'static> EthClient<T> {
seal_fields: header.seal().into_iter().cloned().map(Into::into).collect(),
uncles: block.uncle_hashes().into_iter().map(Into::into).collect(),
transactions: match include_txs {
true => BlockTransactions::Full(block.view().localized_transactions().into_iter().map(|t| Transaction::from_localized(t)).collect()),
true => BlockTransactions::Full(block.view().localized_transactions().into_iter().map(Transaction::from_localized).collect()),
_ => BlockTransactions::Hashes(block.transaction_hashes().into_iter().map(Into::into).collect()),
},
extra_data: Bytes::new(header.extra_data().clone()),
@ -237,7 +237,7 @@ impl<T: LightChainClient + 'static> Eth for EthClient<T> {
let chain_info = self.client.chain_info();
let current_block = U256::from(chain_info.best_block_number);
let highest_block = self.sync.highest_block().map(U256::from)
.unwrap_or_else(|| current_block.clone());
.unwrap_or_else(|| current_block);
Ok(SyncStatus::Info(SyncInfo {
starting_block: U256::from(self.sync.start_block()).into(),