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

View File

@ -118,8 +118,8 @@ pub fn build<F>(cht_num: u64, mut fetcher: F) -> Option<CHT<MemoryDB<KeccakHash
} }
Some(CHT { Some(CHT {
db: db, db,
root: root, root,
number: cht_num, number: cht_num,
}) })
} }

View File

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

View File

@ -176,7 +176,7 @@ impl<T: ChainDataFetcher> Client<T> {
io_channel: IoChannel<ClientIoMessage>, io_channel: IoChannel<ClientIoMessage>,
cache: Arc<Mutex<Cache>> cache: Arc<Mutex<Cache>>
) -> Result<Self, Error> { ) -> Result<Self, Error> {
Ok(Client { Ok(Self {
queue: HeaderQueue::new(config.queue, spec.engine.clone(), io_channel, config.check_seal), queue: HeaderQueue::new(config.queue, spec.engine.clone(), io_channel, config.check_seal),
engine: spec.engine.clone(), engine: spec.engine.clone(),
chain: { chain: {
@ -185,9 +185,9 @@ impl<T: ChainDataFetcher> Client<T> {
}, },
report: RwLock::new(ClientReport::default()), report: RwLock::new(ClientReport::default()),
import_lock: Mutex::new(()), import_lock: Mutex::new(()),
db: db, db,
listeners: RwLock::new(vec![]), listeners: RwLock::new(vec![]),
fetcher: fetcher, fetcher,
verify_full: config.verify_full, verify_full: config.verify_full,
}) })
} }
@ -229,7 +229,7 @@ impl<T: ChainDataFetcher> Client<T> {
BlockChainInfo { BlockChainInfo {
total_difficulty: best_td, total_difficulty: best_td,
pending_total_difficulty: best_td + self.queue.total_difficulty(), pending_total_difficulty: best_td + self.queue.total_difficulty(),
genesis_hash: genesis_hash, genesis_hash,
best_block_hash: best_hdr.hash(), best_block_hash: best_hdr.hash(),
best_block_number: best_hdr.number(), best_block_number: best_hdr.number(),
best_block_timestamp: best_hdr.timestamp(), best_block_timestamp: best_hdr.timestamp(),
@ -320,7 +320,7 @@ impl<T: ChainDataFetcher> Client<T> {
); );
let mut tx = self.db.transaction(); 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) => { Ok(pending) => {
good.push(hash); good.push(hash);
self.report.write().blocks_imported += 1; self.report.write().blocks_imported += 1;
@ -511,8 +511,8 @@ impl<T: ChainDataFetcher> Client<T> {
}; };
let mut batch = self.db.transaction(); let mut batch = self.db.transaction();
self.chain.insert_pending_transition(&mut batch, header.hash(), epoch::PendingTransition { self.chain.insert_pending_transition(&mut batch, header.hash(), &epoch::PendingTransition {
proof: proof, proof,
}); });
self.db.write_buffered(batch); self.db.write_buffered(batch);
Ok(()) 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 { self.chain.epoch_transition_for(parent_hash).map(|(hdr, proof)| EpochTransition {
block_hash: hdr.hash(), block_hash: hdr.hash(),
block_number: hdr.number(), 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 _); spec.engine.register_client(Arc::downgrade(&client) as _);
Ok(Service { Ok(Service {
client: client, client,
io_service: io_service, 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> { 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) { 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> { 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) { fn make_announcement(&self, announcement: Announcement) {

View File

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

View File

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

View File

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

View File

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

View File

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

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

View File

@ -224,7 +224,7 @@ impl HeaderRef {
fn field(&self) -> Field<H256> { fn field(&self) -> Field<H256> {
match *self { match *self {
HeaderRef::Stored(ref hdr) => Field::Scalar(hdr.hash()), 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>)> { fn needs_header(&self) -> Option<(usize, Field<H256>)> {
match *self { match *self {
HeaderRef::Stored(_) => None, 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) => { Request::TransactionIndex(req) => {
let net_req = net_request::IncompleteTransactionIndexRequest { let net_req = net_request::IncompleteTransactionIndexRequest {
hash: req.0.clone(), hash: req.0,
}; };
trace!(target: "on_demand", "TransactionIndex Request, {:?}", net_req); trace!(target: "on_demand", "TransactionIndex Request, {:?}", net_req);
CheckedRequest::TransactionIndex(req, net_req) CheckedRequest::TransactionIndex(req, net_req)
@ -322,7 +322,7 @@ impl From<Request> for CheckedRequest {
Request::Code(req) => { Request::Code(req) => {
let net_req = net_request::IncompleteCodeRequest { let net_req = net_request::IncompleteCodeRequest {
block_hash: req.header.field(), block_hash: req.header.field(),
code_hash: req.code_hash.into(), code_hash: req.code_hash,
}; };
trace!(target: "on_demand", "Code Request, {:?}", net_req); trace!(target: "on_demand", "Code Request, {:?}", net_req);
CheckedRequest::Code(req, net_req) CheckedRequest::Code(req, net_req)
@ -404,7 +404,7 @@ impl CheckedRequest {
match *self { match *self {
CheckedRequest::HeaderProof(ref check, _) => { CheckedRequest::HeaderProof(ref check, _) => {
let mut cache = cache.lock(); 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))) .and_then(|h| cache.chain_score(&h).map(|s| (h, s)))
.map(|(h, s)| Response::HeaderProof((h, s))) .map(|(h, s)| Response::HeaderProof((h, s)))
} }
@ -448,7 +448,7 @@ impl CheckedRequest {
} }
CheckedRequest::Body(ref check, ref req) => { CheckedRequest::Body(ref check, ref req) => {
// check for empty body. // 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 { if hdr.transactions_root() == KECCAK_NULL_RLP && hdr.uncles_hash() == KECCAK_EMPTY_LIST_RLP {
let mut stream = RlpStream::new_list(3); let mut stream = RlpStream::new_list(3);
stream.append_raw(hdr.rlp().as_raw(), 1); stream.append_raw(hdr.rlp().as_raw(), 1);
@ -769,9 +769,9 @@ impl HeaderProof {
/// Provide the expected CHT root to compare against. /// Provide the expected CHT root to compare against.
pub fn new(num: u64, cht_root: H256) -> Option<Self> { pub fn new(num: u64, cht_root: H256) -> Option<Self> {
::cht::block_to_cht_number(num).map(|cht_num| HeaderProof { ::cht::block_to_cht_number(num).map(|cht_num| HeaderProof {
num: num, num,
cht_num: cht_num, cht_num,
cht_root: cht_root, cht_root,
}) })
} }
@ -817,9 +817,9 @@ impl HeaderWithAncestors {
headers: &[encoded::Header] headers: &[encoded::Header]
) -> Result<Vec<encoded::Header>, Error> { ) -> Result<Vec<encoded::Header>, Error> {
let expected_hash = match (self.block_hash, start) { let expected_hash = match (self.block_hash, start) {
(Field::Scalar(ref h), &net_request::HashOrNumber::Hash(ref h2)) => { (Field::Scalar(h), &net_request::HashOrNumber::Hash(h2)) => {
if h != h2 { return Err(Error::WrongHash(*h, *h2)) } if h != h2 { return Err(Error::WrongHash(h, h2)) }
*h h
} }
(_, &net_request::HashOrNumber::Hash(h2)) => h2, (_, &net_request::HashOrNumber::Hash(h2)) => h2,
_ => return Err(Error::HeaderByNumber), _ => return Err(Error::HeaderByNumber),
@ -871,9 +871,9 @@ impl HeaderByHash {
headers: &[encoded::Header] headers: &[encoded::Header]
) -> Result<encoded::Header, Error> { ) -> Result<encoded::Header, Error> {
let expected_hash = match (self.0, start) { let expected_hash = match (self.0, start) {
(Field::Scalar(ref h), &net_request::HashOrNumber::Hash(ref h2)) => { (Field::Scalar(h), &net_request::HashOrNumber::Hash(h2)) => {
if h != h2 { return Err(Error::WrongHash(*h, *h2)) } if h != h2 { return Err(Error::WrongHash(h, h2)) }
*h h
} }
(_, &net_request::HashOrNumber::Hash(h2)) => h2, (_, &net_request::HashOrNumber::Hash(h2)) => h2,
_ => return Err(Error::HeaderByNumber), _ => return Err(Error::HeaderByNumber),
@ -881,12 +881,11 @@ impl HeaderByHash {
let header = headers.get(0).ok_or(Error::Empty)?; let header = headers.get(0).ok_or(Error::Empty)?;
let hash = header.hash(); let hash = header.hash();
match hash == expected_hash { if hash == expected_hash {
true => {
cache.lock().insert_block_header(hash, header.clone()); cache.lock().insert_block_header(hash, header.clone());
Ok(header.clone()) Ok(header.clone())
} } else {
false => Err(Error::WrongHash(expected_hash, hash)), Err(Error::WrongHash(expected_hash, hash))
} }
} }
} }
@ -957,18 +956,15 @@ impl BlockReceipts {
let receipts_root = self.0.as_ref()?.receipts_root(); let receipts_root = self.0.as_ref()?.receipts_root();
let found_root = ::triehash::ordered_trie_root(receipts.iter().map(|r| ::rlp::encode(r))); let found_root = ::triehash::ordered_trie_root(receipts.iter().map(|r| ::rlp::encode(r)));
match receipts_root == found_root { if receipts_root == found_root {
true => {
cache.lock().insert_block_receipts(receipts_root, receipts.to_vec()); cache.lock().insert_block_receipts(receipts_root, receipts.to_vec());
Ok(receipts.to_vec()) Ok(receipts.to_vec())
} } else {
false => {
trace!(target: "on_demand", "Receipt Reponse: \"WrongTrieRoot\" receipts_root: {:?} found_root: {:?}", receipts_root, found_root); trace!(target: "on_demand", "Receipt Reponse: \"WrongTrieRoot\" receipts_root: {:?} found_root: {:?}", receipts_root, found_root);
Err(Error::WrongTrieRoot(receipts_root, found_root)) Err(Error::WrongTrieRoot(receipts_root, found_root))
} }
} }
} }
}
/// Request for an account structure. /// Request for an account structure.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
@ -1052,7 +1048,7 @@ impl TransactionProof {
let root = self.header.as_ref()?.state_root(); let root = self.header.as_ref()?.state_root();
let mut env_info = self.env_info.clone(); 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( let proved_execution = state::check_proof(
state_items, 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 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))) .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| if req.reverse { start_num.saturating_sub(x) } else { start_num.saturating_add(x) })
.map(|x| self.block_header(BlockId::Number(x))) .map(|x| self.block_header(BlockId::Number(x)))
.take_while(|x| x.is_some()) .take_while(|x| x.is_some())
@ -99,7 +99,7 @@ pub trait Provider: Send + Sync {
if headers.is_empty() { if headers.is_empty() {
None None
} else { } 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> { fn block_body(&self, req: request::CompleteBodyRequest) -> Option<request::BodyResponse> {
BlockChainClient::block_body(self, BlockId::Hash(req.hash)) 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> { 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> { fn account_proof(&self, req: request::CompleteAccountRequest) -> Option<request::AccountResponse> {
self.prove_account(req.address_hash, BlockId::Hash(req.block_hash)).map(|(proof, acc)| { self.prove_account(req.address_hash, BlockId::Hash(req.block_hash)).map(|(proof, acc)| {
::request::AccountResponse { ::request::AccountResponse {
proof: proof, proof,
nonce: acc.nonce, nonce: acc.nonce,
balance: acc.balance, balance: acc.balance,
code_hash: acc.code_hash, 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> { 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) | { self.prove_storage(req.address_hash, req.key_hash, BlockId::Hash(req.block_hash)).map(|(proof, item) | {
::request::StorageResponse { ::request::StorageResponse {
proof: proof, proof,
value: item, value: item,
} }
}) })
@ -203,7 +203,7 @@ impl<T: ProvingBlockChainClient + ?Sized> Provider for T {
fn contract_code(&self, req: request::CompleteCodeRequest) -> Option<request::CodeResponse> { fn contract_code(&self, req: request::CompleteCodeRequest) -> Option<request::CodeResponse> {
self.state_data(&req.code_hash) 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> { fn header_proof(&self, req: request::CompleteHeaderProofRequest) -> Option<request::HeaderProofResponse> {
@ -252,7 +252,7 @@ impl<T: ProvingBlockChainClient + ?Sized> Provider for T {
// prove our result. // prove our result.
match cht.prove(req.num, 0) { match cht.prove(req.num, 0) {
Ok(Some(proof)) => Some(::request::HeaderProofResponse { Ok(Some(proof)) => Some(::request::HeaderProofResponse {
proof: proof, proof,
hash: needed_hdr.hash(), hash: needed_hdr.hash(),
td: needed_td, td: needed_td,
}), }),
@ -268,12 +268,12 @@ impl<T: ProvingBlockChainClient + ?Sized> Provider for T {
use transaction::Transaction; use transaction::Transaction;
let id = BlockId::Hash(req.block_hash); 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, Some(nonce) => nonce,
None => return None, None => return None,
}; };
let transaction = Transaction { let transaction = Transaction {
nonce: nonce, nonce,
gas: req.gas, gas: req.gas,
gas_price: req.gas_price, gas_price: req.gas_price,
action: req.action, action: req.action,
@ -294,7 +294,7 @@ impl<T: ProvingBlockChainClient + ?Sized> Provider for T {
fn epoch_signal(&self, req: request::CompleteSignalRequest) -> Option<request::SignalResponse> { fn epoch_signal(&self, req: request::CompleteSignalRequest) -> Option<request::SignalResponse> {
self.epoch_signal(req.block_hash).map(|signal| 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. /// Create a new `LightProvider` from the given client and transaction queue.
pub fn new(client: Arc<L>, txqueue: Arc<RwLock<TransactionQueue>>) -> Self { pub fn new(client: Arc<L>, txqueue: Arc<RwLock<TransactionQueue>>) -> Self {
LightProvider { LightProvider {
client: client, client,
txqueue: txqueue, txqueue,
} }
} }
} }

View File

@ -74,7 +74,7 @@ impl<'a> From<&'a PendingTransaction> for TransactionInfo {
fn from(tx: &'a PendingTransaction) -> Self { fn from(tx: &'a PendingTransaction) -> Self {
TransactionInfo { TransactionInfo {
hash: tx.hash(), hash: tx.hash(),
nonce: tx.nonce.clone(), nonce: tx.nonce,
condition: tx.condition.clone(), condition: tx.condition.clone(),
} }
} }
@ -104,15 +104,9 @@ impl AccountTransactions {
let mut promoted = Vec::new(); let mut promoted = Vec::new();
let mut next_nonce = self.next_nonce(); let mut next_nonce = self.next_nonce();
loop { while let Some(tx) = self.future.remove(&next_nonce) {
match self.future.remove(&next_nonce) {
Some(tx) => {
promoted.push(tx.hash); promoted.push(tx.hash);
self.current.push(tx) self.current.push(tx);
},
None => break,
}
next_nonce = next_nonce + 1; next_nonce = next_nonce + 1;
} }
@ -174,7 +168,7 @@ impl TransactionQueue {
} }
Entry::Occupied(mut entry) => { Entry::Occupied(mut entry) => {
let acct_txs = entry.get_mut(); 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. // don't accept txs from before known current nonce.
if acct_txs.cur_nonce.is_known() { if acct_txs.cur_nonce.is_known() {
return Err(transaction::Error::Old) return Err(transaction::Error::Old)

View File

@ -764,9 +764,7 @@ pub mod header {
headers.push(encoded::Header::new(item.as_raw().to_owned())); headers.push(encoded::Header::new(item.as_raw().to_owned()));
} }
Ok(Response { Ok(Response { headers })
headers: headers,
})
} }
} }
@ -814,7 +812,7 @@ pub mod header_proof {
fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> { fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> {
if let Field::BackReference(req, idx) = self.num { if let Field::BackReference(req, idx) = self.num {
self.num = match oracle(req, idx) { 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), _ => 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> { fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> {
if let Field::BackReference(req, idx) = self.hash { if let Field::BackReference(req, idx) = self.hash {
self.hash = match oracle(req, idx) { 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), _ => 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> { fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> {
if let Field::BackReference(req, idx) = self.block_hash { if let Field::BackReference(req, idx) = self.block_hash {
self.block_hash = match oracle(req, idx) { 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), _ => Field::BackReference(req, idx),
} }
} }
if let Field::BackReference(req, idx) = self.address_hash { if let Field::BackReference(req, idx) = self.address_hash {
self.address_hash = match oracle(req, idx) { 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), _ => 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> { fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> {
if let Field::BackReference(req, idx) = self.block_hash { if let Field::BackReference(req, idx) = self.block_hash {
self.block_hash = match oracle(req, idx) { 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), _ => Field::BackReference(req, idx),
} }
} }
if let Field::BackReference(req, idx) = self.address_hash { if let Field::BackReference(req, idx) = self.address_hash {
self.address_hash = match oracle(req, idx) { 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), _ => Field::BackReference(req, idx),
} }
} }
if let Field::BackReference(req, idx) = self.key_hash { if let Field::BackReference(req, idx) = self.key_hash {
self.key_hash = match oracle(req, idx) { 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), _ => 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> { fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> {
if let Field::BackReference(req, idx) = self.block_hash { if let Field::BackReference(req, idx) = self.block_hash {
self.block_hash = match oracle(req, idx) { 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), _ => Field::BackReference(req, idx),
} }
} }
if let Field::BackReference(req, idx) = self.code_hash { if let Field::BackReference(req, idx) = self.code_hash {
self.code_hash = match oracle(req, idx) { 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), _ => 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> { fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> {
if let Field::BackReference(req, idx) = self.block_hash { if let Field::BackReference(req, idx) = self.block_hash {
self.block_hash = match oracle(req, idx) { 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), _ => Field::BackReference(req, idx),
} }
} }
@ -1514,9 +1512,7 @@ pub mod execution {
items.push(item); items.push(item);
} }
Ok(Response { Ok(Response { items })
items: items,
})
} }
} }
@ -1578,7 +1574,7 @@ pub mod epoch_signal {
fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> { fn fill<F>(&mut self, oracle: F) where F: Fn(usize, usize) -> Result<Output, NoSuchOutput> {
if let Field::BackReference(req, idx) = self.block_hash { if let Field::BackReference(req, idx) = self.block_hash {
self.block_hash = match oracle(req, idx) { 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), _ => Field::BackReference(req, idx),
} }
} }

View File

@ -362,7 +362,7 @@ impl SyncProvider for EthSync {
remote_address: session_info.remote_address, remote_address: session_info.remote_address,
local_address: session_info.local_address, local_address: session_info.local_address,
eth_info: eth_sync.peer_info(&peer_id), 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() }).collect()
}).unwrap_or_else(Vec::new) }).unwrap_or_else(Vec::new)
@ -922,7 +922,7 @@ impl LightSyncProvider for LightSync {
remote_address: session_info.remote_address, remote_address: session_info.remote_address,
local_address: session_info.local_address, local_address: session_info.local_address,
eth_info: None, 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() }).collect()
}).unwrap_or_else(Vec::new) }).unwrap_or_else(Vec::new)

View File

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

View File

@ -164,7 +164,7 @@ impl PeerLike for Peer {
fn on_connect(&self, other: PeerId) { fn on_connect(&self, other: PeerId) {
let io = self.io(Some(other)); let io = self.io(Some(other));
self.proto.on_connect(&other, &io); self.proto.on_connect(other, &io);
} }
fn on_disconnect(&self, other: PeerId){ fn on_disconnect(&self, other: PeerId){
@ -174,7 +174,7 @@ impl PeerLike for Peer {
fn receive_message(&self, from: PeerId, msg: TestPacket) -> HashSet<PeerId> { fn receive_message(&self, from: PeerId, msg: TestPacket) -> HashSet<PeerId> {
let io = self.io(Some(from)); 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() 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)>>()) .flat_map(|(hash, r)| r.logs.into_iter().map(|l| (hash.clone(), l)).collect::<Vec<(H256, LogEntry)>>())
.collect::<Vec<(H256, LogEntry)>>(); .collect::<Vec<(H256, LogEntry)>>();
let result = pending_logs.into_iter() pending_logs.into_iter()
.filter(|pair| filter.matches(&pair.1)) .filter(|pair| filter.matches(&pair.1))
.map(|pair| { .map(|pair| {
let mut log = Log::from(pair.1); let mut log = Log::from(pair.1);
log.transaction_hash = Some(pair.0.into()); log.transaction_hash = Some(pair.0.into());
log log
}) })
.collect(); .collect()
result
} }
fn check_known<C>(client: &C, number: BlockNumber) -> Result<()> where C: BlockChainClient { 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; 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. /// Light client `ETH` (and filter) RPC.
pub struct EthClient<T> { 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(), seal_fields: header.seal().into_iter().cloned().map(Into::into).collect(),
uncles: block.uncle_hashes().into_iter().map(Into::into).collect(), uncles: block.uncle_hashes().into_iter().map(Into::into).collect(),
transactions: match include_txs { 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()), _ => BlockTransactions::Hashes(block.transaction_hashes().into_iter().map(Into::into).collect()),
}, },
extra_data: Bytes::new(header.extra_data().clone()), 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 chain_info = self.client.chain_info();
let current_block = U256::from(chain_info.best_block_number); let current_block = U256::from(chain_info.best_block_number);
let highest_block = self.sync.highest_block().map(U256::from) 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 { Ok(SyncStatus::Info(SyncInfo {
starting_block: U256::from(self.sync.start_block()).into(), starting_block: U256::from(self.sync.start_block()).into(),