openethereum/ethcore/light/src/on_demand/mod.rs

575 lines
19 KiB
Rust
Raw Normal View History

// Copyright 2015-2017 Parity Technologies (UK) Ltd.
2016-12-27 16:43:28 +01:00
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! On-demand chain requests over LES. This is a major building block for RPCs.
//! The request service is implemented using Futures. Higher level request handlers
//! will take the raw data received here and extract meaningful results from it.
// TODO [ToDr] Suppressing deprecation warnings. Rob will fix the API anyway.
#![allow(deprecated)]
2016-12-27 16:43:28 +01:00
use std::collections::HashMap;
2017-02-16 20:46:59 +01:00
use std::sync::Arc;
2016-12-27 16:43:28 +01:00
2017-01-05 13:26:14 +01:00
use ethcore::basic_account::BasicAccount;
use ethcore::encoded;
2016-12-27 16:43:28 +01:00
use ethcore::receipt::Receipt;
use ethcore::state::ProvedExecution;
use ethcore::executed::{Executed, ExecutionError};
2016-12-27 16:43:28 +01:00
2016-12-28 16:20:46 +01:00
use futures::{Async, Poll, Future};
2017-02-07 17:06:22 +01:00
use futures::sync::oneshot::{self, Sender, Receiver};
2016-12-27 16:43:28 +01:00
use network::PeerId;
use rlp::RlpStream;
use util::{Bytes, RwLock, Mutex, U256, H256};
use util::sha3::{SHA3_NULL_RLP, SHA3_EMPTY_LIST_RLP};
2016-12-27 16:43:28 +01:00
use net::{Handler, Status, Capabilities, Announcement, EventContext, BasicContext, ReqId};
2017-02-16 20:46:59 +01:00
use cache::Cache;
2017-03-16 20:23:59 +01:00
use request::{self as basic_request, Request as NetworkRequest, Response as NetworkResponse};
pub mod request;
2016-12-27 16:43:28 +01:00
// relevant peer info.
struct Peer {
status: Status,
capabilities: Capabilities,
}
2017-03-16 20:23:59 +01:00
impl Peer {
// Whether a given peer can handle a specific request.
fn can_handle(&self, pending: &Pending) -> bool {
match *pending {
Pending::HeaderProof(ref req, _) =>
self.capabilities.serve_headers && self.status.head_num > req.num(),
Pending::HeaderByHash(_, _) => self.capabilities.serve_headers,
2017-03-16 20:23:59 +01:00
Pending::Block(ref req, _) =>
self.capabilities.serve_chain_since.as_ref().map_or(false, |x| *x >= req.header.number()),
Pending::BlockReceipts(ref req, _) =>
self.capabilities.serve_chain_since.as_ref().map_or(false, |x| *x >= req.0.number()),
Pending::Account(ref req, _) =>
self.capabilities.serve_state_since.as_ref().map_or(false, |x| *x >= req.header.number()),
Pending::Code(ref req, _) =>
self.capabilities.serve_state_since.as_ref().map_or(false, |x| *x >= req.block_id.1),
Pending::TxProof(ref req, _) =>
self.capabilities.serve_state_since.as_ref().map_or(false, |x| *x >= req.header.number()),
}
}
}
2017-02-16 20:46:59 +01:00
// Which portions of a CHT proof should be sent.
enum ChtProofSender {
2017-03-16 20:23:59 +01:00
Both(Sender<(H256, U256)>),
Hash(Sender<H256>),
2017-02-16 20:46:59 +01:00
ChainScore(Sender<U256>),
}
// Attempted request info and sender to put received value.
2017-01-03 19:13:40 +01:00
enum Pending {
2017-03-16 20:23:59 +01:00
HeaderProof(request::HeaderProof, ChtProofSender),
HeaderByHash(request::HeaderByHash, Sender<encoded::Header>),
2017-01-03 19:13:40 +01:00
Block(request::Body, Sender<encoded::Block>),
BlockReceipts(request::BlockReceipts, Sender<Vec<Receipt>>),
2017-03-16 20:23:59 +01:00
Account(request::Account, Sender<Option<BasicAccount>>),
2017-02-07 15:29:38 +01:00
Code(request::Code, Sender<Bytes>),
TxProof(request::TransactionProof, Sender<Result<Executed, ExecutionError>>),
2016-12-27 16:43:28 +01:00
}
2017-03-16 20:23:59 +01:00
impl Pending {
// Create a network request.
fn make_request(&self) -> NetworkRequest {
match *self {
Pending::HeaderByHash(ref req, _) => NetworkRequest::Headers(basic_request::IncompleteHeadersRequest {
start: basic_request::HashOrNumber::Hash(req.0).into(),
skip: 0,
max: 1,
reverse: false,
}),
Pending::HeaderProof(ref req, _) => NetworkRequest::HeaderProof(basic_request::IncompleteHeaderProofRequest {
num: req.num().into(),
}),
Pending::Block(ref req, _) => NetworkRequest::Body(basic_request::IncompleteBodyRequest {
hash: req.hash.into(),
}),
Pending::BlockReceipts(ref req, _) => NetworkRequest::Receipts(basic_request::IncompleteReceiptsRequest {
hash: req.0.hash().into(),
}),
Pending::Account(ref req, _) => NetworkRequest::Account(basic_request::IncompleteAccountRequest {
block_hash: req.header.hash().into(),
address_hash: ::util::Hashable::sha3(&req.address).into(),
}),
Pending::Code(ref req, _) => NetworkRequest::Code(basic_request::IncompleteCodeRequest {
block_hash: req.block_id.0.into(),
code_hash: req.code_hash.into(),
}),
Pending::TxProof(ref req, _) => NetworkRequest::Execution(basic_request::IncompleteExecutionRequest {
block_hash: req.header.hash().into(),
from: req.tx.sender(),
gas: req.tx.gas,
gas_price: req.tx.gas_price,
action: req.tx.action.clone(),
value: req.tx.value,
data: req.tx.data.clone(),
}),
}
}
}
2016-12-27 16:43:28 +01:00
/// On demand request service. See module docs for more details.
/// Accumulates info about all peers' capabilities and dispatches
/// requests to them accordingly.
pub struct OnDemand {
peers: RwLock<HashMap<PeerId, Peer>>,
2017-01-03 19:13:40 +01:00
pending_requests: RwLock<HashMap<ReqId, Pending>>,
2017-02-16 20:46:59 +01:00
cache: Arc<Mutex<Cache>>,
2017-02-07 16:13:56 +01:00
orphaned_requests: RwLock<Vec<Pending>>,
2016-12-27 16:43:28 +01:00
}
2017-03-16 12:48:51 +01:00
const RECEIVER_IN_SCOPE: &'static str = "Receiver is still in scope, so it's not dropped; qed";
2017-02-16 20:46:59 +01:00
impl OnDemand {
/// Create a new `OnDemand` service with the given cache.
pub fn new(cache: Arc<Mutex<Cache>>) -> Self {
2017-01-04 14:54:50 +01:00
OnDemand {
peers: RwLock::new(HashMap::new()),
pending_requests: RwLock::new(HashMap::new()),
2017-02-16 20:46:59 +01:00
cache: cache,
2017-02-07 16:13:56 +01:00
orphaned_requests: RwLock::new(Vec::new()),
2017-01-04 14:54:50 +01:00
}
}
2017-03-16 20:23:59 +01:00
/// Request a header's hash by block number and CHT root hash.
/// Returns the hash.
pub fn hash_by_number(&self, ctx: &BasicContext, req: request::HeaderProof) -> Receiver<H256> {
2017-02-16 20:46:59 +01:00
let (sender, receiver) = oneshot::channel();
let cached = {
let mut cache = self.cache.lock();
2017-03-16 20:23:59 +01:00
cache.block_hash(&req.num())
2017-02-16 20:46:59 +01:00
};
match cached {
Some(hash) => sender.send(hash).expect(RECEIVER_IN_SCOPE),
2017-03-16 20:23:59 +01:00
None => self.dispatch(ctx, Pending::HeaderProof(req, ChtProofSender::Hash(sender))),
2017-02-16 20:46:59 +01:00
}
receiver
}
/// Request a canonical block's chain score.
/// Returns the chain score.
2017-03-16 20:23:59 +01:00
pub fn chain_score_by_number(&self, ctx: &BasicContext, req: request::HeaderProof) -> Receiver<U256> {
2017-02-16 20:46:59 +01:00
let (sender, receiver) = oneshot::channel();
let cached = {
let mut cache = self.cache.lock();
cache.block_hash(&req.num()).and_then(|hash| cache.chain_score(&hash))
};
match cached {
2017-03-16 12:48:51 +01:00
Some(score) => sender.send(score).expect(RECEIVER_IN_SCOPE),
2017-03-16 20:23:59 +01:00
None => self.dispatch(ctx, Pending::HeaderProof(req, ChtProofSender::ChainScore(sender))),
2017-02-16 20:46:59 +01:00
}
receiver
}
2017-03-16 20:23:59 +01:00
/// Request a canonical block's hash and chain score by number.
/// Returns the hash and chain score.
pub fn hash_and_score_by_number(&self, ctx: &BasicContext, req: request::HeaderProof) -> Receiver<(H256, U256)> {
2016-12-27 16:43:28 +01:00
let (sender, receiver) = oneshot::channel();
2017-02-16 20:46:59 +01:00
let cached = {
let mut cache = self.cache.lock();
let hash = cache.block_hash(&req.num());
(
2017-03-16 20:23:59 +01:00
hash.clone(),
2017-02-16 20:46:59 +01:00
hash.and_then(|hash| cache.chain_score(&hash)),
)
};
match cached {
(Some(hash), Some(score)) => sender.send((hash, score)).expect(RECEIVER_IN_SCOPE),
2017-03-16 20:23:59 +01:00
_ => self.dispatch(ctx, Pending::HeaderProof(req, ChtProofSender::Both(sender))),
2017-02-16 20:46:59 +01:00
}
2017-02-07 17:06:22 +01:00
receiver
}
2016-12-27 16:43:28 +01:00
/// Request a header by hash. This is less accurate than by-number because we don't know
/// where in the chain this header lies, and therefore can't find a peer who is supposed to have
/// it as easily.
2017-02-07 17:06:22 +01:00
pub fn header_by_hash(&self, ctx: &BasicContext, req: request::HeaderByHash) -> Receiver<encoded::Header> {
2016-12-27 16:43:28 +01:00
let (sender, receiver) = oneshot::channel();
2017-02-16 20:46:59 +01:00
match self.cache.lock().block_header(&req.0) {
2017-03-16 12:48:51 +01:00
Some(hdr) => sender.send(hdr).expect(RECEIVER_IN_SCOPE),
2017-03-16 20:23:59 +01:00
None => self.dispatch(ctx, Pending::HeaderByHash(req, sender)),
2017-02-16 20:46:59 +01:00
}
2017-02-07 17:06:22 +01:00
receiver
}
2016-12-27 16:43:28 +01:00
/// Request a block, given its header. Block bodies are requestable by hash only,
/// and the header is required anyway to verify and complete the block body
/// -- this just doesn't obscure the network query.
2017-02-07 17:06:22 +01:00
pub fn block(&self, ctx: &BasicContext, req: request::Body) -> Receiver<encoded::Block> {
2016-12-27 16:43:28 +01:00
let (sender, receiver) = oneshot::channel();
// fast path for empty body.
if req.header.transactions_root() == SHA3_NULL_RLP && req.header.uncles_hash() == SHA3_EMPTY_LIST_RLP {
let mut stream = RlpStream::new_list(3);
stream.append_raw(&req.header.into_inner(), 1);
stream.begin_list(0);
stream.begin_list(0);
sender.send(encoded::Block::new(stream.out())).expect(RECEIVER_IN_SCOPE);
} else {
2017-02-16 20:46:59 +01:00
match self.cache.lock().block_body(&req.hash) {
Some(body) => {
let mut stream = RlpStream::new_list(3);
stream.append_raw(&req.header.into_inner(), 1);
stream.append_raw(&body.into_inner(), 2);
sender.send(encoded::Block::new(stream.out())).expect(RECEIVER_IN_SCOPE);
2017-02-16 20:46:59 +01:00
}
2017-03-16 20:23:59 +01:00
None => self.dispatch(ctx, Pending::Block(req, sender)),
2017-02-16 20:46:59 +01:00
}
}
2017-02-07 17:06:22 +01:00
receiver
}
2016-12-27 16:43:28 +01:00
/// Request the receipts for a block. The header serves two purposes:
/// provide the block hash to fetch receipts for, and for verification of the receipts root.
2017-02-07 17:06:22 +01:00
pub fn block_receipts(&self, ctx: &BasicContext, req: request::BlockReceipts) -> Receiver<Vec<Receipt>> {
2016-12-27 16:43:28 +01:00
let (sender, receiver) = oneshot::channel();
// fast path for empty receipts.
if req.0.receipts_root() == SHA3_NULL_RLP {
sender.send(Vec::new()).expect(RECEIVER_IN_SCOPE);
} else {
2017-02-16 20:46:59 +01:00
match self.cache.lock().block_receipts(&req.0.hash()) {
2017-03-16 12:48:51 +01:00
Some(receipts) => sender.send(receipts).expect(RECEIVER_IN_SCOPE),
2017-03-16 20:23:59 +01:00
None => self.dispatch(ctx, Pending::BlockReceipts(req, sender)),
2017-02-16 20:46:59 +01:00
}
}
2017-02-07 17:06:22 +01:00
receiver
}
2016-12-27 16:43:28 +01:00
/// Request an account by address and block header -- which gives a hash to query and a state root
/// to verify against.
2017-03-16 20:23:59 +01:00
pub fn account(&self, ctx: &BasicContext, req: request::Account) -> Receiver<Option<BasicAccount>> {
2016-12-27 16:43:28 +01:00
let (sender, receiver) = oneshot::channel();
2017-03-16 20:23:59 +01:00
self.dispatch(ctx, Pending::Account(req, sender));
2017-02-07 17:06:22 +01:00
receiver
}
2017-02-07 15:29:38 +01:00
/// Request code by address, known code hash, and block header.
2017-02-07 17:06:22 +01:00
pub fn code(&self, ctx: &BasicContext, req: request::Code) -> Receiver<Bytes> {
2017-02-07 15:29:38 +01:00
let (sender, receiver) = oneshot::channel();
// fast path for no code.
if req.code_hash == ::util::sha3::SHA3_EMPTY {
2017-03-16 12:48:51 +01:00
sender.send(Vec::new()).expect(RECEIVER_IN_SCOPE)
2017-02-07 15:29:38 +01:00
} else {
2017-03-16 20:23:59 +01:00
self.dispatch(ctx, Pending::Code(req, sender));
2017-02-07 15:29:38 +01:00
}
2017-02-07 17:06:22 +01:00
receiver
2017-02-07 15:29:38 +01:00
}
/// Request proof-of-execution for a transaction.
pub fn transaction_proof(&self, ctx: &BasicContext, req: request::TransactionProof) -> Receiver<Result<Executed, ExecutionError>> {
let (sender, receiver) = oneshot::channel();
2017-03-16 20:23:59 +01:00
self.dispatch(ctx, Pending::TxProof(req, sender));
receiver
}
2017-03-16 20:23:59 +01:00
// dispatch the request, with a "suitability" function to filter acceptable peers.
fn dispatch(&self, ctx: &BasicContext, pending: Pending) {
let mut builder = basic_request::RequestBuilder::default();
builder.push(pending.make_request())
.expect("make_request always returns fully complete request; qed");
let complete = builder.build();
for (id, peer) in self.peers.read().iter() {
2017-03-16 20:23:59 +01:00
if !peer.can_handle(&pending) { continue }
match ctx.request_from(*id, complete.clone()) {
Ok(req_id) => {
trace!(target: "on_demand", "Assigning request to peer {}", id);
self.pending_requests.write().insert(
req_id,
pending,
);
return
}
2017-03-16 20:23:59 +01:00
Err(e) =>
trace!(target: "on_demand", "Failed to make request of peer {}: {:?}", id, e),
}
}
trace!(target: "on_demand", "No suitable peer for request");
2017-03-16 20:23:59 +01:00
self.orphaned_requests.write().push(pending);
}
2017-03-16 20:23:59 +01:00
2017-02-07 16:49:14 +01:00
// dispatch orphaned requests, and discard those for which the corresponding
// receiver has been dropped.
fn dispatch_orphaned(&self, ctx: &BasicContext) {
// wrapper future for calling `poll_cancel` on our `Senders` to preserve
// the invariant that it's always within a task.
struct CheckHangup<'a, T: 'a>(&'a mut Sender<T>);
impl<'a, T: 'a> Future for CheckHangup<'a, T> {
type Item = bool;
type Error = ();
fn poll(&mut self) -> Poll<bool, ()> {
Ok(Async::Ready(match self.0.poll_cancel() {
Ok(Async::NotReady) => false, // hasn't hung up.
_ => true, // has hung up.
}))
}
}
// check whether a sender's hung up (using `wait` to preserve the task invariant)
// returns true if has hung up, false otherwise.
fn check_hangup<T>(send: &mut Sender<T>) -> bool {
CheckHangup(send).wait().expect("CheckHangup always returns ok; qed")
}
if self.orphaned_requests.read().is_empty() { return }
let to_dispatch = ::std::mem::replace(&mut *self.orphaned_requests.write(), Vec::new());
2017-03-16 20:23:59 +01:00
for mut orphaned in to_dispatch {
let hung_up = match orphaned {
Pending::HeaderProof(_, ref mut sender) => match *sender {
2017-02-16 20:46:59 +01:00
ChtProofSender::Both(ref mut s) => check_hangup(s),
2017-03-16 20:23:59 +01:00
ChtProofSender::Hash(ref mut s) => check_hangup(s),
2017-02-16 20:46:59 +01:00
ChtProofSender::ChainScore(ref mut s) => check_hangup(s),
2017-03-16 20:23:59 +01:00
},
Pending::HeaderByHash(_, ref mut sender) => check_hangup(sender),
Pending::Block(_, ref mut sender) => check_hangup(sender),
Pending::BlockReceipts(_, ref mut sender) => check_hangup(sender),
Pending::Account(_, ref mut sender) => check_hangup(sender),
Pending::Code(_, ref mut sender) => check_hangup(sender),
Pending::TxProof(_, ref mut sender) => check_hangup(sender),
};
if !hung_up { self.dispatch(ctx, orphaned) }
2017-02-07 16:49:14 +01:00
}
2017-02-07 15:29:38 +01:00
}
2016-12-27 16:43:28 +01:00
}
impl Handler for OnDemand {
fn on_connect(&self, ctx: &EventContext, status: &Status, capabilities: &Capabilities) {
self.peers.write().insert(ctx.peer(), Peer { status: status.clone(), capabilities: capabilities.clone() });
2017-02-07 16:49:14 +01:00
self.dispatch_orphaned(ctx.as_basic());
}
fn on_disconnect(&self, ctx: &EventContext, unfulfilled: &[ReqId]) {
self.peers.write().remove(&ctx.peer());
let ctx = ctx.as_basic();
2017-02-07 16:49:14 +01:00
{
let mut orphaned = self.orphaned_requests.write();
for unfulfilled in unfulfilled {
if let Some(pending) = self.pending_requests.write().remove(unfulfilled) {
trace!(target: "on_demand", "Attempting to reassign dropped request");
orphaned.push(pending);
}
}
}
2017-02-07 16:49:14 +01:00
self.dispatch_orphaned(ctx);
}
fn on_announcement(&self, ctx: &EventContext, announcement: &Announcement) {
let mut peers = self.peers.write();
if let Some(ref mut peer) = peers.get_mut(&ctx.peer()) {
peer.status.update_from(&announcement);
peer.capabilities.update_from(&announcement);
}
2017-02-07 16:49:14 +01:00
self.dispatch_orphaned(ctx.as_basic());
}
2017-03-16 20:23:59 +01:00
fn on_responses(&self, ctx: &EventContext, req_id: ReqId, responses: &[basic_request::Response]) {
let peer = ctx.peer();
let req = match self.pending_requests.write().remove(&req_id) {
Some(req) => req,
None => return,
};
2017-03-16 20:23:59 +01:00
let response = match responses.get(0) {
Some(response) => response,
None => {
trace!(target: "on_demand", "Ignoring empty response for request {}", req_id);
self.dispatch(ctx.as_basic(), req);
return;
}
};
// handle the response appropriately for the request.
// all branches which do not return early lead to disabling of the peer
// due to misbehavior.
match req {
2017-03-16 20:23:59 +01:00
Pending::HeaderProof(req, sender) => {
if let NetworkResponse::HeaderProof(ref response) = *response {
match req.check_response(&response.proof) {
Ok((hash, score)) => {
2017-02-16 20:46:59 +01:00
let mut cache = self.cache.lock();
2017-03-16 20:23:59 +01:00
cache.insert_block_hash(req.num(), hash);
2017-02-16 20:46:59 +01:00
cache.insert_chain_score(hash, score);
match sender {
ChtProofSender::Both(sender) => { let _ = sender.send((hash, score)); }
ChtProofSender::Hash(sender) => { let _ = sender.send(hash); }
ChtProofSender::ChainScore(sender) => { let _ = sender.send(score); }
2017-02-16 20:46:59 +01:00
}
2017-01-04 13:34:50 +01:00
return
}
2017-03-16 20:23:59 +01:00
Err(e) => warn!("Error handling response for header request: {:?}", e),
}
2017-01-04 13:34:50 +01:00
}
}
2017-01-04 13:34:50 +01:00
Pending::HeaderByHash(req, sender) => {
2017-03-16 20:23:59 +01:00
if let NetworkResponse::Headers(ref response) = *response {
if let Some(header) = response.headers.get(0) {
match req.check_response(header) {
Ok(header) => {
self.cache.lock().insert_block_header(req.0, header.clone());
let _ = sender.send(header);
2017-03-16 20:23:59 +01:00
return
}
Err(e) => warn!("Error handling response for header request: {:?}", e),
2017-01-04 13:34:50 +01:00
}
}
}
}
Pending::Block(req, sender) => {
2017-03-16 20:23:59 +01:00
if let NetworkResponse::Body(ref response) = *response {
match req.check_response(&response.body) {
2017-01-04 13:34:50 +01:00
Ok(block) => {
2017-03-16 20:23:59 +01:00
self.cache.lock().insert_block_body(req.hash, response.body.clone());
let _ = sender.send(block);
2017-01-04 13:34:50 +01:00
return
}
2017-03-16 20:23:59 +01:00
Err(e) => warn!("Error handling response for block request: {:?}", e),
2017-01-04 13:34:50 +01:00
}
}
}
Pending::BlockReceipts(req, sender) => {
2017-03-16 20:23:59 +01:00
if let NetworkResponse::Receipts(ref response) = *response {
match req.check_response(&response.receipts) {
2017-01-04 13:34:50 +01:00
Ok(receipts) => {
2017-02-16 20:46:59 +01:00
let hash = req.0.hash();
self.cache.lock().insert_block_receipts(hash, receipts.clone());
let _ = sender.send(receipts);
2017-01-04 13:34:50 +01:00
return
}
2017-03-16 20:23:59 +01:00
Err(e) => warn!("Error handling response for receipts request: {:?}", e),
2017-01-04 13:34:50 +01:00
}
}
}
Pending::Account(req, sender) => {
2017-03-16 20:23:59 +01:00
if let NetworkResponse::Account(ref response) = *response {
match req.check_response(&response.proof) {
Ok(maybe_account) => {
// TODO: validate against request outputs.
// needs engine + env info as part of request.
let _ = sender.send(maybe_account);
2017-01-04 13:34:50 +01:00
return
}
2017-03-16 20:23:59 +01:00
Err(e) => warn!("Error handling response for state request: {:?}", e),
2017-01-04 13:34:50 +01:00
}
}
}
2017-02-07 15:29:38 +01:00
Pending::Code(req, sender) => {
2017-03-16 20:23:59 +01:00
if let NetworkResponse::Code(ref response) = *response {
match req.check_response(response.code.as_slice()) {
2017-02-07 15:29:38 +01:00
Ok(()) => {
let _ = sender.send(response.code.clone());
2017-02-07 15:29:38 +01:00
return
}
2017-03-16 20:23:59 +01:00
Err(e) => warn!("Error handling response for code request: {:?}", e),
2017-02-07 15:29:38 +01:00
}
}
}
Pending::TxProof(req, sender) => {
2017-03-16 20:23:59 +01:00
if let NetworkResponse::Execution(ref response) = *response {
match req.check_response(&response.items) {
ProvedExecution::Complete(executed) => {
let _ = sender.send(Ok(executed));
2017-03-16 20:23:59 +01:00
return
}
ProvedExecution::Failed(err) => {
let _ = sender.send(Err(err));
2017-03-16 20:23:59 +01:00
return
}
ProvedExecution::BadProof => warn!("Error handling response for transaction proof request"),
}
}
}
}
2017-03-16 20:23:59 +01:00
ctx.disable_peer(peer);
}
2017-02-07 16:49:14 +01:00
fn tick(&self, ctx: &BasicContext) {
self.dispatch_orphaned(ctx)
}
}
2017-01-04 14:54:50 +01:00
#[cfg(test)]
mod tests {
use super::*;
2017-02-16 20:46:59 +01:00
use std::sync::Arc;
use cache::Cache;
2017-01-04 16:12:58 +01:00
use net::{Announcement, BasicContext, ReqId, Error as LesError};
2017-03-16 20:33:45 +01:00
use request::Requests;
2017-02-16 20:46:59 +01:00
2017-01-04 14:54:50 +01:00
use network::{PeerId, NodeId};
2017-02-16 20:46:59 +01:00
use time::Duration;
use util::{H256, Mutex};
2017-01-04 14:54:50 +01:00
struct FakeContext;
impl BasicContext for FakeContext {
fn persistent_peer_id(&self, _: PeerId) -> Option<NodeId> { None }
2017-03-16 20:33:45 +01:00
fn request_from(&self, _: PeerId, _: Requests) -> Result<ReqId, LesError> {
2017-01-04 14:54:50 +01:00
unimplemented!()
}
fn make_announcement(&self, _: Announcement) { }
fn disconnect_peer(&self, _: PeerId) { }
fn disable_peer(&self, _: PeerId) { }
}
#[test]
2017-02-07 17:06:22 +01:00
fn detects_hangup() {
2017-02-16 20:46:59 +01:00
let cache = Arc::new(Mutex::new(Cache::new(Default::default(), Duration::hours(6))));
let on_demand = OnDemand::new(cache);
2017-01-04 14:54:50 +01:00
let result = on_demand.header_by_hash(&FakeContext, request::HeaderByHash(H256::default()));
2017-02-07 17:06:22 +01:00
assert!(on_demand.orphaned_requests.read().len() == 1);
drop(result);
on_demand.dispatch_orphaned(&FakeContext);
assert!(on_demand.orphaned_requests.read().is_empty());
2017-01-04 14:54:50 +01:00
}
}