fix(rpc): fix a bunch of clippy lints (#10493)

* fix(rpc): fix a bunch of clippy lints

* fix(rpc clippy): remove unused ignored lints

* fix(clippy): fix all redundant_field_names

This commit fixes all uses of `redundant_field_names` and removes the ignored lint `redundant_field_names`

* fix(brain unwrap): replace with expect
This commit is contained in:
Niklas Adolfsson 2019-03-22 12:01:11 +01:00 committed by Hernando Castano
parent f2c34f7ca2
commit 17042e9c32
53 changed files with 472 additions and 491 deletions

View File

@ -283,7 +283,7 @@ impl FullDependencies {
handler.extend_with(DebugClient::new(self.client.clone()).to_delegate()); handler.extend_with(DebugClient::new(self.client.clone()).to_delegate());
} }
Api::Web3 => { Api::Web3 => {
handler.extend_with(Web3Client::new().to_delegate()); handler.extend_with(Web3Client::default().to_delegate());
} }
Api::Net => { Api::Net => {
handler.extend_with(NetClient::new(&self.sync).to_delegate()); handler.extend_with(NetClient::new(&self.sync).to_delegate());
@ -529,7 +529,7 @@ impl<C: LightChainClient + 'static> LightDependencies<C> {
warn!(target: "rpc", "Debug API is not available in light client mode.") warn!(target: "rpc", "Debug API is not available in light client mode.")
} }
Api::Web3 => { Api::Web3 => {
handler.extend_with(Web3Client::new().to_delegate()); handler.extend_with(Web3Client::default().to_delegate());
} }
Api::Net => { Api::Net => {
handler.extend_with(light::NetClient::new(self.sync.clone()).to_delegate()); handler.extend_with(light::NetClient::new(self.sync.clone()).to_delegate());

View File

@ -51,7 +51,7 @@ const TIME_THRESHOLD: u64 = 7;
/// minimal length of hash /// minimal length of hash
const TOKEN_LENGTH: usize = 16; const TOKEN_LENGTH: usize = 16;
/// Separator between fields in serialized tokens file. /// Separator between fields in serialized tokens file.
const SEPARATOR: &'static str = ";"; const SEPARATOR: &str = ";";
/// Number of seconds to keep unused tokens. /// Number of seconds to keep unused tokens.
const UNUSED_TOKEN_TIMEOUT: u64 = 3600 * 24; // a day const UNUSED_TOKEN_TIMEOUT: u64 = 3600 * 24; // a day
@ -115,7 +115,7 @@ impl AuthCodes<DefaultTimeProvider> {
}) })
.collect(); .collect();
Ok(AuthCodes { Ok(AuthCodes {
codes: codes, codes,
now: time_provider, now: time_provider,
}) })
} }
@ -128,7 +128,7 @@ impl<T: TimeProvider> AuthCodes<T> {
pub fn to_file(&self, file: &Path) -> io::Result<()> { pub fn to_file(&self, file: &Path) -> io::Result<()> {
let mut file = fs::File::create(file)?; let mut file = fs::File::create(file)?;
let content = self.codes.iter().map(|code| { let content = self.codes.iter().map(|code| {
let mut data = vec![code.code.clone(), encode_time(code.created_at.clone())]; let mut data = vec![code.code.clone(), encode_time(code.created_at)];
if let Some(used_at) = code.last_used_at { if let Some(used_at) = code.last_used_at {
data.push(encode_time(used_at)); data.push(encode_time(used_at));
} }
@ -141,11 +141,11 @@ impl<T: TimeProvider> AuthCodes<T> {
pub fn new(codes: Vec<String>, now: T) -> Self { pub fn new(codes: Vec<String>, now: T) -> Self {
AuthCodes { AuthCodes {
codes: codes.into_iter().map(|code| Code { codes: codes.into_iter().map(|code| Code {
code: code, code,
created_at: time::Duration::from_secs(now.now()), created_at: time::Duration::from_secs(now.now()),
last_used_at: None, last_used_at: None,
}).collect(), }).collect(),
now: now, now,
} }
} }
@ -183,7 +183,7 @@ impl<T: TimeProvider> AuthCodes<T> {
.join("-"); .join("-");
trace!(target: "signer", "New authentication token generated."); trace!(target: "signer", "New authentication token generated.");
self.codes.push(Code { self.codes.push(Code {
code: code, code,
created_at: time::Duration::from_secs(self.now.now()), created_at: time::Duration::from_secs(self.now.now()),
last_used_at: None, last_used_at: None,
}); });

View File

@ -44,7 +44,7 @@ impl<M, T> http::MetaExtractor<M> for MetaExtractor<T> where
{ {
fn read_metadata(&self, req: &hyper::Request<hyper::Body>) -> M { fn read_metadata(&self, req: &hyper::Request<hyper::Body>) -> M {
let as_string = |header: Option<&hyper::header::HeaderValue>| { let as_string = |header: Option<&hyper::header::HeaderValue>| {
header.and_then(|val| val.to_str().ok().map(|s| s.to_owned())) header.and_then(|val| val.to_str().ok().map(ToOwned::to_owned))
}; };
let origin = as_string(req.headers().get("origin")); let origin = as_string(req.headers().get("origin"));

View File

@ -17,6 +17,25 @@
//! Parity RPC. //! Parity RPC.
#![warn(missing_docs, unused_extern_crates)] #![warn(missing_docs, unused_extern_crates)]
#![cfg_attr(feature = "cargo-clippy", warn(clippy::all, clippy::pedantic))]
#![cfg_attr(
feature = "cargo-clippy",
allow(
// things are often more readable this way
clippy::cast_lossless,
clippy::module_name_repetitions,
clippy::single_match_else,
clippy::type_complexity,
clippy::use_self,
// not practical
clippy::match_bool,
clippy::needless_pass_by_value,
clippy::similar_names,
// don't require markdown syntax for docs
clippy::doc_markdown,
),
warn(clippy::indexing_slicing)
)]
#[macro_use] #[macro_use]
extern crate futures; extern crate futures;
@ -145,8 +164,8 @@ pub fn start_http<M, S, H, T>(
Ok(http::ServerBuilder::with_meta_extractor(handler, extractor) Ok(http::ServerBuilder::with_meta_extractor(handler, extractor)
.keep_alive(keep_alive) .keep_alive(keep_alive)
.threads(threads) .threads(threads)
.cors(cors_domains.into()) .cors(cors_domains)
.allowed_hosts(allowed_hosts.into()) .allowed_hosts(allowed_hosts)
.health_api(("/api/health", "parity_nodeStatus")) .health_api(("/api/health", "parity_nodeStatus"))
.cors_allow_headers(AccessControlAllowHeaders::Any) .cors_allow_headers(AccessControlAllowHeaders::Any)
.max_request_body_size(max_payload * 1024 * 1024) .max_request_body_size(max_payload * 1024 * 1024)
@ -176,8 +195,8 @@ pub fn start_http_with_middleware<M, S, H, T, R>(
Ok(http::ServerBuilder::with_meta_extractor(handler, extractor) Ok(http::ServerBuilder::with_meta_extractor(handler, extractor)
.keep_alive(keep_alive) .keep_alive(keep_alive)
.threads(threads) .threads(threads)
.cors(cors_domains.into()) .cors(cors_domains)
.allowed_hosts(allowed_hosts.into()) .allowed_hosts(allowed_hosts)
.cors_allow_headers(AccessControlAllowHeaders::Any) .cors_allow_headers(AccessControlAllowHeaders::Any)
.max_request_body_size(max_payload * 1024 * 1024) .max_request_body_size(max_payload * 1024 * 1024)
.request_middleware(middleware) .request_middleware(middleware)

View File

@ -39,7 +39,7 @@ impl<T> Server<T> {
Server { Server {
server: f(remote), server: f(remote),
event_loop: event_loop, event_loop,
} }
} }
} }
@ -60,8 +60,8 @@ pub struct GuardedAuthCodes {
pub path: PathBuf, pub path: PathBuf,
} }
impl GuardedAuthCodes { impl Default for GuardedAuthCodes {
pub fn new() -> Self { fn default() -> Self {
let tempdir = TempDir::new("").unwrap(); let tempdir = TempDir::new("").unwrap();
let path = tempdir.path().join("file"); let path = tempdir.path().join("file");

View File

@ -30,7 +30,7 @@ pub struct Response {
impl Response { impl Response {
pub fn assert_header(&self, header: &str, value: &str) { pub fn assert_header(&self, header: &str, value: &str) {
let header = format!("{}: {}", header, value); let header = format!("{}: {}", header, value);
assert!(self.headers.iter().find(|h| *h == &header).is_some(), "Couldn't find header {} in {:?}", header, &self.headers) assert!(self.headers.iter().any(|h| h == &header), "Couldn't find header {} in {:?}", header, &self.headers)
} }
pub fn assert_status(&self, status: &str) { pub fn assert_status(&self, status: &str) {
@ -98,35 +98,35 @@ pub fn request(address: &SocketAddr, request: &str) -> Response {
let mut lines = response.lines(); let mut lines = response.lines();
let status = lines.next().expect("Expected a response").to_owned(); let status = lines.next().expect("Expected a response").to_owned();
let headers_raw = read_block(&mut lines, false); let headers_raw = read_block(&mut lines, false);
let headers = headers_raw.split('\n').map(|v| v.to_owned()).collect(); let headers = headers_raw.split('\n').map(ToOwned::to_owned).collect();
let body = read_block(&mut lines, true); let body = read_block(&mut lines, true);
Response { Response {
status: status, status,
headers: headers, headers,
headers_raw: headers_raw, headers_raw,
body: body, body,
} }
} }
/// Check if all required security headers are present /// Check if all required security headers are present
pub fn assert_security_headers_present(headers: &[String], port: Option<u16>) { pub fn assert_security_headers_present(headers: &[String], port: Option<u16>) {
if let None = port { if port.is_none() {
assert!( assert!(
headers.iter().find(|header| header.as_str() == "X-Frame-Options: SAMEORIGIN").is_some(), headers.iter().any(|header| header.as_str() == "X-Frame-Options: SAMEORIGIN")
"X-Frame-Options: SAMEORIGIN missing: {:?}", headers "X-Frame-Options: SAMEORIGIN missing: {:?}", headers
); );
} }
assert!( assert!(
headers.iter().find(|header| header.as_str() == "X-XSS-Protection: 1; mode=block").is_some(), headers.iter().any(|header| header.as_str() == "X-XSS-Protection: 1; mode=block")
"X-XSS-Protection missing: {:?}", headers "X-XSS-Protection missing: {:?}", headers
); );
assert!( assert!(
headers.iter().find(|header| header.as_str() == "X-Content-Type-Options: nosniff").is_some(), headers.iter().any(|header| header.as_str() == "X-Content-Type-Options: nosniff")
"X-Content-Type-Options missing: {:?}", headers "X-Content-Type-Options missing: {:?}", headers
); );
assert!( assert!(
headers.iter().find(|header| header.starts_with("Content-Security-Policy: ")).is_some(), headers.iter().any(|header| header.starts_with("Content-Security-Policy: "))
"Content-Security-Policy missing: {:?}", headers "Content-Security-Policy missing: {:?}", headers
) )
} }

View File

@ -29,7 +29,7 @@ use tests::http_client;
pub fn serve() -> (Server<ws::Server>, usize, GuardedAuthCodes) { pub fn serve() -> (Server<ws::Server>, usize, GuardedAuthCodes) {
let address = "127.0.0.1:0".parse().unwrap(); let address = "127.0.0.1:0".parse().unwrap();
let io = MetaIoHandler::default(); let io = MetaIoHandler::default();
let authcodes = GuardedAuthCodes::new(); let authcodes = GuardedAuthCodes::default();
let stats = Arc::new(informant::RpcStats::default()); let stats = Arc::new(informant::RpcStats::default());
let res = Server::new(|_| ::start_ws( let res = Server::new(|_| ::start_ws(

View File

@ -41,8 +41,8 @@ impl HttpMetaExtractor for RpcExtractor {
Metadata { Metadata {
origin: Origin::Rpc( origin: Origin::Rpc(
format!("{} / {}", format!("{} / {}",
origin.unwrap_or("unknown origin".to_string()), origin.unwrap_or_else(|| "unknown origin".to_string()),
user_agent.unwrap_or("unknown agent".to_string())) user_agent.unwrap_or_else(|| "unknown agent".to_string()))
), ),
session: None, session: None,
} }
@ -67,7 +67,7 @@ impl WsExtractor {
/// Creates new `WsExtractor` with given authcodes path. /// Creates new `WsExtractor` with given authcodes path.
pub fn new(path: Option<&Path>) -> Self { pub fn new(path: Option<&Path>) -> Self {
WsExtractor { WsExtractor {
authcodes_path: path.map(|p| p.to_owned()), authcodes_path: path.map(ToOwned::to_owned),
} }
} }
} }
@ -80,7 +80,7 @@ impl ws::MetaExtractor<Metadata> for WsExtractor {
Some(ref path) => { Some(ref path) => {
let authorization = req.protocols.get(0).and_then(|p| auth_token_hash(&path, p, true)); let authorization = req.protocols.get(0).and_then(|p| auth_token_hash(&path, p, true));
match authorization { match authorization {
Some(id) => Origin::Signer { session: id.into() }, Some(id) => Origin::Signer { session: id },
None => Origin::Ws { session: id.into() }, None => Origin::Ws { session: id.into() },
} }
}, },
@ -186,7 +186,7 @@ impl WsStats {
/// Creates new WS usage tracker. /// Creates new WS usage tracker.
pub fn new(stats: Arc<RpcStats>) -> Self { pub fn new(stats: Arc<RpcStats>) -> Self {
WsStats { WsStats {
stats: stats, stats,
} }
} }
} }
@ -210,7 +210,7 @@ impl<M: core::Middleware<Metadata>> WsDispatcher<M> {
/// Create new `WsDispatcher` with given full handler. /// Create new `WsDispatcher` with given full handler.
pub fn new(full_handler: core::MetaIoHandler<Metadata, M>) -> Self { pub fn new(full_handler: core::MetaIoHandler<Metadata, M>) -> Self {
WsDispatcher { WsDispatcher {
full_handler: full_handler, full_handler,
} }
} }
} }
@ -229,7 +229,7 @@ impl<M: core::Middleware<Metadata>> core::Middleware<Metadata> for WsDispatcher<
X: core::futures::Future<Item=Option<core::Response>, Error=()> + Send + 'static, X: core::futures::Future<Item=Option<core::Response>, Error=()> + Send + 'static,
{ {
let use_full = match &meta.origin { let use_full = match &meta.origin {
&Origin::Signer { .. } => true, Origin::Signer { .. } => true,
_ => false, _ => false,
}; };

View File

@ -66,7 +66,7 @@ impl<N: Fn() -> Instant> DeprecationNotice<N> {
pub fn print<'a, T: Into<Option<&'a str>>>(&self, method: MethodName, details: T) { pub fn print<'a, T: Into<Option<&'a str>>>(&self, method: MethodName, details: T) {
let now = (self.now)(); let now = (self.now)();
match self.next_warning_at.read().get(method) { match self.next_warning_at.read().get(method) {
Some(next) if next > &now => return, Some(next) if *next > now => return,
_ => {}, _ => {},
} }

View File

@ -147,19 +147,19 @@ where
const DEFAULT_GAS_PRICE: U256 = U256([0, 0, 0, 21_000_000]); const DEFAULT_GAS_PRICE: U256 = U256([0, 0, 0, 21_000_000]);
let gas_limit = self.client.best_block_header().gas_limit(); let gas_limit = self.client.best_block_header().gas_limit();
let request_gas_price = request.gas_price.clone(); let request_gas_price = request.gas_price;
let from = request.from.unwrap_or(default_sender); let from = request.from.unwrap_or(default_sender);
let with_gas_price = move |gas_price| { let with_gas_price = move |gas_price| {
let request = request; let request = request;
FilledTransactionRequest { FilledTransactionRequest {
from: from.clone(), from,
used_default_from: request.from.is_none(), used_default_from: request.from.is_none(),
to: request.to, to: request.to,
nonce: request.nonce, nonce: request.nonce,
gas_price: gas_price, gas_price,
gas: request.gas.unwrap_or_else(|| gas_limit / 3), gas: request.gas.unwrap_or_else(|| gas_limit / 3),
value: request.value.unwrap_or_else(|| 0.into()), value: request.value.unwrap_or_default(),
data: request.data.unwrap_or_else(Vec::new), data: request.data.unwrap_or_else(Vec::new),
condition: request.condition, condition: request.condition,
} }

View File

@ -294,7 +294,7 @@ pub fn execute<D: Dispatcher + 'static>(
Box::new( Box::new(
dispatcher.sign(request, &signer, pass, post_sign).map(|(hash, token)| { dispatcher.sign(request, &signer, pass, post_sign).map(|(hash, token)| {
WithToken::from((ConfirmationResponse::SendTransaction(hash.into()), token)) WithToken::from((ConfirmationResponse::SendTransaction(hash), token))
}) })
) )
}, },
@ -368,13 +368,13 @@ pub fn from_rpc<D>(payload: RpcConfirmationPayload, default_account: Address, di
.map(ConfirmationPayload::SignTransaction)) .map(ConfirmationPayload::SignTransaction))
}, },
RpcConfirmationPayload::Decrypt(RpcDecryptRequest { address, msg }) => { RpcConfirmationPayload::Decrypt(RpcDecryptRequest { address, msg }) => {
Box::new(future::ok(ConfirmationPayload::Decrypt(address.into(), msg.into()))) Box::new(future::ok(ConfirmationPayload::Decrypt(address, msg.into())))
}, },
RpcConfirmationPayload::EthSignMessage(RpcEthSignRequest { address, data }) => { RpcConfirmationPayload::EthSignMessage(RpcEthSignRequest { address, data }) => {
Box::new(future::ok(ConfirmationPayload::EthSignMessage(address.into(), data.into()))) Box::new(future::ok(ConfirmationPayload::EthSignMessage(address, data.into())))
}, },
RpcConfirmationPayload::EIP191SignMessage(RpcSignRequest { address, data }) => { RpcConfirmationPayload::EIP191SignMessage(RpcSignRequest { address, data }) => {
Box::new(future::ok(ConfirmationPayload::SignMessage(address.into(), data.into()))) Box::new(future::ok(ConfirmationPayload::SignMessage(address, data)))
}, },
} }
} }

View File

@ -40,7 +40,7 @@ impl SignerService {
SignerService { SignerService {
queue: Arc::new(ConfirmationsQueue::default()), queue: Arc::new(ConfirmationsQueue::default()),
generate_new_token: Box::new(new_token), generate_new_token: Box::new(new_token),
is_enabled: is_enabled, is_enabled,
} }
} }

View File

@ -28,7 +28,7 @@ pub struct Sender<T> {
impl<T> Sender<T> { impl<T> Sender<T> {
pub fn send(self, data: Res<T>) { pub fn send(self, data: Res<T>) {
let res = self.sender.send(data); let res = self.sender.send(data);
if let Err(_) = res { if res.is_err() {
debug!(target: "rpc", "Responding to a no longer active request."); debug!(target: "rpc", "Responding to a no longer active request.");
} }
} }

View File

@ -121,7 +121,7 @@ impl ConfirmationsQueue {
)); ));
// notify confirmation receiver about resolution // notify confirmation receiver about resolution
let result = result.ok_or(errors::request_rejected()); let result = result.ok_or_else(errors::request_rejected);
sender.sender.send(result); sender.sender.send(result);
Some(sender.request) Some(sender.request)
@ -150,7 +150,7 @@ impl SigningQueue for ConfirmationsQueue {
// Increment id // Increment id
let id = { let id = {
let mut last_id = self.id.lock(); let mut last_id = self.id.lock();
*last_id = *last_id + U256::from(1); *last_id += U256::from(1);
*last_id *last_id
}; };
// Add request to queue // Add request to queue

View File

@ -24,16 +24,16 @@ pub fn sign_call(request: CallRequest) -> Result<SignedTransaction, Error> {
let max_gas = U256::from(50_000_000); let max_gas = U256::from(50_000_000);
let gas = match request.gas { let gas = match request.gas {
Some(gas) => gas, Some(gas) => gas,
None => max_gas * 10u32, None => max_gas * 10_u32,
}; };
let from = request.from.unwrap_or(0.into()); let from = request.from.unwrap_or_default();
Ok(Transaction { Ok(Transaction {
nonce: request.nonce.unwrap_or_else(|| 0.into()), nonce: request.nonce.unwrap_or_default(),
action: request.to.map_or(Action::Create, Action::Call), action: request.to.map_or(Action::Create, Action::Call),
gas, gas,
gas_price: request.gas_price.unwrap_or_else(|| 0.into()), gas_price: request.gas_price.unwrap_or_default(),
value: request.value.unwrap_or(0.into()), value: request.value.unwrap_or_default(),
data: request.data.unwrap_or_default(), data: request.data.unwrap_or_default(),
}.fake_sign(from)) }.fake_sign(from))
} }

View File

@ -28,5 +28,5 @@ pub fn cid(content: Bytes) -> Result<String, Error> {
let hash = digest::sha256(&content.0); let hash = digest::sha256(&content.0);
let mh = multihash::encode(multihash::Hash::SHA2256, &*hash).map_err(errors::encoding)?; let mh = multihash::encode(multihash::Hash::SHA2256, &*hash).map_err(errors::encoding)?;
let cid = Cid::new(Codec::DagProtobuf, Version::V0, &mh); let cid = Cid::new(Codec::DagProtobuf, Version::V0, &mh);
Ok(cid.to_string().into()) Ok(cid.to_string())
} }

View File

@ -121,7 +121,7 @@ pub fn extract_transaction_at_index(block: encoded::Block, index: usize) -> Opti
cached_sender, cached_sender,
} }
}) })
.map(|tx| Transaction::from_localized(tx)) .map(Transaction::from_localized)
} }
// extract the header indicated by the given `HeaderRef` from the given responses. // extract the header indicated by the given `HeaderRef` from the given responses.
@ -159,7 +159,7 @@ where
let idx = reqs.len(); let idx = reqs.len();
let hash_ref = Field::back_ref(idx, 0); let hash_ref = Field::back_ref(idx, 0);
reqs.push(req.into()); reqs.push(req.into());
reqs.push(request::HeaderByHash(hash_ref.clone()).into()); reqs.push(request::HeaderByHash(hash_ref).into());
Ok(HeaderRef::Unresolved(idx + 1, hash_ref)) Ok(HeaderRef::Unresolved(idx + 1, hash_ref))
} }
@ -197,7 +197,7 @@ where
Err(e) => return Either::A(future::err(e)), Err(e) => return Either::A(future::err(e)),
}; };
reqs.push(request::Account { header: header_ref.clone(), address: address }.into()); reqs.push(request::Account { header: header_ref.clone(), address }.into());
let account_idx = reqs.len() - 1; let account_idx = reqs.len() - 1;
reqs.push(request::Code { header: header_ref, code_hash: Field::back_ref(account_idx, 0) }.into()); reqs.push(request::Code { header: header_ref, code_hash: Field::back_ref(account_idx, 0) }.into());
@ -216,7 +216,7 @@ where
Err(e) => return Either::A(future::err(e)), Err(e) => return Either::A(future::err(e)),
}; };
reqs.push(request::Account { header: header_ref, address: address }.into()); reqs.push(request::Account { header: header_ref, address }.into());
Either::B(self.send_requests(reqs, |mut res|match res.pop() { Either::B(self.send_requests(reqs, |mut res|match res.pop() {
Some(OnDemandResponse::Account(acc)) => acc, Some(OnDemandResponse::Account(acc)) => acc,
@ -246,7 +246,7 @@ where
} }
}; };
let from = req.from.unwrap_or_else(|| Address::zero()); let from = req.from.unwrap_or_default();
let nonce_fut = match req.nonce { let nonce_fut = match req.nonce {
Some(nonce) => Either::A(future::ok(Some(nonce))), Some(nonce) => Either::A(future::ok(Some(nonce))),
None => Either::B(self.account(from, id).map(|acc| acc.map(|a| a.nonce))), None => Either::B(self.account(from, id).map(|acc| acc.map(|a| a.nonce))),
@ -370,10 +370,10 @@ where
for (transaction_log_index, log) in receipt.logs.into_iter().enumerate() { for (transaction_log_index, log) in receipt.logs.into_iter().enumerate() {
if filter.matches(&log) { if filter.matches(&log) {
matches.insert((num, block_index), Log { matches.insert((num, block_index), Log {
address: log.address.into(), address: log.address,
topics: log.topics.into_iter().map(Into::into).collect(), topics: log.topics.into_iter().map(Into::into).collect(),
data: log.data.into(), data: log.data.into(),
block_hash: Some(hash.into()), block_hash: Some(hash),
block_number: Some(num.into()), block_number: Some(num.into()),
// No way to easily retrieve transaction hash, so let's just skip it. // No way to easily retrieve transaction hash, so let's just skip it.
transaction_hash: None, transaction_hash: None,
@ -410,8 +410,8 @@ where
let mut blocks = BTreeMap::new(); let mut blocks = BTreeMap::new();
for log in result.iter() { for log in result.iter() {
let block_hash = log.block_hash.as_ref().expect("Previously initialized with value; qed"); let block_hash = log.block_hash.as_ref().expect("Previously initialized with value; qed");
blocks.entry(block_hash.clone()).or_insert_with(|| { blocks.entry(*block_hash).or_insert_with(|| {
fetcher_block.block(BlockId::Hash(block_hash.clone().into())) fetcher_block.block(BlockId::Hash(*block_hash))
}); });
} }
// future get blocks (unordered it) // future get blocks (unordered it)
@ -419,12 +419,12 @@ where
let transactions_per_block: BTreeMap<_, _> = blocks.iter() let transactions_per_block: BTreeMap<_, _> = blocks.iter()
.map(|block| (block.hash(), block.transactions())).collect(); .map(|block| (block.hash(), block.transactions())).collect();
for log in result.iter_mut() { for log in result.iter_mut() {
let log_index: U256 = log.transaction_index.expect("Previously initialized with value; qed").into(); let log_index = log.transaction_index.expect("Previously initialized with value; qed");
let block_hash = log.block_hash.clone().expect("Previously initialized with value; qed").into(); let block_hash = log.block_hash.expect("Previously initialized with value; qed");
let tx_hash = transactions_per_block.get(&block_hash) let tx_hash = transactions_per_block.get(&block_hash)
// transaction index is from an enumerate call in log common so not need to check value // transaction index is from an enumerate call in log common so not need to check value
.and_then(|txs| txs.get(log_index.as_usize())) .and_then(|txs| txs.get(log_index.as_usize()))
.map(|tr| tr.hash().into()); .map(types::transaction::UnverifiedTransaction::hash);
log.transaction_hash = tx_hash; log.transaction_hash = tx_hash;
} }
result result
@ -442,7 +442,7 @@ where
Box::new(future::loop_fn(params, move |(sync, on_demand)| { Box::new(future::loop_fn(params, move |(sync, on_demand)| {
let maybe_future = sync.with_context(|ctx| { let maybe_future = sync.with_context(|ctx| {
let req = request::TransactionIndex(tx_hash.clone().into()); let req = request::TransactionIndex(tx_hash.into());
on_demand.request(ctx, req) on_demand.request(ctx, req)
}); });
@ -468,7 +468,7 @@ where
let index = index.index as usize; let index = index.index as usize;
let transaction = extract_transaction_at_index(blk, index); let transaction = extract_transaction_at_index(blk, index);
if transaction.as_ref().map_or(true, |tx| tx.hash != tx_hash.into()) { if transaction.as_ref().map_or(true, |tx| tx.hash != tx_hash) {
// index is actively wrong: indicated block has // index is actively wrong: indicated block has
// fewer transactions than necessary or the transaction // fewer transactions than necessary or the transaction
// at that index had a different hash. // at that index had a different hash.
@ -522,7 +522,7 @@ where
) -> impl Future<Item = Vec<encoded::Header>, Error = Error> { ) -> impl Future<Item = Vec<encoded::Header>, Error = Error> {
let fetch_hashes = [from_block, to_block].iter() let fetch_hashes = [from_block, to_block].iter()
.filter_map(|block_id| match block_id { .filter_map(|block_id| match block_id {
BlockId::Hash(hash) => Some(hash.clone()), BlockId::Hash(hash) => Some(*hash),
_ => None, _ => None,
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@ -533,14 +533,14 @@ where
self.headers_by_hash(&fetch_hashes[..]).and_then(move |mut header_map| { self.headers_by_hash(&fetch_hashes[..]).and_then(move |mut header_map| {
let (from_block_num, to_block_num) = { let (from_block_num, to_block_num) = {
let block_number = |id| match id { let block_number = |id| match id {
&BlockId::Earliest => 0, BlockId::Earliest => 0,
&BlockId::Latest => best_number, BlockId::Latest => best_number,
&BlockId::Hash(ref h) => BlockId::Hash(ref h) =>
header_map.get(h).map(|hdr| hdr.number()) header_map.get(h).map(types::encoded::Header::number)
.expect("from_block and to_block headers are fetched by hash; this closure is only called on from_block and to_block; qed"), .expect("from_block and to_block headers are fetched by hash; this closure is only called on from_block and to_block; qed"),
&BlockId::Number(x) => x, BlockId::Number(x) => x,
}; };
(block_number(&from_block), block_number(&to_block)) (block_number(from_block), block_number(to_block))
}; };
if to_block_num < from_block_num { if to_block_num < from_block_num {
@ -557,7 +557,7 @@ where
let headers_fut = fetcher.headers_range(from_block_num, to_block_num, to_header_hint); let headers_fut = fetcher.headers_range(from_block_num, to_block_num, to_header_hint);
Either::B(headers_fut.map(move |headers| { Either::B(headers_fut.map(move |headers| {
// Validate from_block if it's a hash // Validate from_block if it's a hash
let last_hash = headers.last().map(|hdr| hdr.hash()); let last_hash = headers.last().map(types::encoded::Header::hash);
match (last_hash, from_block) { match (last_hash, from_block) {
(Some(h1), BlockId::Hash(h2)) if h1 != h2 => Vec::new(), (Some(h1), BlockId::Hash(h2)) if h1 != h2 => Vec::new(),
_ => headers, _ => headers,
@ -578,15 +578,13 @@ where
} }
self.send_requests(reqs, move |res| { self.send_requests(reqs, move |res| {
let headers = refs.drain() refs.into_iter().map(|(hash, header_ref)| {
.map(|(hash, header_ref)| {
let hdr = extract_header(&res, header_ref) let hdr = extract_header(&res, header_ref)
.expect("these responses correspond to requests that header_ref belongs to; \ .expect("these responses correspond to requests that header_ref belongs to; \
qed"); qed");
(hash, hdr) (hash, hdr)
}) })
.collect(); .collect()
headers
}) })
} }
@ -678,7 +676,7 @@ where
{ {
fn clone(&self) -> Self { fn clone(&self) -> Self {
Self { Self {
from: self.from.clone(), from: self.from,
tx: self.tx.clone(), tx: self.tx.clone(),
hdr: self.hdr.clone(), hdr: self.hdr.clone(),
env_info: self.env_info.clone(), env_info: self.env_info.clone(),
@ -719,7 +717,7 @@ where
required, got); required, got);
if required <= params.hdr.gas_limit() { if required <= params.hdr.gas_limit() {
params.tx.gas = required; params.tx.gas = required;
return Ok(future::Loop::Continue(params)) Ok(future::Loop::Continue(params))
} else { } else {
warn!(target: "light_fetch", warn!(target: "light_fetch",
"Required gas is bigger than block header's gas dropping the request"); "Required gas is bigger than block header's gas dropping the request");

View File

@ -45,7 +45,7 @@ pub fn verify_signature(
let v = if v >= 35 { (v - 1) % 2 } else { v }; let v = if v >= 35 { (v - 1) % 2 } else { v };
let signature = Signature::from_rsv(&r.into(), &s.into(), v as u8); let signature = Signature::from_rsv(&r, &s, v as u8);
let public_key = recover(&signature, &hash).map_err(errors::encryption)?; let public_key = recover(&signature, &hash).map_err(errors::encryption)?;
let address = public_to_address(&public_key); let address = public_to_address(&public_key);
Ok(RecoveredAccount { address, public_key, is_valid_for_current_chain }) Ok(RecoveredAccount { address, public_key, is_valid_for_current_chain })

View File

@ -52,7 +52,7 @@ impl<S: core::Middleware<Metadata>> GenericPollManager<S> {
pub fn new(rpc: MetaIoHandler<Metadata, S>) -> Self { pub fn new(rpc: MetaIoHandler<Metadata, S>) -> Self {
GenericPollManager { GenericPollManager {
subscribers: Default::default(), subscribers: Default::default(),
rpc: rpc, rpc,
} }
} }

View File

@ -29,15 +29,10 @@ pub fn submit_work_detail<C: BlockChainClient, M: MinerService>(client: &Arc<C>,
// TODO [ToDr] Should disallow submissions in case of PoA? // TODO [ToDr] Should disallow submissions in case of PoA?
trace!(target: "miner", "submit_work_detail: Decoded: nonce={}, pow_hash={}, mix_hash={}", nonce, pow_hash, mix_hash); trace!(target: "miner", "submit_work_detail: Decoded: nonce={}, pow_hash={}, mix_hash={}", nonce, pow_hash, mix_hash);
let seal = vec![rlp::encode(&mix_hash), rlp::encode(&nonce)]; let seal = vec![rlp::encode(&mix_hash), rlp::encode(&nonce)];
let import = miner.submit_seal(pow_hash, seal) miner.submit_seal(pow_hash, seal)
.and_then(|block| client.import_sealed_block(block)); .and_then(|block| client.import_sealed_block(block))
match import { .map_err(|e| {
Ok(hash) => { warn!(target: "miner", "Cannot submit work - {:?}.", e);
Ok(hash.into()) errors::cannot_submit_work(e)
}, })
Err(err) => {
warn!(target: "miner", "Cannot submit work - {:?}.", err);
Err(errors::cannot_submit_work(err))
},
}
} }

View File

@ -19,6 +19,7 @@
use std::sync::Arc; use std::sync::Arc;
use ethcore::client::BlockChainClient; use ethcore::client::BlockChainClient;
use types::header::Header;
use types::transaction::LocalizedTransaction; use types::transaction::LocalizedTransaction;
use jsonrpc_core::Result; use jsonrpc_core::Result;
@ -50,7 +51,7 @@ impl<C: BlockChainClient + 'static> Debug for DebugClient<C> {
let hash = block.header.hash(); let hash = block.header.hash();
RichBlock { RichBlock {
inner: Block { inner: Block {
hash: Some(hash.into()), hash: Some(hash),
size: Some(block.bytes.len().into()), size: Some(block.bytes.len().into()),
parent_hash: cast(block.header.parent_hash()), parent_hash: cast(block.header.parent_hash()),
uncles_hash: cast(block.header.uncles_hash()), uncles_hash: cast(block.header.uncles_hash()),
@ -65,14 +66,14 @@ impl<C: BlockChainClient + 'static> Debug for DebugClient<C> {
timestamp: block.header.timestamp().into(), timestamp: block.header.timestamp().into(),
difficulty: cast(block.header.difficulty()), difficulty: cast(block.header.difficulty()),
total_difficulty: None, total_difficulty: None,
seal_fields: block.header.seal().into_iter().cloned().map(Into::into).collect(), seal_fields: block.header.seal().iter().cloned().map(Into::into).collect(),
uncles: block.uncles.into_iter().map(|u| u.hash().into()).collect(), uncles: block.uncles.iter().map(Header::hash).collect(),
transactions: BlockTransactions::Full(block.transactions transactions: BlockTransactions::Full(block.transactions
.into_iter() .into_iter()
.enumerate() .enumerate()
.map(|(transaction_index, signed)| Transaction::from_localized(LocalizedTransaction { .map(|(transaction_index, signed)| Transaction::from_localized(LocalizedTransaction {
block_number: number.into(), block_number: number,
block_hash: hash.into(), block_hash: hash,
transaction_index, transaction_index,
signed, signed,
cached_sender: None, cached_sender: None,

View File

@ -197,7 +197,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> EthClient<C, SN, S
accounts: accounts.clone(), accounts: accounts.clone(),
external_miner: em.clone(), external_miner: em.clone(),
seed_compute: Mutex::new(SeedHashCompute::default()), seed_compute: Mutex::new(SeedHashCompute::default()),
options: options, options,
deprecation_notice: Default::default(), deprecation_notice: Default::default(),
} }
} }
@ -257,34 +257,34 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> EthClient<C, SN, S
inner: Block { inner: Block {
hash: match is_pending { hash: match is_pending {
true => None, true => None,
false => Some(view.hash().into()), false => Some(view.hash()),
}, },
size: Some(block.rlp().as_raw().len().into()), size: Some(block.rlp().as_raw().len().into()),
parent_hash: view.parent_hash().into(), parent_hash: view.parent_hash(),
uncles_hash: view.uncles_hash().into(), uncles_hash: view.uncles_hash(),
author: view.author().into(), author: view.author(),
miner: view.author().into(), miner: view.author(),
state_root: view.state_root().into(), state_root: view.state_root(),
transactions_root: view.transactions_root().into(), transactions_root: view.transactions_root(),
receipts_root: view.receipts_root().into(), receipts_root: view.receipts_root(),
number: match is_pending { number: match is_pending {
true => None, true => None,
false => Some(view.number().into()), false => Some(view.number().into()),
}, },
gas_used: view.gas_used().into(), gas_used: view.gas_used(),
gas_limit: view.gas_limit().into(), gas_limit: view.gas_limit(),
logs_bloom: match is_pending { logs_bloom: match is_pending {
true => None, true => None,
false => Some(view.log_bloom().into()), false => Some(view.log_bloom()),
}, },
timestamp: view.timestamp().into(), timestamp: view.timestamp().into(),
difficulty: view.difficulty().into(), difficulty: view.difficulty(),
total_difficulty: Some(total_difficulty.into()), total_difficulty: Some(total_difficulty),
seal_fields: view.seal().into_iter().map(Into::into).collect(), seal_fields: view.seal().into_iter().map(Into::into).collect(),
uncles: block.uncle_hashes().into_iter().map(Into::into).collect(), uncles: block.uncle_hashes(),
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()),
false => BlockTransactions::Hashes(block.transaction_hashes().into_iter().map(Into::into).collect()), false => BlockTransactions::Hashes(block.transaction_hashes()),
}, },
extra_data: Bytes::new(view.extra_data()), extra_data: Bytes::new(view.extra_data()),
}, },
@ -334,7 +334,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> EthClient<C, SN, S
cached_sender, cached_sender,
} }
}) })
.map(|tx| Transaction::from_localized(tx)); .map(Transaction::from_localized);
Ok(transaction) Ok(transaction)
} }
@ -385,7 +385,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> EthClient<C, SN, S
None => { return Ok(None); } None => { return Ok(None); }
}; };
let parent_difficulty = match client.block_total_difficulty(BlockId::Hash(uncle.parent_hash().clone())) { let parent_difficulty = match client.block_total_difficulty(BlockId::Hash(*uncle.parent_hash())) {
Some(difficulty) => difficulty, Some(difficulty) => difficulty,
None => { return Ok(None); } None => { return Ok(None); }
}; };
@ -398,29 +398,28 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> EthClient<C, SN, S
let size = client.block(BlockId::Hash(uncle.hash())) let size = client.block(BlockId::Hash(uncle.hash()))
.map(|block| block.into_inner().len()) .map(|block| block.into_inner().len())
.map(U256::from) .map(U256::from);
.map(Into::into);
let block = RichBlock { let block = RichBlock {
inner: Block { inner: Block {
hash: Some(uncle.hash().into()), hash: Some(uncle.hash()),
size: size, size,
parent_hash: uncle.parent_hash().clone().into(), parent_hash: *uncle.parent_hash(),
uncles_hash: uncle.uncles_hash().clone().into(), uncles_hash: *uncle.uncles_hash(),
author: uncle.author().clone().into(), author: *uncle.author(),
miner: uncle.author().clone().into(), miner: *uncle.author(),
state_root: uncle.state_root().clone().into(), state_root: *uncle.state_root(),
transactions_root: uncle.transactions_root().clone().into(), transactions_root: *uncle.transactions_root(),
number: Some(uncle.number().into()), number: Some(uncle.number().into()),
gas_used: uncle.gas_used().clone().into(), gas_used: *uncle.gas_used(),
gas_limit: uncle.gas_limit().clone().into(), gas_limit: *uncle.gas_limit(),
logs_bloom: Some(uncle.log_bloom().clone().into()), logs_bloom: Some(*uncle.log_bloom()),
timestamp: uncle.timestamp().into(), timestamp: uncle.timestamp().into(),
difficulty: uncle.difficulty().clone().into(), difficulty: *uncle.difficulty(),
total_difficulty: Some((uncle.difficulty().clone() + parent_difficulty).into()), total_difficulty: Some(uncle.difficulty() + parent_difficulty),
receipts_root: uncle.receipts_root().clone().into(), receipts_root: *uncle.receipts_root(),
extra_data: uncle.extra_data().clone().into(), extra_data: uncle.extra_data().clone().into(),
seal_fields: uncle.seal().into_iter().cloned().map(Into::into).collect(), seal_fields: uncle.seal().iter().cloned().map(Into::into).collect(),
uncles: vec![], uncles: vec![],
transactions: BlockTransactions::Hashes(vec![]), transactions: BlockTransactions::Hashes(vec![]),
}, },
@ -459,7 +458,7 @@ pub fn pending_logs<M>(miner: &M, best_block: EthBlockNumber, filter: &EthcoreFi
.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);
log log
}) })
.collect() .collect()
@ -518,8 +517,8 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
let info = SyncInfo { let info = SyncInfo {
starting_block: status.start_block_number.into(), starting_block: status.start_block_number.into(),
current_block: current_block.into(), current_block,
highest_block: highest_block.into(), highest_block,
warp_chunks_amount: warp_chunks_amount.map(|x| U256::from(x as u64)).map(Into::into), warp_chunks_amount: warp_chunks_amount.map(|x| U256::from(x as u64)).map(Into::into),
warp_chunks_processed: warp_chunks_processed.map(|x| U256::from(x as u64)).map(Into::into), warp_chunks_processed: warp_chunks_processed.map(|x| U256::from(x as u64)).map(Into::into),
}; };
@ -535,10 +534,9 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
(self.accounts)() (self.accounts)()
.first() .first()
.cloned() .cloned()
.map(From::from)
.ok_or_else(|| errors::account("No accounts were found", "")) .ok_or_else(|| errors::account("No accounts were found", ""))
} else { } else {
Ok(H160::from(miner)) Ok(miner)
} }
} }
@ -551,18 +549,18 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
} }
fn hashrate(&self) -> Result<U256> { fn hashrate(&self) -> Result<U256> {
Ok(U256::from(self.external_miner.hashrate())) Ok(self.external_miner.hashrate())
} }
fn gas_price(&self) -> Result<U256> { fn gas_price(&self) -> Result<U256> {
Ok(U256::from(default_gas_price(&*self.client, &*self.miner, self.options.gas_price_percentile))) Ok(default_gas_price(&*self.client, &*self.miner, self.options.gas_price_percentile))
} }
fn accounts(&self) -> Result<Vec<H160>> { fn accounts(&self) -> Result<Vec<H160>> {
self.deprecation_notice.print("eth_accounts", deprecated::msgs::ACCOUNTS); self.deprecation_notice.print("eth_accounts", deprecated::msgs::ACCOUNTS);
let accounts = (self.accounts)(); let accounts = (self.accounts)();
Ok(accounts.into_iter().map(Into::into).collect()) Ok(accounts)
} }
fn block_number(&self) -> Result<U256> { fn block_number(&self) -> Result<U256> {
@ -574,7 +572,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
try_bf!(check_known(&*self.client, num.clone())); try_bf!(check_known(&*self.client, num.clone()));
let res = match self.client.balance(&address, self.get_state(num)) { let res = match self.client.balance(&address, self.get_state(num)) {
Some(balance) => Ok(balance.into()), Some(balance) => Ok(balance),
None => Err(errors::state_pruned()), None => Err(errors::state_pruned()),
}; };
@ -600,16 +598,16 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
try_bf!(check_known(&*self.client, num.clone())); try_bf!(check_known(&*self.client, num.clone()));
let res = match self.client.prove_account(key1, id) { let res = match self.client.prove_account(key1, id) {
Some((proof, account)) => Ok(EthAccount { Some((proof, account)) => Ok(EthAccount {
address: address, address,
balance: account.balance.into(), balance: account.balance,
nonce: account.nonce.into(), nonce: account.nonce,
code_hash: account.code_hash.into(), code_hash: account.code_hash,
storage_hash: account.storage_root.into(), storage_hash: account.storage_root,
account_proof: proof.into_iter().map(Bytes::new).collect(), account_proof: proof.into_iter().map(Bytes::new).collect(),
storage_proof: values.into_iter().filter_map(|storage_index| { storage_proof: values.into_iter().filter_map(|storage_index| {
let key2: H256 = storage_index.into(); let key2: H256 = storage_index;
self.client.prove_storage(key1, keccak(key2), id) self.client.prove_storage(key1, keccak(key2), id)
.map(|(storage_proof,storage_value)| StorageProof { .map(|(storage_proof, storage_value)| StorageProof {
key: key2.into(), key: key2.into(),
value: storage_value.into(), value: storage_value.into(),
proof: storage_proof.into_iter().map(Bytes::new).collect() proof: storage_proof.into_iter().map(Bytes::new).collect()
@ -624,12 +622,11 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
} }
fn storage_at(&self, address: H160, position: U256, num: Option<BlockNumber>) -> BoxFuture<H256> { fn storage_at(&self, address: H160, position: U256, num: Option<BlockNumber>) -> BoxFuture<H256> {
let address: Address = address.into();
let num = num.unwrap_or_default(); let num = num.unwrap_or_default();
try_bf!(check_known(&*self.client, num.clone())); try_bf!(check_known(&*self.client, num.clone()));
let res = match self.client.storage_at(&address, &H256::from(position), self.get_state(num)) { let res = match self.client.storage_at(&address, &H256::from(position), self.get_state(num)) {
Some(s) => Ok(s.into()), Some(s) => Ok(s),
None => Err(errors::state_pruned()), None => Err(errors::state_pruned()),
}; };
@ -637,11 +634,9 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
} }
fn transaction_count(&self, address: H160, num: Option<BlockNumber>) -> BoxFuture<U256> { fn transaction_count(&self, address: H160, num: Option<BlockNumber>) -> BoxFuture<U256> {
let address: Address = address.into();
let res = match num.unwrap_or_default() { let res = match num.unwrap_or_default() {
BlockNumber::Pending if self.options.pending_nonce_from_queue => { BlockNumber::Pending if self.options.pending_nonce_from_queue => {
Ok(self.miner.next_nonce(&*self.client, &address).into()) Ok(self.miner.next_nonce(&*self.client, &address))
} }
BlockNumber::Pending => { BlockNumber::Pending => {
let info = self.client.chain_info(); let info = self.client.chain_info();
@ -654,14 +649,14 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
}); });
match nonce { match nonce {
Some(nonce) => Ok(nonce.into()), Some(nonce) => Ok(nonce),
None => Err(errors::database("latest nonce missing")) None => Err(errors::database("latest nonce missing"))
} }
}, },
number => { number => {
try_bf!(check_known(&*self.client, number.clone())); try_bf!(check_known(&*self.client, number.clone()));
match self.client.nonce(&address, block_number_to_id(number)) { match self.client.nonce(&address, block_number_to_id(number)) {
Some(nonce) => Ok(nonce.into()), Some(nonce) => Ok(nonce),
None => Err(errors::state_pruned()), None => Err(errors::state_pruned()),
} }
} }
@ -671,7 +666,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
} }
fn block_transaction_count_by_hash(&self, hash: H256) -> BoxFuture<Option<U256>> { fn block_transaction_count_by_hash(&self, hash: H256) -> BoxFuture<Option<U256>> {
let trx_count = self.client.block(BlockId::Hash(hash.into())) let trx_count = self.client.block(BlockId::Hash(hash))
.map(|block| block.transactions_count().into()); .map(|block| block.transactions_count().into());
let result = Ok(trx_count) let result = Ok(trx_count)
.and_then(errors::check_block_gap(&*self.client, self.options.allow_missing_blocks)); .and_then(errors::check_block_gap(&*self.client, self.options.allow_missing_blocks));
@ -696,7 +691,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
} }
fn block_uncles_count_by_hash(&self, hash: H256) -> BoxFuture<Option<U256>> { fn block_uncles_count_by_hash(&self, hash: H256) -> BoxFuture<Option<U256>> {
let uncle_count = self.client.block(BlockId::Hash(hash.into())) let uncle_count = self.client.block(BlockId::Hash(hash))
.map(|block| block.uncles_count().into()); .map(|block| block.uncles_count().into());
let result = Ok(uncle_count) let result = Ok(uncle_count)
.and_then(errors::check_block_gap(&*self.client, self.options.allow_missing_blocks)); .and_then(errors::check_block_gap(&*self.client, self.options.allow_missing_blocks));
@ -734,7 +729,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
} }
fn block_by_hash(&self, hash: H256, include_txs: bool) -> BoxFuture<Option<RichBlock>> { fn block_by_hash(&self, hash: H256, include_txs: bool) -> BoxFuture<Option<RichBlock>> {
let result = self.rich_block(BlockId::Hash(hash.into()).into(), include_txs) let result = self.rich_block(BlockId::Hash(hash).into(), include_txs)
.and_then(errors::check_block_gap(&*self.client, self.options.allow_missing_blocks)); .and_then(errors::check_block_gap(&*self.client, self.options.allow_missing_blocks));
Box::new(future::done(result)) Box::new(future::done(result))
} }
@ -756,7 +751,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
} }
fn transaction_by_block_hash_and_index(&self, hash: H256, index: Index) -> BoxFuture<Option<Transaction>> { fn transaction_by_block_hash_and_index(&self, hash: H256, index: Index) -> BoxFuture<Option<Transaction>> {
let id = PendingTransactionId::Location(PendingOrBlock::Block(BlockId::Hash(hash.into())), index.value()); let id = PendingTransactionId::Location(PendingOrBlock::Block(BlockId::Hash(hash)), index.value());
let result = self.transaction(id).and_then( let result = self.transaction(id).and_then(
errors::check_block_gap(&*self.client, self.options.allow_missing_blocks)); errors::check_block_gap(&*self.client, self.options.allow_missing_blocks));
Box::new(future::done(result)) Box::new(future::done(result))
@ -792,7 +787,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
fn uncle_by_block_hash_and_index(&self, hash: H256, index: Index) -> BoxFuture<Option<RichBlock>> { fn uncle_by_block_hash_and_index(&self, hash: H256, index: Index) -> BoxFuture<Option<RichBlock>> {
let result = self.uncle(PendingUncleId { let result = self.uncle(PendingUncleId {
id: PendingOrBlock::Block(BlockId::Hash(hash.into())), id: PendingOrBlock::Block(BlockId::Hash(hash)),
position: index.value() position: index.value()
}).and_then(errors::check_block_gap(&*self.client, self.options.allow_missing_blocks)); }).and_then(errors::check_block_gap(&*self.client, self.options.allow_missing_blocks));
Box::new(future::done(result)) Box::new(future::done(result))
@ -822,7 +817,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
} }
fn logs(&self, filter: Filter) -> BoxFuture<Vec<Log>> { fn logs(&self, filter: Filter) -> BoxFuture<Vec<Log>> {
base_logs(&*self.client, &*self.miner, filter.into()) base_logs(&*self.client, &*self.miner, filter)
} }
fn work(&self, no_new_work_timeout: Option<u64>) -> Result<Work> { fn work(&self, no_new_work_timeout: Option<u64>) -> Result<Work> {
@ -865,16 +860,16 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
Err(errors::no_new_work()) Err(errors::no_new_work())
} else if self.options.send_block_number_in_get_work { } else if self.options.send_block_number_in_get_work {
Ok(Work { Ok(Work {
pow_hash: pow_hash.into(), pow_hash,
seed_hash: seed_hash.into(), seed_hash: seed_hash.into(),
target: target.into(), target,
number: Some(number), number: Some(number),
}) })
} else { } else {
Ok(Work { Ok(Work {
pow_hash: pow_hash.into(), pow_hash,
seed_hash: seed_hash.into(), seed_hash: seed_hash.into(),
target: target.into(), target,
number: None number: None
}) })
} }
@ -888,7 +883,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
} }
fn submit_hashrate(&self, rate: U256, id: H256) -> Result<bool> { fn submit_hashrate(&self, rate: U256, id: H256) -> Result<bool> {
self.external_miner.submit_hashrate(rate.into(), id.into()); self.external_miner.submit_hashrate(rate, id);
Ok(true) Ok(true)
} }
@ -919,8 +914,8 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
let (mut state, header) = if num == BlockNumber::Pending { let (mut state, header) = if num == BlockNumber::Pending {
let info = self.client.chain_info(); let info = self.client.chain_info();
let state = try_bf!(self.miner.pending_state(info.best_block_number).ok_or(errors::state_pruned())); let state = try_bf!(self.miner.pending_state(info.best_block_number).ok_or_else(errors::state_pruned));
let header = try_bf!(self.miner.pending_block_header(info.best_block_number).ok_or(errors::state_pruned())); let header = try_bf!(self.miner.pending_block_header(info.best_block_number).ok_or_else(errors::state_pruned));
(state, header) (state, header)
} else { } else {
@ -931,8 +926,8 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
BlockNumber::Pending => unreachable!(), // Already covered BlockNumber::Pending => unreachable!(), // Already covered
}; };
let state = try_bf!(self.client.state_at(id).ok_or(errors::state_pruned())); let state = try_bf!(self.client.state_at(id).ok_or_else(errors::state_pruned));
let header = try_bf!(self.client.block_header(id).ok_or(errors::state_pruned()).and_then(|h| h.decode().map_err(errors::decode))); let header = try_bf!(self.client.block_header(id).ok_or_else(errors::state_pruned).and_then(|h| h.decode().map_err(errors::decode)));
(state, header) (state, header)
}; };
@ -958,8 +953,10 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
let (state, header) = if num == BlockNumber::Pending { let (state, header) = if num == BlockNumber::Pending {
let info = self.client.chain_info(); let info = self.client.chain_info();
let state = try_bf!(self.miner.pending_state(info.best_block_number).ok_or(errors::state_pruned())); let state = try_bf!(self.miner.pending_state(info.best_block_number)
let header = try_bf!(self.miner.pending_block_header(info.best_block_number).ok_or(errors::state_pruned())); .ok_or_else(errors::state_pruned));
let header = try_bf!(self.miner.pending_block_header(info.best_block_number)
.ok_or_else(errors::state_pruned));
(state, header) (state, header)
} else { } else {
@ -970,14 +967,15 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
BlockNumber::Pending => unreachable!(), // Already covered BlockNumber::Pending => unreachable!(), // Already covered
}; };
let state = try_bf!(self.client.state_at(id).ok_or(errors::state_pruned())); let state = try_bf!(self.client.state_at(id)
let header = try_bf!(self.client.block_header(id).ok_or(errors::state_pruned()).and_then(|h| h.decode().map_err(errors::decode))); .ok_or_else(errors::state_pruned));
let header = try_bf!(self.client.block_header(id)
.ok_or_else(errors::state_pruned)
.and_then(|h| h.decode().map_err(errors::decode)));
(state, header) (state, header)
}; };
Box::new(future::done(self.client.estimate_gas(&signed, &state, &header) Box::new(future::done(self.client.estimate_gas(&signed, &state, &header)
.map(Into::into)
.map_err(errors::call) .map_err(errors::call)
)) ))
} }

View File

@ -68,8 +68,8 @@ impl<C, M> EthFilterClient<C, M> {
/// Creates new Eth filter client. /// Creates new Eth filter client.
pub fn new(client: Arc<C>, miner: Arc<M>, poll_lifetime: u32) -> Self { pub fn new(client: Arc<C>, miner: Arc<M>, poll_lifetime: u32) -> Self {
EthFilterClient { EthFilterClient {
client: client, client,
miner: miner, miner,
polls: Mutex::new(PollManager::new(poll_lifetime)), polls: Mutex::new(PollManager::new(poll_lifetime)),
} }
} }
@ -188,17 +188,14 @@ impl<T: Filterable + Send + Sync + 'static> EthFilter for T {
let mut hashes = Vec::new(); let mut hashes = Vec::new();
for n in (*last_block_number + 1)..=current_number { for n in (*last_block_number + 1)..=current_number {
let block_number = BlockId::Number(n); let block_number = BlockId::Number(n);
match self.block_hash(block_number) { if let Some(hash) = self.block_hash(block_number) {
Some(hash) => { *last_block_number = n;
*last_block_number = n; hashes.push(hash);
hashes.push(H256::from(hash)); // Only keep the most recent history
// Only keep the most recent history if recent_reported_hashes.len() >= PollFilter::MAX_BLOCK_HISTORY_SIZE {
if recent_reported_hashes.len() >= PollFilter::MAX_BLOCK_HISTORY_SIZE { recent_reported_hashes.pop_back();
recent_reported_hashes.pop_back(); }
} recent_reported_hashes.push_front((n, hash));
recent_reported_hashes.push_front((n, hash));
},
None => (),
} }
} }

View File

@ -134,10 +134,10 @@ impl<C> ChainNotificationHandler<C> {
fn notify_heads(&self, headers: &[(encoded::Header, BTreeMap<String, String>)]) { fn notify_heads(&self, headers: &[(encoded::Header, BTreeMap<String, String>)]) {
for subscriber in self.heads_subscribers.read().values() { for subscriber in self.heads_subscribers.read().values() {
for &(ref header, ref extra_info) in headers { for &(ref header, ref extra_info) in headers {
Self::notify(&self.executor, subscriber, pubsub::Result::Header(RichHeader { Self::notify(&self.executor, subscriber, pubsub::Result::Header(Box::new(RichHeader {
inner: header.into(), inner: header.into(),
extra_info: extra_info.clone(), extra_info: extra_info.clone(),
})); })));
} }
} }
} }
@ -154,7 +154,7 @@ impl<C> ChainNotificationHandler<C> {
.map(|&(hash, ref ex)| { .map(|&(hash, ref ex)| {
let mut filter = filter.clone(); let mut filter = filter.clone();
filter.from_block = BlockId::Hash(hash); filter.from_block = BlockId::Hash(hash);
filter.to_block = filter.from_block.clone(); filter.to_block = filter.from_block;
logs(filter, ex).into_future() logs(filter, ex).into_future()
}) })
.collect::<Vec<_>>() .collect::<Vec<_>>()
@ -167,7 +167,7 @@ impl<C> ChainNotificationHandler<C> {
let logs = logs.into_iter().flat_map(|log| log).collect(); let logs = logs.into_iter().flat_map(|log| log).collect();
for log in limit_logs(logs, limit) { for log in limit_logs(logs, limit) {
Self::notify(&executor, &subscriber, pubsub::Result::Log(log)) Self::notify(&executor, &subscriber, pubsub::Result::Log(Box::new(log)))
} }
}) })
.map_err(|e| warn!("Unable to fetch latest logs: {:?}", e)) .map_err(|e| warn!("Unable to fetch latest logs: {:?}", e))
@ -179,7 +179,7 @@ impl<C> ChainNotificationHandler<C> {
pub fn notify_new_transactions(&self, hashes: &[H256]) { pub fn notify_new_transactions(&self, hashes: &[H256]) {
for subscriber in self.transactions_subscribers.read().values() { for subscriber in self.transactions_subscribers.read().values() {
for hash in hashes { for hash in hashes {
Self::notify(&self.executor, subscriber, pubsub::Result::TransactionHash((*hash).into())); Self::notify(&self.executor, subscriber, pubsub::Result::TransactionHash(*hash));
} }
} }
} }
@ -223,13 +223,13 @@ impl<C: LightClient> LightChainNotify for ChainNotificationHandler<C> {
impl<C: BlockChainClient> ChainNotify for ChainNotificationHandler<C> { impl<C: BlockChainClient> ChainNotify for ChainNotificationHandler<C> {
fn new_blocks(&self, new_blocks: NewBlocks) { fn new_blocks(&self, new_blocks: NewBlocks) {
if self.heads_subscribers.read().is_empty() && self.logs_subscribers.read().is_empty() { return } if self.heads_subscribers.read().is_empty() && self.logs_subscribers.read().is_empty() { return }
const EXTRA_INFO_PROOF: &'static str = "Object exists in in blockchain (fetched earlier), extra_info is always available if object exists; qed"; const EXTRA_INFO_PROOF: &str = "Object exists in in blockchain (fetched earlier), extra_info is always available if object exists; qed";
let headers = new_blocks.route.route() let headers = new_blocks.route.route()
.iter() .iter()
.filter_map(|&(hash, ref typ)| { .filter_map(|&(hash, ref typ)| {
match typ { match typ {
&ChainRouteType::Retracted => None, ChainRouteType::Retracted => None,
&ChainRouteType::Enacted => self.client.block_header(BlockId::Hash(hash)) ChainRouteType::Enacted => self.client.block_header(BlockId::Hash(hash))
} }
}) })
.map(|header| { .map(|header| {
@ -244,9 +244,9 @@ impl<C: BlockChainClient> ChainNotify for ChainNotificationHandler<C> {
// We notify logs enacting and retracting as the order in route. // We notify logs enacting and retracting as the order in route.
self.notify_logs(new_blocks.route.route(), |filter, ex| { self.notify_logs(new_blocks.route.route(), |filter, ex| {
match ex { match ex {
&ChainRouteType::Enacted => ChainRouteType::Enacted =>
Ok(self.client.logs(filter).unwrap_or_default().into_iter().map(Into::into).collect()), Ok(self.client.logs(filter).unwrap_or_default().into_iter().map(Into::into).collect()),
&ChainRouteType::Retracted => ChainRouteType::Retracted =>
Ok(self.client.logs(filter).unwrap_or_default().into_iter().map(Into::into).map(|mut log: Log| { Ok(self.client.logs(filter).unwrap_or_default().into_iter().map(Into::into).map(|mut log: Log| {
log.log_type = "removed".into(); log.log_type = "removed".into();
log.removed = true; log.removed = true;
@ -267,7 +267,7 @@ impl<C: Send + Sync + 'static> EthPubSub for EthPubSubClient<C> {
kind: pubsub::Kind, kind: pubsub::Kind,
params: Option<pubsub::Params>, params: Option<pubsub::Params>,
) { ) {
let error = match (kind, params.into()) { let error = match (kind, params) {
(pubsub::Kind::NewHeads, None) => { (pubsub::Kind::NewHeads, None) => {
self.heads_subscribers.write().push(subscriber); self.heads_subscribers.write().push(subscriber);
return; return;

View File

@ -142,23 +142,23 @@ where
let extra_info = engine.extra_info(&header); let extra_info = engine.extra_info(&header);
RichBlock { RichBlock {
inner: Block { inner: Block {
hash: Some(header.hash().into()), hash: Some(header.hash()),
size: Some(block.rlp().as_raw().len().into()), size: Some(block.rlp().as_raw().len().into()),
parent_hash: header.parent_hash().clone().into(), parent_hash: *header.parent_hash(),
uncles_hash: header.uncles_hash().clone().into(), uncles_hash: *header.uncles_hash(),
author: header.author().clone().into(), author: *header.author(),
miner: header.author().clone().into(), miner: *header.author(),
state_root: header.state_root().clone().into(), state_root: *header.state_root(),
transactions_root: header.transactions_root().clone().into(), transactions_root: *header.transactions_root(),
receipts_root: header.receipts_root().clone().into(), receipts_root: *header.receipts_root(),
number: Some(header.number().into()), number: Some(header.number().into()),
gas_used: header.gas_used().clone().into(), gas_used: *header.gas_used(),
gas_limit: header.gas_limit().clone().into(), gas_limit: *header.gas_limit(),
logs_bloom: Some(header.log_bloom().clone().into()), logs_bloom: Some(*header.log_bloom()),
timestamp: header.timestamp().into(), timestamp: header.timestamp().into(),
difficulty: header.difficulty().clone().into(), difficulty: *header.difficulty(),
total_difficulty: score.map(Into::into), total_difficulty: score.map(Into::into),
seal_fields: header.seal().into_iter().cloned().map(Into::into).collect(), seal_fields: header.seal().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(Transaction::from_localized).collect()), true => BlockTransactions::Full(block.view().localized_transactions().into_iter().map(Transaction::from_localized).collect()),
@ -166,7 +166,7 @@ where
}, },
extra_data: Bytes::new(header.extra_data().clone()), extra_data: Bytes::new(header.extra_data().clone()),
}, },
extra_info: extra_info extra_info,
} }
}; };
@ -237,9 +237,9 @@ where
.unwrap_or_else(|| current_block); .unwrap_or_else(|| current_block);
Ok(RpcSyncStatus::Info(RpcSyncInfo { Ok(RpcSyncStatus::Info(RpcSyncInfo {
starting_block: U256::from(self.sync.start_block()).into(), starting_block: U256::from(self.sync.start_block()),
current_block: current_block.into(), current_block,
highest_block: highest_block.into(), highest_block,
warp_chunks_amount: None, warp_chunks_amount: None,
warp_chunks_processed: None, warp_chunks_processed: None,
})) }))
@ -289,8 +289,8 @@ where
} }
fn balance(&self, address: H160, num: Option<BlockNumber>) -> BoxFuture<U256> { fn balance(&self, address: H160, num: Option<BlockNumber>) -> BoxFuture<U256> {
Box::new(self.fetcher().account(address.into(), num.unwrap_or_default().to_block_id()) Box::new(self.fetcher().account(address, num.unwrap_or_default().to_block_id())
.map(|acc| acc.map_or(0.into(), |a| a.balance).into())) .map(|acc| acc.map_or(0.into(), |a| a.balance)))
} }
fn storage_at(&self, _address: H160, _key: U256, _num: Option<BlockNumber>) -> BoxFuture<H256> { fn storage_at(&self, _address: H160, _key: U256, _num: Option<BlockNumber>) -> BoxFuture<H256> {
@ -298,7 +298,7 @@ where
} }
fn block_by_hash(&self, hash: H256, include_txs: bool) -> BoxFuture<Option<RichBlock>> { fn block_by_hash(&self, hash: H256, include_txs: bool) -> BoxFuture<Option<RichBlock>> {
Box::new(self.rich_block(BlockId::Hash(hash.into()), include_txs).map(Some)) Box::new(self.rich_block(BlockId::Hash(hash), include_txs).map(Some))
} }
fn block_by_number(&self, num: BlockNumber, include_txs: bool) -> BoxFuture<Option<RichBlock>> { fn block_by_number(&self, num: BlockNumber, include_txs: bool) -> BoxFuture<Option<RichBlock>> {
@ -306,20 +306,20 @@ where
} }
fn transaction_count(&self, address: H160, num: Option<BlockNumber>) -> BoxFuture<U256> { fn transaction_count(&self, address: H160, num: Option<BlockNumber>) -> BoxFuture<U256> {
Box::new(self.fetcher().account(address.into(), num.unwrap_or_default().to_block_id()) Box::new(self.fetcher().account(address, num.unwrap_or_default().to_block_id())
.map(|acc| acc.map_or(0.into(), |a| a.nonce).into())) .map(|acc| acc.map_or(0.into(), |a| a.nonce)))
} }
fn block_transaction_count_by_hash(&self, hash: H256) -> BoxFuture<Option<U256>> { fn block_transaction_count_by_hash(&self, hash: H256) -> BoxFuture<Option<U256>> {
let (sync, on_demand) = (self.sync.clone(), self.on_demand.clone()); let (sync, on_demand) = (self.sync.clone(), self.on_demand.clone());
Box::new(self.fetcher().header(BlockId::Hash(hash.into())).and_then(move |hdr| { Box::new(self.fetcher().header(BlockId::Hash(hash)).and_then(move |hdr| {
if hdr.transactions_root() == KECCAK_NULL_RLP { if hdr.transactions_root() == KECCAK_NULL_RLP {
Either::A(future::ok(Some(U256::from(0).into()))) Either::A(future::ok(Some(U256::from(0))))
} else { } else {
sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into()))) sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into())))
.map(|x| x.expect(NO_INVALID_BACK_REFS)) .map(|x| x.expect(NO_INVALID_BACK_REFS))
.map(|x| x.map(|b| Some(U256::from(b.transactions_count()).into()))) .map(|x| x.map(|b| Some(U256::from(b.transactions_count()))))
.map(|x| Either::B(x.map_err(errors::on_demand_error))) .map(|x| Either::B(x.map_err(errors::on_demand_error)))
.unwrap_or_else(|| Either::A(future::err(errors::network_disabled()))) .unwrap_or_else(|| Either::A(future::err(errors::network_disabled())))
} }
@ -331,11 +331,11 @@ where
Box::new(self.fetcher().header(num.to_block_id()).and_then(move |hdr| { Box::new(self.fetcher().header(num.to_block_id()).and_then(move |hdr| {
if hdr.transactions_root() == KECCAK_NULL_RLP { if hdr.transactions_root() == KECCAK_NULL_RLP {
Either::A(future::ok(Some(U256::from(0).into()))) Either::A(future::ok(Some(U256::from(0))))
} else { } else {
sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into()))) sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into())))
.map(|x| x.expect(NO_INVALID_BACK_REFS)) .map(|x| x.expect(NO_INVALID_BACK_REFS))
.map(|x| x.map(|b| Some(U256::from(b.transactions_count()).into()))) .map(|x| x.map(|b| Some(U256::from(b.transactions_count()))))
.map(|x| Either::B(x.map_err(errors::on_demand_error))) .map(|x| Either::B(x.map_err(errors::on_demand_error)))
.unwrap_or_else(|| Either::A(future::err(errors::network_disabled()))) .unwrap_or_else(|| Either::A(future::err(errors::network_disabled())))
} }
@ -345,13 +345,13 @@ where
fn block_uncles_count_by_hash(&self, hash: H256) -> BoxFuture<Option<U256>> { fn block_uncles_count_by_hash(&self, hash: H256) -> BoxFuture<Option<U256>> {
let (sync, on_demand) = (self.sync.clone(), self.on_demand.clone()); let (sync, on_demand) = (self.sync.clone(), self.on_demand.clone());
Box::new(self.fetcher().header(BlockId::Hash(hash.into())).and_then(move |hdr| { Box::new(self.fetcher().header(BlockId::Hash(hash)).and_then(move |hdr| {
if hdr.uncles_hash() == KECCAK_EMPTY_LIST_RLP { if hdr.uncles_hash() == KECCAK_EMPTY_LIST_RLP {
Either::A(future::ok(Some(U256::from(0).into()))) Either::A(future::ok(Some(U256::from(0))))
} else { } else {
sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into()))) sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into())))
.map(|x| x.expect(NO_INVALID_BACK_REFS)) .map(|x| x.expect(NO_INVALID_BACK_REFS))
.map(|x| x.map(|b| Some(U256::from(b.uncles_count()).into()))) .map(|x| x.map(|b| Some(U256::from(b.uncles_count()))))
.map(|x| Either::B(x.map_err(errors::on_demand_error))) .map(|x| Either::B(x.map_err(errors::on_demand_error)))
.unwrap_or_else(|| Either::A(future::err(errors::network_disabled()))) .unwrap_or_else(|| Either::A(future::err(errors::network_disabled())))
} }
@ -363,11 +363,11 @@ where
Box::new(self.fetcher().header(num.to_block_id()).and_then(move |hdr| { Box::new(self.fetcher().header(num.to_block_id()).and_then(move |hdr| {
if hdr.uncles_hash() == KECCAK_EMPTY_LIST_RLP { if hdr.uncles_hash() == KECCAK_EMPTY_LIST_RLP {
Either::B(future::ok(Some(U256::from(0).into()))) Either::B(future::ok(Some(U256::from(0))))
} else { } else {
sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into()))) sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into())))
.map(|x| x.expect(NO_INVALID_BACK_REFS)) .map(|x| x.expect(NO_INVALID_BACK_REFS))
.map(|x| x.map(|b| Some(U256::from(b.uncles_count()).into()))) .map(|x| x.map(|b| Some(U256::from(b.uncles_count()))))
.map(|x| Either::A(x.map_err(errors::on_demand_error))) .map(|x| Either::A(x.map_err(errors::on_demand_error)))
.unwrap_or_else(|| Either::B(future::err(errors::network_disabled()))) .unwrap_or_else(|| Either::B(future::err(errors::network_disabled())))
} }
@ -375,7 +375,7 @@ where
} }
fn code_at(&self, address: H160, num: Option<BlockNumber>) -> BoxFuture<Bytes> { fn code_at(&self, address: H160, num: Option<BlockNumber>) -> BoxFuture<Bytes> {
Box::new(self.fetcher().code(address.into(), num.unwrap_or_default().to_block_id()).map(Into::into)) Box::new(self.fetcher().code(address, num.unwrap_or_default().to_block_id()).map(Into::into))
} }
fn send_raw_transaction(&self, raw: Bytes) -> Result<H256> { fn send_raw_transaction(&self, raw: Bytes) -> Result<H256> {
@ -414,15 +414,13 @@ where
// TODO: binary chop for more accurate estimates. // TODO: binary chop for more accurate estimates.
Box::new(self.fetcher().proved_read_only_execution(req, num).and_then(|res| { Box::new(self.fetcher().proved_read_only_execution(req, num).and_then(|res| {
match res { match res {
Ok(exec) => Ok((exec.refunded + exec.gas_used).into()), Ok(exec) => Ok(exec.refunded + exec.gas_used),
Err(e) => Err(errors::execution(e)), Err(e) => Err(errors::execution(e)),
} }
})) }))
} }
fn transaction_by_hash(&self, hash: H256) -> BoxFuture<Option<Transaction>> { fn transaction_by_hash(&self, hash: H256) -> BoxFuture<Option<Transaction>> {
let hash = hash.into();
{ {
let tx_queue = self.transaction_queue.read(); let tx_queue = self.transaction_queue.read();
if let Some(tx) = tx_queue.get(&hash) { if let Some(tx) = tx_queue.get(&hash) {
@ -436,7 +434,7 @@ where
} }
fn transaction_by_block_hash_and_index(&self, hash: H256, idx: Index) -> BoxFuture<Option<Transaction>> { fn transaction_by_block_hash_and_index(&self, hash: H256, idx: Index) -> BoxFuture<Option<Transaction>> {
Box::new(self.fetcher().block(BlockId::Hash(hash.into())).map(move |block| { Box::new(self.fetcher().block(BlockId::Hash(hash)).map(move |block| {
light_fetch::extract_transaction_at_index(block, idx.value()) light_fetch::extract_transaction_at_index(block, idx.value())
})) }))
} }
@ -449,14 +447,14 @@ where
fn transaction_receipt(&self, hash: H256) -> BoxFuture<Option<Receipt>> { fn transaction_receipt(&self, hash: H256) -> BoxFuture<Option<Receipt>> {
let fetcher = self.fetcher(); let fetcher = self.fetcher();
Box::new(fetcher.transaction_by_hash(hash.into()).and_then(move |tx| { Box::new(fetcher.transaction_by_hash(hash).and_then(move |tx| {
// the block hash included in the transaction object here has // the block hash included in the transaction object here has
// already been checked for canonicality and whether it contains // already been checked for canonicality and whether it contains
// the transaction. // the transaction.
match tx { match tx {
Some((tx, index)) => match tx.block_hash.clone() { Some((tx, index)) => match tx.block_hash {
Some(block_hash) => { Some(block_hash) => {
let extract_receipt = fetcher.receipts(BlockId::Hash(block_hash.clone().into())) let extract_receipt = fetcher.receipts(BlockId::Hash(block_hash))
.and_then(move |mut receipts| future::ok(receipts.swap_remove(index))) .and_then(move |mut receipts| future::ok(receipts.swap_remove(index)))
.map(Receipt::from) .map(Receipt::from)
.map(move |mut receipt| { .map(move |mut receipt| {
@ -479,7 +477,7 @@ where
fn uncle_by_block_hash_and_index(&self, hash: H256, idx: Index) -> BoxFuture<Option<RichBlock>> { fn uncle_by_block_hash_and_index(&self, hash: H256, idx: Index) -> BoxFuture<Option<RichBlock>> {
let client = self.client.clone(); let client = self.client.clone();
Box::new(self.fetcher().block(BlockId::Hash(hash.into())).map(move |block| { Box::new(self.fetcher().block(BlockId::Hash(hash)).map(move |block| {
extract_uncle_at_index(block, idx, client) extract_uncle_at_index(block, idx, client)
})) }))
} }
@ -576,27 +574,27 @@ fn extract_uncle_at_index<T: LightChainClient>(block: encoded::Block, index: Ind
let extra_info = client.engine().extra_info(&uncle); let extra_info = client.engine().extra_info(&uncle);
Some(RichBlock { Some(RichBlock {
inner: Block { inner: Block {
hash: Some(uncle.hash().into()), hash: Some(uncle.hash()),
size: None, size: None,
parent_hash: uncle.parent_hash().clone().into(), parent_hash: *uncle.parent_hash(),
uncles_hash: uncle.uncles_hash().clone().into(), uncles_hash: *uncle.uncles_hash(),
author: uncle.author().clone().into(), author: *uncle.author(),
miner: uncle.author().clone().into(), miner: *uncle.author(),
state_root: uncle.state_root().clone().into(), state_root: *uncle.state_root(),
transactions_root: uncle.transactions_root().clone().into(), transactions_root: *uncle.transactions_root(),
number: Some(uncle.number().into()), number: Some(uncle.number().into()),
gas_used: uncle.gas_used().clone().into(), gas_used: *uncle.gas_used(),
gas_limit: uncle.gas_limit().clone().into(), gas_limit: *uncle.gas_limit(),
logs_bloom: Some(uncle.log_bloom().clone().into()), logs_bloom: Some(*uncle.log_bloom()),
timestamp: uncle.timestamp().into(), timestamp: uncle.timestamp().into(),
difficulty: uncle.difficulty().clone().into(), difficulty: *uncle.difficulty(),
total_difficulty: None, total_difficulty: None,
receipts_root: uncle.receipts_root().clone().into(), receipts_root: *uncle.receipts_root(),
extra_data: uncle.extra_data().clone().into(), extra_data: uncle.extra_data().clone().into(),
seal_fields: uncle.seal().into_iter().cloned().map(Into::into).collect(), seal_fields: uncle.seal().iter().cloned().map(Into::into).collect(),
uncles: vec![], uncles: vec![],
transactions: BlockTransactions::Hashes(vec![]), transactions: BlockTransactions::Hashes(vec![]),
}, },
extra_info: extra_info, extra_info,
}) })
} }

View File

@ -29,7 +29,7 @@ impl<S: ?Sized> NetClient<S> where S: LightSyncProvider {
/// Creates new NetClient. /// Creates new NetClient.
pub fn new(sync: Arc<S>) -> Self { pub fn new(sync: Arc<S>) -> Self {
NetClient { NetClient {
sync: sync, sync,
} }
} }
} }

View File

@ -140,7 +140,7 @@ where
active: peer_numbers.active, active: peer_numbers.active,
connected: peer_numbers.connected, connected: peer_numbers.connected,
max: peer_numbers.max as u32, max: peer_numbers.max as u32,
peers: peers, peers,
}) })
} }
@ -157,7 +157,7 @@ where
if reg == Default::default() { if reg == Default::default() {
Ok(None) Ok(None)
} else { } else {
Ok(Some(reg.into())) Ok(Some(reg))
} }
} }
@ -191,7 +191,7 @@ where
} }
fn phrase_to_address(&self, phrase: String) -> Result<H160> { fn phrase_to_address(&self, phrase: String) -> Result<H160> {
Ok(Brain::new(phrase).generate().unwrap().address().into()) Ok(Brain::new(phrase).generate().expect("Brain::generate always returns Ok; qed").address())
} }
fn list_accounts(&self, _: u64, _: Option<H160>, _: Option<BlockNumber>) -> Result<Option<Vec<H160>>> { fn list_accounts(&self, _: u64, _: Option<H160>, _: Option<BlockNumber>) -> Result<Option<Vec<H160>>> {
@ -203,7 +203,7 @@ where
} }
fn encrypt_message(&self, key: H512, phrase: Bytes) -> Result<Bytes> { fn encrypt_message(&self, key: H512, phrase: Bytes) -> Result<Bytes> {
ecies::encrypt(&key.into(), &DEFAULT_MAC, &phrase.0) ecies::encrypt(&key, &DEFAULT_MAC, &phrase.0)
.map_err(errors::encryption) .map_err(errors::encryption)
.map(Into::into) .map(Into::into)
} }
@ -215,7 +215,7 @@ where
txq.ready_transactions(chain_info.best_block_number, chain_info.best_block_timestamp) txq.ready_transactions(chain_info.best_block_number, chain_info.best_block_timestamp)
.into_iter() .into_iter()
.take(limit.unwrap_or_else(usize::max_value)) .take(limit.unwrap_or_else(usize::max_value))
.map(|tx| Transaction::from_pending(tx)) .map(Transaction::from_pending)
.collect::<Vec<_>>() .collect::<Vec<_>>()
) )
} }
@ -223,7 +223,7 @@ where
fn all_transactions(&self) -> Result<Vec<Transaction>> { fn all_transactions(&self) -> Result<Vec<Transaction>> {
Ok( Ok(
light_all_transactions(&self.light_dispatch) light_all_transactions(&self.light_dispatch)
.map(|tx| Transaction::from_pending(tx)) .map(Transaction::from_pending)
.collect() .collect()
) )
} }
@ -231,7 +231,7 @@ where
fn all_transaction_hashes(&self) -> Result<Vec<H256>> { fn all_transaction_hashes(&self) -> Result<Vec<H256>> {
Ok( Ok(
light_all_transactions(&self.light_dispatch) light_all_transactions(&self.light_dispatch)
.map(|tx| tx.transaction.hash().into()) .map(|tx| tx.transaction.hash())
.collect() .collect()
) )
} }
@ -242,7 +242,7 @@ where
Ok( Ok(
txq.future_transactions(chain_info.best_block_number, chain_info.best_block_timestamp) txq.future_transactions(chain_info.best_block_number, chain_info.best_block_timestamp)
.into_iter() .into_iter()
.map(|tx| Transaction::from_pending(tx)) .map(Transaction::from_pending)
.collect::<Vec<_>>() .collect::<Vec<_>>()
) )
} }
@ -250,7 +250,7 @@ where
fn pending_transactions_stats(&self) -> Result<BTreeMap<H256, TransactionStats>> { fn pending_transactions_stats(&self) -> Result<BTreeMap<H256, TransactionStats>> {
let stats = self.light_dispatch.sync.transactions_stats(); let stats = self.light_dispatch.sync.transactions_stats();
Ok(stats.into_iter() Ok(stats.into_iter()
.map(|(hash, stats)| (hash.into(), stats.into())) .map(|(hash, stats)| (hash, stats.into()))
.collect() .collect()
) )
} }
@ -262,11 +262,11 @@ where
let txq = self.light_dispatch.transaction_queue.read(); let txq = self.light_dispatch.transaction_queue.read();
for pending in txq.ready_transactions(best_num, best_tm) { for pending in txq.ready_transactions(best_num, best_tm) {
map.insert(pending.hash().into(), LocalTransactionStatus::Pending); map.insert(pending.hash(), LocalTransactionStatus::Pending);
} }
for future in txq.future_transactions(best_num, best_tm) { for future in txq.future_transactions(best_num, best_tm) {
map.insert(future.hash().into(), LocalTransactionStatus::Future); map.insert(future.hash(), LocalTransactionStatus::Future);
} }
// TODO: other types? // TODO: other types?
@ -276,11 +276,11 @@ where
fn ws_url(&self) -> Result<String> { fn ws_url(&self) -> Result<String> {
helpers::to_url(&self.ws_address) helpers::to_url(&self.ws_address)
.ok_or_else(|| errors::ws_disabled()) .ok_or_else(errors::ws_disabled)
} }
fn next_nonce(&self, address: H160) -> BoxFuture<U256> { fn next_nonce(&self, address: H160) -> BoxFuture<U256> {
Box::new(self.light_dispatch.next_nonce(address.into()).map(Into::into)) Box::new(self.light_dispatch.next_nonce(address))
} }
fn mode(&self) -> Result<String> { fn mode(&self) -> Result<String> {
@ -314,7 +314,7 @@ where
.and_then(|first| chain_info.first_block_number.map(|last| (first, U256::from(last)))); .and_then(|first| chain_info.first_block_number.map(|last| (first, U256::from(last))));
Ok(ChainStatus { Ok(ChainStatus {
block_gap: gap.map(|(x, y)| (x.into(), y.into())), block_gap: gap,
}) })
} }
@ -336,25 +336,25 @@ where
let extra_info = engine.extra_info(&header); let extra_info = engine.extra_info(&header);
Ok(RichHeader { Ok(RichHeader {
inner: Header { inner: Header {
hash: Some(header.hash().into()), hash: Some(header.hash()),
size: Some(encoded.rlp().as_raw().len().into()), size: Some(encoded.rlp().as_raw().len().into()),
parent_hash: header.parent_hash().clone().into(), parent_hash: *header.parent_hash(),
uncles_hash: header.uncles_hash().clone().into(), uncles_hash: *header.uncles_hash(),
author: header.author().clone().into(), author: *header.author(),
miner: header.author().clone().into(), miner: *header.author(),
state_root: header.state_root().clone().into(), state_root: *header.state_root(),
transactions_root: header.transactions_root().clone().into(), transactions_root: *header.transactions_root(),
receipts_root: header.receipts_root().clone().into(), receipts_root: *header.receipts_root(),
number: Some(header.number().into()), number: Some(header.number().into()),
gas_used: header.gas_used().clone().into(), gas_used: *header.gas_used(),
gas_limit: header.gas_limit().clone().into(), gas_limit: *header.gas_limit(),
logs_bloom: header.log_bloom().clone().into(), logs_bloom: *header.log_bloom(),
timestamp: header.timestamp().into(), timestamp: header.timestamp().into(),
difficulty: header.difficulty().clone().into(), difficulty: *header.difficulty(),
seal_fields: header.seal().iter().cloned().map(Into::into).collect(), seal_fields: header.seal().iter().cloned().map(Into::into).collect(),
extra_data: Bytes::new(header.extra_data().clone()), extra_data: Bytes::new(header.extra_data().clone()),
}, },
extra_info: extra_info, extra_info,
}) })
}; };
let id = number.unwrap_or_default().to_block_id(); let id = number.unwrap_or_default().to_block_id();

View File

@ -43,9 +43,9 @@ impl<F: Fetch> ParitySetClient<F> {
/// Creates new `ParitySetClient` with given `Fetch`. /// Creates new `ParitySetClient` with given `Fetch`.
pub fn new(client: Arc<LightChainClient>, net: Arc<ManageNetwork>, fetch: F) -> Self { pub fn new(client: Arc<LightChainClient>, net: Arc<ManageNetwork>, fetch: F) -> Self {
ParitySetClient { ParitySetClient {
client: client, client,
net: net, net,
fetch: fetch, fetch,
} }
} }
} }

View File

@ -109,7 +109,7 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
} }
fn min_gas_price(&self) -> Result<U256> { fn min_gas_price(&self) -> Result<U256> {
Ok(self.miner.queue_status().options.minimal_gas_price.into()) Ok(self.miner.queue_status().options.minimal_gas_price)
} }
fn extra_data(&self) -> Result<Bytes> { fn extra_data(&self) -> Result<Bytes> {
@ -117,11 +117,11 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
} }
fn gas_floor_target(&self) -> Result<U256> { fn gas_floor_target(&self) -> Result<U256> {
Ok(U256::from(self.miner.authoring_params().gas_range_target.0)) Ok(self.miner.authoring_params().gas_range_target.0)
} }
fn gas_ceil_target(&self) -> Result<U256> { fn gas_ceil_target(&self) -> Result<U256> {
Ok(U256::from(self.miner.authoring_params().gas_range_target.1)) Ok(self.miner.authoring_params().gas_range_target.1)
} }
fn dev_logs(&self) -> Result<Vec<String>> { fn dev_logs(&self) -> Result<Vec<String>> {
@ -152,7 +152,7 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
active: sync_status.num_active_peers, active: sync_status.num_active_peers,
connected: sync_status.num_peers, connected: sync_status.num_peers,
max: sync_status.current_max_peers(*num_peers_range.start(), *num_peers_range.end()), max: sync_status.current_max_peers(*num_peers_range.start(), *num_peers_range.end()),
peers: peers peers,
}) })
} }
@ -170,7 +170,6 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
.additional_params() .additional_params()
.get("registrar") .get("registrar")
.and_then(|s| Address::from_str(s).ok()) .and_then(|s| Address::from_str(s).ok())
.map(|s| H160::from(s))
) )
} }
@ -207,7 +206,7 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
} }
fn phrase_to_address(&self, phrase: String) -> Result<H160> { fn phrase_to_address(&self, phrase: String) -> Result<H160> {
Ok(Brain::new(phrase).generate().unwrap().address().into()) Ok(Brain::new(phrase).generate().expect("Brain::generate always returns Ok; qed").address())
} }
fn list_accounts(&self, count: u64, after: Option<H160>, block_number: Option<BlockNumber>) -> Result<Option<Vec<H160>>> { fn list_accounts(&self, count: u64, after: Option<H160>, block_number: Option<BlockNumber>) -> Result<Option<Vec<H160>>> {
@ -236,12 +235,12 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
}; };
Ok(self.client Ok(self.client
.list_storage(number, &address.into(), after.map(Into::into).as_ref(), count) .list_storage(number, &address, after.map(Into::into).as_ref(), count)
.map(|a| a.into_iter().map(Into::into).collect())) .map(|a| a.into_iter().map(Into::into).collect()))
} }
fn encrypt_message(&self, key: H512, phrase: Bytes) -> Result<Bytes> { fn encrypt_message(&self, key: H512, phrase: Bytes) -> Result<Bytes> {
ecies::encrypt(&key.into(), &DEFAULT_MAC, &phrase.0) ecies::encrypt(&key, &DEFAULT_MAC, &phrase.0)
.map_err(errors::encryption) .map_err(errors::encryption)
.map(Into::into) .map(Into::into)
} }
@ -271,13 +270,7 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
} }
fn all_transaction_hashes(&self) -> Result<Vec<H256>> { fn all_transaction_hashes(&self) -> Result<Vec<H256>> {
let all_transaction_hashes = self.miner.queued_transaction_hashes(); Ok(self.miner.queued_transaction_hashes())
Ok(all_transaction_hashes
.into_iter()
.map(|hash| hash.into())
.collect()
)
} }
fn future_transactions(&self) -> Result<Vec<Transaction>> { fn future_transactions(&self) -> Result<Vec<Transaction>> {
@ -287,7 +280,7 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
fn pending_transactions_stats(&self) -> Result<BTreeMap<H256, TransactionStats>> { fn pending_transactions_stats(&self) -> Result<BTreeMap<H256, TransactionStats>> {
let stats = self.sync.transactions_stats(); let stats = self.sync.transactions_stats();
Ok(stats.into_iter() Ok(stats.into_iter()
.map(|(hash, stats)| (hash.into(), stats.into())) .map(|(hash, stats)| (hash, stats.into()))
.collect() .collect()
) )
} }
@ -296,7 +289,7 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
let transactions = self.miner.local_transactions(); let transactions = self.miner.local_transactions();
Ok(transactions Ok(transactions
.into_iter() .into_iter()
.map(|(hash, status)| (hash.into(), LocalTransactionStatus::from(status))) .map(|(hash, status)| (hash, LocalTransactionStatus::from(status)))
.collect() .collect()
) )
} }
@ -307,9 +300,7 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
} }
fn next_nonce(&self, address: H160) -> BoxFuture<U256> { fn next_nonce(&self, address: H160) -> BoxFuture<U256> {
let address: Address = address.into(); Box::new(future::ok(self.miner.next_nonce(&*self.client, &address)))
Box::new(future::ok(self.miner.next_nonce(&*self.client, &address).into()))
} }
fn mode(&self) -> Result<String> { fn mode(&self) -> Result<String> {
@ -339,7 +330,7 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
.and_then(|first| chain_info.first_block_number.map(|last| (first, U256::from(last)))); .and_then(|first| chain_info.first_block_number.map(|last| (first, U256::from(last))));
Ok(ChainStatus { Ok(ChainStatus {
block_gap: gap.map(|(x, y)| (x.into(), y.into())), block_gap: gap,
}) })
} }
@ -370,7 +361,7 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
BlockNumber::Pending => unreachable!(), // Already covered BlockNumber::Pending => unreachable!(), // Already covered
}; };
let header = try_bf!(self.client.block_header(id.clone()).ok_or_else(errors::unknown_block)); let header = try_bf!(self.client.block_header(id).ok_or_else(errors::unknown_block));
let info = self.client.block_extra_info(id).expect(EXTRA_INFO_PROOF); let info = self.client.block_extra_info(id).expect(EXTRA_INFO_PROOF);
(header, Some(info)) (header, Some(info))
@ -467,7 +458,7 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
fn logs_no_tx_hash(&self, filter: Filter) -> BoxFuture<Vec<Log>> { fn logs_no_tx_hash(&self, filter: Filter) -> BoxFuture<Vec<Log>> {
use v1::impls::eth::base_logs; use v1::impls::eth::base_logs;
// only specific impl for lightclient // only specific impl for lightclient
base_logs(&*self.client, &*self.miner, filter.into()) base_logs(&*self.client, &*self.miner, filter)
} }
fn verify_signature(&self, is_prefixed: bool, message: Bytes, r: H256, s: H256, v: U64) -> Result<RecoveredAccount> { fn verify_signature(&self, is_prefixed: bool, message: Bytes, r: H256, s: H256, v: U64) -> Result<RecoveredAccount> {

View File

@ -119,7 +119,7 @@ impl<C, M, U, F> ParitySet for ParitySetClient<C, M, U, F> where
{ {
fn set_min_gas_price(&self, gas_price: U256) -> Result<bool> { fn set_min_gas_price(&self, gas_price: U256) -> Result<bool> {
match self.miner.set_minimal_gas_price(gas_price.into()) { match self.miner.set_minimal_gas_price(gas_price) {
Ok(success) => Ok(success), Ok(success) => Ok(success),
Err(e) => Err(errors::unsupported(e, None)), Err(e) => Err(errors::unsupported(e, None)),
} }
@ -136,15 +136,15 @@ impl<C, M, U, F> ParitySet for ParitySetClient<C, M, U, F> where
} }
fn set_gas_floor_target(&self, target: U256) -> Result<bool> { fn set_gas_floor_target(&self, target: U256) -> Result<bool> {
let mut range = self.miner.authoring_params().gas_range_target.clone(); let mut range = self.miner.authoring_params().gas_range_target;
range.0 = target.into(); range.0 = target;
self.miner.set_gas_range_target(range); self.miner.set_gas_range_target(range);
Ok(true) Ok(true)
} }
fn set_gas_ceil_target(&self, target: U256) -> Result<bool> { fn set_gas_ceil_target(&self, target: U256) -> Result<bool> {
let mut range = self.miner.authoring_params().gas_range_target.clone(); let mut range = self.miner.authoring_params().gas_range_target;
range.1 = target.into(); range.1 = target;
self.miner.set_gas_range_target(range); self.miner.set_gas_range_target(range);
Ok(true) Ok(true)
} }
@ -155,7 +155,7 @@ impl<C, M, U, F> ParitySet for ParitySetClient<C, M, U, F> where
} }
fn set_author(&self, address: H160) -> Result<bool> { fn set_author(&self, address: H160) -> Result<bool> {
self.miner.set_author(miner::Author::External(address.into())); self.miner.set_author(miner::Author::External(address));
Ok(true) Ok(true)
} }
@ -236,8 +236,6 @@ impl<C, M, U, F> ParitySet for ParitySetClient<C, M, U, F> where
} }
fn remove_transaction(&self, hash: H256) -> Result<Option<Transaction>> { fn remove_transaction(&self, hash: H256) -> Result<Option<Transaction>> {
let hash = hash.into();
Ok(self.miner.remove_transaction(&hash) Ok(self.miner.remove_transaction(&hash)
.map(|t| Transaction::from_pending(t.pending().clone())) .map(|t| Transaction::from_pending(t.pending().clone()))
) )

View File

@ -60,7 +60,7 @@ impl Private for PrivateClient {
.map_err(errors::rlp) .map_err(errors::rlp)
.and_then(|tx| SignedTransaction::new(tx).map_err(errors::transaction))?; .and_then(|tx| SignedTransaction::new(tx).map_err(errors::transaction))?;
let client = self.unwrap_manager()?; let client = self.unwrap_manager()?;
let receipt = client.create_private_transaction(signed_transaction).map_err(|e| errors::private_message(e))?; let receipt = client.create_private_transaction(signed_transaction).map_err(errors::private_message)?;
Ok(receipt.into()) Ok(receipt.into())
} }
@ -76,16 +76,17 @@ impl Private for PrivateClient {
num => block_number_to_id(num) num => block_number_to_id(num)
}; };
let (transaction, contract_address) = client.public_creation_transaction(id, &signed_transaction, addresses.as_slice(), gas_price.into()) let (transaction, contract_address) = client
.map_err(|e| errors::private_message(e))?; .public_creation_transaction(id, &signed_transaction, addresses.as_slice(), gas_price)
.map_err(errors::private_message)?;
let tx_hash = transaction.hash(None); let tx_hash = transaction.hash(None);
let request = TransactionRequest { let request = TransactionRequest {
from: Some(signed_transaction.sender().into()), from: Some(signed_transaction.sender()),
to: None, to: None,
nonce: Some(transaction.nonce.into()), nonce: Some(transaction.nonce),
gas_price: Some(transaction.gas_price.into()), gas_price: Some(transaction.gas_price),
gas: Some(transaction.gas.into()), gas: Some(transaction.gas),
value: Some(transaction.value.into()), value: Some(transaction.value),
data: Some(transaction.data.into()), data: Some(transaction.data.into()),
condition: None, condition: None,
}; };
@ -93,8 +94,8 @@ impl Private for PrivateClient {
Ok(PrivateTransactionReceiptAndTransaction { Ok(PrivateTransactionReceiptAndTransaction {
transaction: request, transaction: request,
receipt: PrivateTransactionReceipt { receipt: PrivateTransactionReceipt {
transaction_hash: tx_hash.into(), transaction_hash: tx_hash,
contract_address: contract_address.into(), contract_address,
status_code: 0, status_code: 0,
} }
}) })
@ -109,13 +110,13 @@ impl Private for PrivateClient {
let request = CallRequest::into(request); let request = CallRequest::into(request);
let signed = fake_sign::sign_call(request)?; let signed = fake_sign::sign_call(request)?;
let client = self.unwrap_manager()?; let client = self.unwrap_manager()?;
let executed_result = client.private_call(id, &signed).map_err(|e| errors::private_message(e))?; let executed_result = client.private_call(id, &signed).map_err(errors::private_message)?;
Ok(executed_result.output.into()) Ok(executed_result.output.into())
} }
fn private_contract_key(&self, contract_address: H160) -> Result<H256, Error> { fn private_contract_key(&self, contract_address: H160) -> Result<H256, Error> {
let client = self.unwrap_manager()?; let client = self.unwrap_manager()?;
let key = client.contract_key_id(&contract_address.into()).map_err(|e| errors::private_message(e))?; let key = client.contract_key_id(&contract_address).map_err(errors::private_message)?;
Ok(key.into()) Ok(key)
} }
} }

View File

@ -81,7 +81,7 @@ impl<S: core::Middleware<Metadata>> PubSub for PubSubClient<S> {
type Metadata = Metadata; type Metadata = Metadata;
fn parity_subscribe(&self, mut meta: Metadata, subscriber: Subscriber<core::Value>, method: String, params: Option<core::Params>) { fn parity_subscribe(&self, mut meta: Metadata, subscriber: Subscriber<core::Value>, method: String, params: Option<core::Params>) {
let params = params.unwrap_or(core::Params::Array(vec![])); let params = params.unwrap_or_else(|| core::Params::Array(vec![]));
// Make sure to get rid of PubSub session otherwise it will never be dropped. // Make sure to get rid of PubSub session otherwise it will never be dropped.
meta.session = None; meta.session = None;

View File

@ -32,8 +32,8 @@ impl RpcClient {
let valid_apis = vec!["web3", "eth", "net", "personal", "rpc"]; let valid_apis = vec!["web3", "eth", "net", "personal", "rpc"];
RpcClient { RpcClient {
modules: modules, modules,
valid_apis: valid_apis.into_iter().map(|x| x.to_owned()).collect(), valid_apis: valid_apis.into_iter().map(ToOwned::to_owned).collect(),
} }
} }
} }

View File

@ -85,7 +85,6 @@ impl<D: Dispatcher + 'static> SignerClient<D> {
T: IntoFuture<Item=WithToken<ConfirmationResponse>, Error=Error>, T: IntoFuture<Item=WithToken<ConfirmationResponse>, Error=Error>,
T::Future: Send + 'static T::Future: Send + 'static
{ {
let id = id.into();
let dispatcher = self.dispatcher.clone(); let dispatcher = self.dispatcher.clone();
let signer = self.signer.clone(); let signer = self.signer.clone();
@ -94,15 +93,15 @@ impl<D: Dispatcher + 'static> SignerClient<D> {
// Modify payload // Modify payload
if let ConfirmationPayload::SendTransaction(ref mut request) = payload { if let ConfirmationPayload::SendTransaction(ref mut request) = payload {
if let Some(sender) = modification.sender { if let Some(sender) = modification.sender {
request.from = sender.into(); request.from = sender;
// Altering sender should always reset the nonce. // Altering sender should always reset the nonce.
request.nonce = None; request.nonce = None;
} }
if let Some(gas_price) = modification.gas_price { if let Some(gas_price) = modification.gas_price {
request.gas_price = gas_price.into(); request.gas_price = gas_price;
} }
if let Some(gas) = modification.gas { if let Some(gas) = modification.gas {
request.gas = gas.into(); request.gas = gas;
} }
if let Some(ref condition) = modification.condition { if let Some(ref condition) = modification.condition {
request.condition = condition.clone().map(Into::into); request.condition = condition.clone().map(Into::into);
@ -177,7 +176,7 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
Box::new(self.confirm_internal(id, modification, move |dis, accounts, payload| { Box::new(self.confirm_internal(id, modification, move |dis, accounts, payload| {
dispatch::execute(dis, accounts, payload, dispatch::SignWith::Password(pass.into())) dispatch::execute(dis, accounts, payload, dispatch::SignWith::Password(pass.into()))
}).map(|v| v.into_value())) }).map(dispatch::WithToken::into_value))
} }
fn confirm_request_with_token(&self, id: U256, modification: TransactionModification, token: String) fn confirm_request_with_token(&self, id: U256, modification: TransactionModification, token: String)
@ -191,7 +190,7 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
WithToken::No(_) => Err(errors::internal("Unexpected response without token.", "")), WithToken::No(_) => Err(errors::internal("Unexpected response without token.", "")),
WithToken::Yes(response, token) => Ok(ConfirmationResponseWithToken { WithToken::Yes(response, token) => Ok(ConfirmationResponseWithToken {
result: response, result: response,
token: token, token,
}), }),
})) }))
} }
@ -199,8 +198,6 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
fn confirm_request_raw(&self, id: U256, bytes: Bytes) -> Result<ConfirmationResponse> { fn confirm_request_raw(&self, id: U256, bytes: Bytes) -> Result<ConfirmationResponse> {
self.deprecation_notice.print("signer_confirmRequestRaw", deprecated::msgs::ACCOUNTS); self.deprecation_notice.print("signer_confirmRequestRaw", deprecated::msgs::ACCOUNTS);
let id = id.into();
self.signer.take(&id).map(|sender| { self.signer.take(&id).map(|sender| {
let payload = sender.request.payload.clone(); let payload = sender.request.payload.clone();
let result = match payload { let result = match payload {
@ -251,7 +248,7 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
fn reject_request(&self, id: U256) -> Result<bool> { fn reject_request(&self, id: U256) -> Result<bool> {
self.deprecation_notice.print("signer_rejectRequest", deprecated::msgs::ACCOUNTS); self.deprecation_notice.print("signer_rejectRequest", deprecated::msgs::ACCOUNTS);
let res = self.signer.take(&id.into()).map(|sender| self.signer.request_rejected(sender)); let res = self.signer.take(&id).map(|sender| self.signer.request_rejected(sender));
Ok(res.is_some()) Ok(res.is_some())
} }
@ -259,7 +256,7 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
self.deprecation_notice.print("signer_generateAuthorizationToken", deprecated::msgs::ACCOUNTS); self.deprecation_notice.print("signer_generateAuthorizationToken", deprecated::msgs::ACCOUNTS);
self.signer.generate_token() self.signer.generate_token()
.map_err(|e| errors::token(e)) .map_err(errors::token)
} }
fn subscribe_pending(&self, _meta: Self::Metadata, sub: Subscriber<Vec<ConfirmationRequest>>) { fn subscribe_pending(&self, _meta: Self::Metadata, sub: Subscriber<Vec<ConfirmationRequest>>) {

View File

@ -75,7 +75,7 @@ fn schedule(executor: Executor,
future: RpcConfirmationReceiver) { future: RpcConfirmationReceiver) {
{ {
let mut confirmations = confirmations.lock(); let mut confirmations = confirmations.lock();
confirmations.insert(id.clone(), None); confirmations.insert(id, None);
} }
let future = future.then(move |result| { let future = future.then(move |result| {
@ -122,7 +122,7 @@ impl<D: Dispatcher + 'static> SigningQueueClient<D> {
let sender = payload.sender(); let sender = payload.sender();
if accounts.is_unlocked(&sender) { if accounts.is_unlocked(&sender) {
Either::A(dispatch::execute(dispatcher, &accounts, payload, dispatch::SignWith::Nothing) Either::A(dispatch::execute(dispatcher, &accounts, payload, dispatch::SignWith::Nothing)
.map(|v| v.into_value()) .map(dispatch::WithToken::into_value)
.map(DispatchResult::Value)) .map(DispatchResult::Value))
} else { } else {
Either::B(future::done( Either::B(future::done(
@ -149,13 +149,13 @@ impl<D: Dispatcher + 'static> ParitySigning for SigningQueueClient<D> {
let confirmations = self.confirmations.clone(); let confirmations = self.confirmations.clone();
Box::new(self.dispatch( Box::new(self.dispatch(
RpcConfirmationPayload::EthSignMessage((address.clone(), data).into()), RpcConfirmationPayload::EthSignMessage((address, data).into()),
meta.origin meta.origin
).map(move |result| match result { ).map(move |result| match result {
DispatchResult::Value(v) => RpcEither::Or(v), DispatchResult::Value(v) => RpcEither::Or(v),
DispatchResult::Future(id, future) => { DispatchResult::Future(id, future) => {
schedule(executor, confirmations, id, future); schedule(executor, confirmations, id, future);
RpcEither::Either(id.into()) RpcEither::Either(id)
}, },
})) }))
} }
@ -170,14 +170,13 @@ impl<D: Dispatcher + 'static> ParitySigning for SigningQueueClient<D> {
DispatchResult::Value(v) => RpcEither::Or(v), DispatchResult::Value(v) => RpcEither::Or(v),
DispatchResult::Future(id, future) => { DispatchResult::Future(id, future) => {
schedule(executor, confirmations, id, future); schedule(executor, confirmations, id, future);
RpcEither::Either(id.into()) RpcEither::Either(id)
}, },
})) }))
} }
fn check_request(&self, id: U256) -> Result<Option<RpcConfirmationResponse>> { fn check_request(&self, id: U256) -> Result<Option<RpcConfirmationResponse>> {
self.deprecation_notice.print("parity_checkRequest", deprecated::msgs::ACCOUNTS); self.deprecation_notice.print("parity_checkRequest", deprecated::msgs::ACCOUNTS);
let id: U256 = id.into();
match self.confirmations.lock().get(&id) { match self.confirmations.lock().get(&id) {
None => Err(errors::request_not_found()), // Request info has been dropped, or even never been there None => Err(errors::request_not_found()), // Request info has been dropped, or even never been there
Some(&None) => Ok(None), // No confirmation yet, request is known, confirmation is pending Some(&None) => Ok(None), // No confirmation yet, request is known, confirmation is pending
@ -188,7 +187,7 @@ impl<D: Dispatcher + 'static> ParitySigning for SigningQueueClient<D> {
fn decrypt_message(&self, meta: Metadata, address: H160, data: RpcBytes) -> BoxFuture<RpcBytes> { fn decrypt_message(&self, meta: Metadata, address: H160, data: RpcBytes) -> BoxFuture<RpcBytes> {
self.deprecation_notice.print("parity_decryptMessage", deprecated::msgs::ACCOUNTS); self.deprecation_notice.print("parity_decryptMessage", deprecated::msgs::ACCOUNTS);
let res = self.dispatch( let res = self.dispatch(
RpcConfirmationPayload::Decrypt((address.clone(), data).into()), RpcConfirmationPayload::Decrypt((address, data).into()),
meta.origin, meta.origin,
); );
@ -208,7 +207,7 @@ impl<D: Dispatcher + 'static> EthSigning for SigningQueueClient<D> {
fn sign(&self, meta: Metadata, address: H160, data: RpcBytes) -> BoxFuture<H520> { fn sign(&self, meta: Metadata, address: H160, data: RpcBytes) -> BoxFuture<H520> {
self.deprecation_notice.print("eth_sign", deprecated::msgs::ACCOUNTS); self.deprecation_notice.print("eth_sign", deprecated::msgs::ACCOUNTS);
let res = self.dispatch( let res = self.dispatch(
RpcConfirmationPayload::EthSignMessage((address.clone(), data).into()), RpcConfirmationPayload::EthSignMessage((address, data).into()),
meta.origin, meta.origin,
); );

View File

@ -60,7 +60,7 @@ impl<D: Dispatcher + 'static> SigningUnsafeClient<D> {
.and_then(move |payload| { .and_then(move |payload| {
dispatch::execute(dis, &accounts, payload, dispatch::SignWith::Nothing) dispatch::execute(dis, &accounts, payload, dispatch::SignWith::Nothing)
}) })
.map(|v| v.into_value())) .map(dispatch::WithToken::into_value))
} }
} }
@ -70,7 +70,7 @@ impl<D: Dispatcher + 'static> EthSigning for SigningUnsafeClient<D>
fn sign(&self, _: Metadata, address: H160, data: RpcBytes) -> BoxFuture<H520> { fn sign(&self, _: Metadata, address: H160, data: RpcBytes) -> BoxFuture<H520> {
self.deprecation_notice.print("eth_sign", deprecated::msgs::ACCOUNTS); self.deprecation_notice.print("eth_sign", deprecated::msgs::ACCOUNTS);
Box::new(self.handle(RpcConfirmationPayload::EthSignMessage((address.clone(), data).into()), address.into()) Box::new(self.handle(RpcConfirmationPayload::EthSignMessage((address, data).into()), address)
.then(|res| match res { .then(|res| match res {
Ok(RpcConfirmationResponse::Signature(signature)) => Ok(signature), Ok(RpcConfirmationResponse::Signature(signature)) => Ok(signature),
Err(e) => Err(e), Err(e) => Err(e),
@ -111,7 +111,7 @@ impl<D: Dispatcher + 'static> ParitySigning for SigningUnsafeClient<D> {
fn decrypt_message(&self, _: Metadata, address: H160, data: RpcBytes) -> BoxFuture<RpcBytes> { fn decrypt_message(&self, _: Metadata, address: H160, data: RpcBytes) -> BoxFuture<RpcBytes> {
self.deprecation_notice.print("parity_decryptMessage", deprecated::msgs::ACCOUNTS); self.deprecation_notice.print("parity_decryptMessage", deprecated::msgs::ACCOUNTS);
Box::new(self.handle(RpcConfirmationPayload::Decrypt((address.clone(), data).into()), address.into()) Box::new(self.handle(RpcConfirmationPayload::Decrypt((address, data).into()), address)
.then(|res| match res { .then(|res| match res {
Ok(RpcConfirmationResponse::Decrypt(data)) => Ok(data), Ok(RpcConfirmationResponse::Decrypt(data)) => Ok(data),
Err(e) => Err(e), Err(e) => Err(e),

View File

@ -74,13 +74,13 @@ impl<C, S> Traces for TracesClient<C> where
} }
fn transaction_traces(&self, transaction_hash: H256) -> Result<Option<Vec<LocalizedTrace>>> { fn transaction_traces(&self, transaction_hash: H256) -> Result<Option<Vec<LocalizedTrace>>> {
Ok(self.client.transaction_traces(TransactionId::Hash(transaction_hash.into())) Ok(self.client.transaction_traces(TransactionId::Hash(transaction_hash))
.map(|traces| traces.into_iter().map(LocalizedTrace::from).collect())) .map(|traces| traces.into_iter().map(LocalizedTrace::from).collect()))
} }
fn trace(&self, transaction_hash: H256, address: Vec<Index>) -> Result<Option<LocalizedTrace>> { fn trace(&self, transaction_hash: H256, address: Vec<Index>) -> Result<Option<LocalizedTrace>> {
let id = TraceId { let id = TraceId {
transaction: TransactionId::Hash(transaction_hash.into()), transaction: TransactionId::Hash(transaction_hash),
address: address.into_iter().map(|i| i.value()).collect() address: address.into_iter().map(|i| i.value()).collect()
}; };
@ -102,8 +102,8 @@ impl<C, S> Traces for TracesClient<C> where
BlockNumber::Pending => return Err(errors::invalid_params("`BlockNumber::Pending` is not supported", ())), BlockNumber::Pending => return Err(errors::invalid_params("`BlockNumber::Pending` is not supported", ())),
}; };
let mut state = self.client.state_at(id).ok_or(errors::state_pruned())?; let mut state = self.client.state_at(id).ok_or_else(errors::state_pruned)?;
let header = self.client.block_header(id).ok_or(errors::state_pruned())?; let header = self.client.block_header(id).ok_or_else(errors::state_pruned)?;
self.client.call(&signed, to_call_analytics(flags), &mut state, &header.decode().map_err(errors::decode)?) self.client.call(&signed, to_call_analytics(flags), &mut state, &header.decode().map_err(errors::decode)?)
.map(TraceResults::from) .map(TraceResults::from)
@ -129,8 +129,8 @@ impl<C, S> Traces for TracesClient<C> where
BlockNumber::Pending => return Err(errors::invalid_params("`BlockNumber::Pending` is not supported", ())), BlockNumber::Pending => return Err(errors::invalid_params("`BlockNumber::Pending` is not supported", ())),
}; };
let mut state = self.client.state_at(id).ok_or(errors::state_pruned())?; let mut state = self.client.state_at(id).ok_or_else(errors::state_pruned)?;
let header = self.client.block_header(id).ok_or(errors::state_pruned())?; let header = self.client.block_header(id).ok_or_else(errors::state_pruned)?;
self.client.call_many(&requests, &mut state, &header.decode().map_err(errors::decode)?) self.client.call_many(&requests, &mut state, &header.decode().map_err(errors::decode)?)
.map(|results| results.into_iter().map(TraceResults::from).collect()) .map(|results| results.into_iter().map(TraceResults::from).collect())
@ -151,8 +151,8 @@ impl<C, S> Traces for TracesClient<C> where
BlockNumber::Pending => return Err(errors::invalid_params("`BlockNumber::Pending` is not supported", ())), BlockNumber::Pending => return Err(errors::invalid_params("`BlockNumber::Pending` is not supported", ())),
}; };
let mut state = self.client.state_at(id).ok_or(errors::state_pruned())?; let mut state = self.client.state_at(id).ok_or_else(errors::state_pruned)?;
let header = self.client.block_header(id).ok_or(errors::state_pruned())?; let header = self.client.block_header(id).ok_or_else(errors::state_pruned)?;
self.client.call(&signed, to_call_analytics(flags), &mut state, &header.decode().map_err(errors::decode)?) self.client.call(&signed, to_call_analytics(flags), &mut state, &header.decode().map_err(errors::decode)?)
.map(TraceResults::from) .map(TraceResults::from)
@ -160,7 +160,7 @@ impl<C, S> Traces for TracesClient<C> where
} }
fn replay_transaction(&self, transaction_hash: H256, flags: TraceOptions) -> Result<TraceResults> { fn replay_transaction(&self, transaction_hash: H256, flags: TraceOptions) -> Result<TraceResults> {
self.client.replay(TransactionId::Hash(transaction_hash.into()), to_call_analytics(flags)) self.client.replay(TransactionId::Hash(transaction_hash), to_call_analytics(flags))
.map(TraceResults::from) .map(TraceResults::from)
.map_err(errors::call) .map_err(errors::call)
} }
@ -175,7 +175,7 @@ impl<C, S> Traces for TracesClient<C> where
}; };
self.client.replay_block_transactions(id, to_call_analytics(flags)) self.client.replay_block_transactions(id, to_call_analytics(flags))
.map(|results| results.into_iter().map(TraceResultsWithTransactionHash::from).collect()) .map(|results| results.map(TraceResultsWithTransactionHash::from).collect())
.map_err(errors::call) .map_err(errors::call)
} }
} }

View File

@ -23,19 +23,15 @@ use v1::traits::Web3;
use v1::types::Bytes; use v1::types::Bytes;
/// Web3 rpc implementation. /// Web3 rpc implementation.
#[derive(Default)]
pub struct Web3Client; pub struct Web3Client;
impl Web3Client {
/// Creates new Web3Client.
pub fn new() -> Self { Web3Client }
}
impl Web3 for Web3Client { impl Web3 for Web3Client {
fn client_version(&self) -> Result<String> { fn client_version(&self) -> Result<String> {
Ok(version().to_owned().replacen("/", "//", 1)) Ok(version().to_owned().replacen("/", "//", 1))
} }
fn sha3(&self, data: Bytes) -> Result<H256> { fn sha3(&self, data: Bytes) -> Result<H256> {
Ok(keccak(&data.0).into()) Ok(keccak(&data.0))
} }
} }

View File

@ -135,7 +135,7 @@ impl<T: Default + Copy + Ord> StatsCalculator<T> {
#[derive(Default, Debug)] #[derive(Default, Debug)]
pub struct RpcStats { pub struct RpcStats {
requests: RwLock<RateCalculator>, requests: RwLock<RateCalculator>,
roundtrips: RwLock<StatsCalculator<u32>>, roundtrips: RwLock<StatsCalculator<u128>>,
active_sessions: AtomicUsize, active_sessions: AtomicUsize,
} }
@ -157,7 +157,7 @@ impl RpcStats {
} }
/// Add roundtrip time (microseconds) /// Add roundtrip time (microseconds)
pub fn add_roundtrip(&self, microseconds: u32) { pub fn add_roundtrip(&self, microseconds: u128) {
self.roundtrips.write().add(microseconds) self.roundtrips.write().add(microseconds)
} }
@ -172,7 +172,7 @@ impl RpcStats {
} }
/// Returns approximated roundtrip in microseconds /// Returns approximated roundtrip in microseconds
pub fn approximated_roundtrip(&self) -> u32 { pub fn approximated_roundtrip(&self) -> u128 {
self.roundtrips.read().approximated_median() self.roundtrips.read().approximated_median()
} }
} }
@ -197,10 +197,6 @@ impl<T: ActivityNotifier> Middleware<T> {
notifier, notifier,
} }
} }
fn as_micro(dur: time::Duration) -> u32 {
(dur.as_secs() * 1_000_000) as u32 + dur.subsec_nanos() / 1_000
}
} }
impl<M: core::Metadata, T: ActivityNotifier> core::Middleware<M> for Middleware<T> { impl<M: core::Metadata, T: ActivityNotifier> core::Middleware<M> for Middleware<T> {
@ -223,7 +219,7 @@ impl<M: core::Metadata, T: ActivityNotifier> core::Middleware<M> for Middleware<
let stats = self.stats.clone(); let stats = self.stats.clone();
let future = process(request, meta).map(move |res| { let future = process(request, meta).map(move |res| {
let time = Self::as_micro(start.elapsed()); let time = start.elapsed().as_micros();
if time > 10_000 { if time > 10_000 {
debug!(target: "rpc", "[{:?}] Took {}ms", id, time / 1_000); debug!(target: "rpc", "[{:?}] Took {}ms", id, time / 1_000);
} }

View File

@ -20,7 +20,7 @@ use v1::{Web3, Web3Client};
#[test] #[test]
fn rpc_web3_version() { fn rpc_web3_version() {
let web3 = Web3Client::new().to_delegate(); let web3 = Web3Client::default().to_delegate();
let mut io = IoHandler::new(); let mut io = IoHandler::new();
io.extend_with(web3); io.extend_with(web3);
@ -34,7 +34,7 @@ fn rpc_web3_version() {
#[test] #[test]
fn rpc_web3_sha3() { fn rpc_web3_sha3() {
let web3 = Web3Client::new().to_delegate(); let web3 = Web3Client::default().to_delegate();
let mut io = IoHandler::new(); let mut io = IoHandler::new();
io.extend_with(web3); io.extend_with(web3);
@ -46,7 +46,7 @@ fn rpc_web3_sha3() {
#[test] #[test]
fn rpc_web3_sha3_wiki() { fn rpc_web3_sha3_wiki() {
let web3 = Web3Client::new().to_delegate(); let web3 = Web3Client::default().to_delegate();
let mut io = IoHandler::new(); let mut io = IoHandler::new();
io.extend_with(web3); io.extend_with(web3);

View File

@ -139,21 +139,21 @@ impl From<EthHeader> for Header {
impl<'a> From<&'a EthHeader> for Header { impl<'a> From<&'a EthHeader> for Header {
fn from(h: &'a EthHeader) -> Self { fn from(h: &'a EthHeader) -> Self {
Header { Header {
hash: Some(h.hash().into()), hash: Some(h.hash()),
size: Some(h.rlp().as_raw().len().into()), size: Some(h.rlp().as_raw().len().into()),
parent_hash: h.parent_hash().into(), parent_hash: h.parent_hash(),
uncles_hash: h.uncles_hash().into(), uncles_hash: h.uncles_hash(),
author: h.author().into(), author: h.author(),
miner: h.author().into(), miner: h.author(),
state_root: h.state_root().into(), state_root: h.state_root(),
transactions_root: h.transactions_root().into(), transactions_root: h.transactions_root(),
receipts_root: h.receipts_root().into(), receipts_root: h.receipts_root(),
number: Some(h.number().into()), number: Some(h.number().into()),
gas_used: h.gas_used().into(), gas_used: h.gas_used(),
gas_limit: h.gas_limit().into(), gas_limit: h.gas_limit(),
logs_bloom: h.log_bloom().into(), logs_bloom: h.log_bloom(),
timestamp: h.timestamp().into(), timestamp: h.timestamp().into(),
difficulty: h.difficulty().into(), difficulty: h.difficulty(),
extra_data: h.extra_data().into(), extra_data: h.extra_data().into(),
seal_fields: h.view().decode_seal() seal_fields: h.view().decode_seal()
.expect("Client/Miner returns only valid headers. We only serialize headers from Client/Miner; qed") .expect("Client/Miner returns only valid headers. We only serialize headers from Client/Miner; qed")

View File

@ -107,7 +107,7 @@ impl<'a> Visitor<'a> for BlockNumberVisitor {
_ if value.starts_with("0x") => u64::from_str_radix(&value[2..], 16).map(BlockNumber::Num).map_err(|e| { _ if value.starts_with("0x") => u64::from_str_radix(&value[2..], 16).map(BlockNumber::Num).map_err(|e| {
Error::custom(format!("Invalid block number: {}", e)) Error::custom(format!("Invalid block number: {}", e))
}), }),
_ => Err(Error::custom(format!("Invalid block number: missing 0x prefix"))), _ => Err(Error::custom("Invalid block number: missing 0x prefix".to_string())),
} }
} }

View File

@ -41,7 +41,7 @@ pub struct ConfirmationRequest {
impl From<helpers::ConfirmationRequest> for ConfirmationRequest { impl From<helpers::ConfirmationRequest> for ConfirmationRequest {
fn from(c: helpers::ConfirmationRequest) -> Self { fn from(c: helpers::ConfirmationRequest) -> Self {
ConfirmationRequest { ConfirmationRequest {
id: c.id.into(), id: c.id,
payload: c.payload.into(), payload: c.payload.into(),
origin: c.origin, origin: c.origin,
} }
@ -214,15 +214,15 @@ impl From<helpers::ConfirmationPayload> for ConfirmationPayload {
helpers::ConfirmationPayload::SendTransaction(t) => ConfirmationPayload::SendTransaction(t.into()), helpers::ConfirmationPayload::SendTransaction(t) => ConfirmationPayload::SendTransaction(t.into()),
helpers::ConfirmationPayload::SignTransaction(t) => ConfirmationPayload::SignTransaction(t.into()), helpers::ConfirmationPayload::SignTransaction(t) => ConfirmationPayload::SignTransaction(t.into()),
helpers::ConfirmationPayload::EthSignMessage(address, data) => ConfirmationPayload::EthSignMessage(EthSignRequest { helpers::ConfirmationPayload::EthSignMessage(address, data) => ConfirmationPayload::EthSignMessage(EthSignRequest {
address: address.into(), address,
data: data.into(), data: data.into(),
}), }),
helpers::ConfirmationPayload::SignMessage(address, data) => ConfirmationPayload::EIP191SignMessage(EIP191SignRequest { helpers::ConfirmationPayload::SignMessage(address, data) => ConfirmationPayload::EIP191SignMessage(EIP191SignRequest {
address: address.into(), address,
data: data.into(), data,
}), }),
helpers::ConfirmationPayload::Decrypt(address, msg) => ConfirmationPayload::Decrypt(DecryptRequest { helpers::ConfirmationPayload::Decrypt(address, msg) => ConfirmationPayload::Decrypt(DecryptRequest {
address: address.into(), address,
msg: msg.into(), msg: msg.into(),
}), }),
} }

View File

@ -109,7 +109,7 @@ impl Into<VersionInfo> for updater::VersionInfo {
VersionInfo { VersionInfo {
track: self.track.into(), track: self.track.into(),
version: self.version.into(), version: self.version.into(),
hash: self.hash.into(), hash: self.hash,
} }
} }
} }

View File

@ -88,10 +88,7 @@ impl Filter {
}; };
let (from_block, to_block) = match self.block_hash { let (from_block, to_block) = match self.block_hash {
Some(hash) => { Some(hash) => (BlockId::Hash(hash), BlockId::Hash(hash)),
let hash = hash.into();
(BlockId::Hash(hash), BlockId::Hash(hash))
},
None => None =>
(self.from_block.map_or_else(|| BlockId::Latest, &num_to_id), (self.from_block.map_or_else(|| BlockId::Latest, &num_to_id),
self.to_block.map_or_else(|| BlockId::Latest, &num_to_id)), self.to_block.map_or_else(|| BlockId::Latest, &num_to_id)),
@ -101,14 +98,14 @@ impl Filter {
from_block, to_block, from_block, to_block,
address: self.address.and_then(|address| match address { address: self.address.and_then(|address| match address {
VariadicValue::Null => None, VariadicValue::Null => None,
VariadicValue::Single(a) => Some(vec![a.into()]), VariadicValue::Single(a) => Some(vec![a]),
VariadicValue::Multiple(a) => Some(a.into_iter().map(Into::into).collect()) VariadicValue::Multiple(a) => Some(a)
}), }),
topics: { topics: {
let mut iter = self.topics.map_or_else(Vec::new, |topics| topics.into_iter().take(4).map(|topic| match topic { let mut iter = self.topics.map_or_else(Vec::new, |topics| topics.into_iter().take(4).map(|topic| match topic {
VariadicValue::Null => None, VariadicValue::Null => None,
VariadicValue::Single(t) => Some(vec![t.into()]), VariadicValue::Single(t) => Some(vec![t]),
VariadicValue::Multiple(t) => Some(t.into_iter().map(Into::into).collect()) VariadicValue::Multiple(t) => Some(t)
}).collect()).into_iter(); }).collect()).into_iter();
vec![ vec![

View File

@ -51,12 +51,12 @@ pub struct Log {
impl From<LocalizedLogEntry> for Log { impl From<LocalizedLogEntry> for Log {
fn from(e: LocalizedLogEntry) -> Log { fn from(e: LocalizedLogEntry) -> Log {
Log { Log {
address: e.entry.address.into(), address: e.entry.address,
topics: e.entry.topics.into_iter().map(Into::into).collect(), topics: e.entry.topics.into_iter().map(Into::into).collect(),
data: e.entry.data.into(), data: e.entry.data.into(),
block_hash: Some(e.block_hash.into()), block_hash: Some(e.block_hash),
block_number: Some(e.block_number.into()), block_number: Some(e.block_number.into()),
transaction_hash: Some(e.transaction_hash.into()), transaction_hash: Some(e.transaction_hash),
transaction_index: Some(e.transaction_index.into()), transaction_index: Some(e.transaction_index.into()),
log_index: Some(e.log_index.into()), log_index: Some(e.log_index.into()),
transaction_log_index: Some(e.transaction_log_index.into()), transaction_log_index: Some(e.transaction_log_index.into()),
@ -69,7 +69,7 @@ impl From<LocalizedLogEntry> for Log {
impl From<LogEntry> for Log { impl From<LogEntry> for Log {
fn from(e: LogEntry) -> Log { fn from(e: LogEntry) -> Log {
Log { Log {
address: e.address.into(), address: e.address,
topics: e.topics.into_iter().map(Into::into).collect(), topics: e.topics.into_iter().map(Into::into).collect(),
data: e.data.into(), data: e.data.into(),
block_hash: None, block_hash: None,

View File

@ -34,9 +34,9 @@ pub struct PrivateTransactionReceipt {
impl From<EthPrivateReceipt> for PrivateTransactionReceipt { impl From<EthPrivateReceipt> for PrivateTransactionReceipt {
fn from(r: EthPrivateReceipt) -> Self { fn from(r: EthPrivateReceipt) -> Self {
PrivateTransactionReceipt { PrivateTransactionReceipt {
transaction_hash: r.hash.into(), transaction_hash: r.hash,
contract_address: r.contract_address.into(), contract_address: r.contract_address,
status_code: r.status_code.into(), status_code: r.status_code,
} }
} }
} }

View File

@ -26,9 +26,9 @@ use v1::types::{RichHeader, Filter, Log};
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum Result { pub enum Result {
/// New block header. /// New block header.
Header(RichHeader), Header(Box<RichHeader>),
/// Log /// Log
Log(Log), Log(Box<Log>),
/// Transaction hash /// Transaction hash
TransactionHash(H256), TransactionHash(H256),
} }
@ -144,7 +144,7 @@ mod tests {
#[test] #[test]
fn should_serialize_header() { fn should_serialize_header() {
let header = Result::Header(RichHeader { let header = Result::Header(Box::new(RichHeader {
extra_info: Default::default(), extra_info: Default::default(),
inner: Header { inner: Header {
hash: Some(Default::default()), hash: Some(Default::default()),
@ -165,7 +165,7 @@ mod tests {
seal_fields: vec![Default::default(), Default::default()], seal_fields: vec![Default::default(), Default::default()],
size: Some(69.into()), size: Some(69.into()),
}, },
}); }));
let expected = r#"{"author":"0x0000000000000000000000000000000000000000","difficulty":"0x0","extraData":"0x","gasLimit":"0x0","gasUsed":"0x0","hash":"0x0000000000000000000000000000000000000000000000000000000000000000","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0x0000000000000000000000000000000000000000","number":"0x0","parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000","receiptsRoot":"0x0000000000000000000000000000000000000000000000000000000000000000","sealFields":["0x","0x"],"sha3Uncles":"0x0000000000000000000000000000000000000000000000000000000000000000","size":"0x45","stateRoot":"0x0000000000000000000000000000000000000000000000000000000000000000","timestamp":"0x0","transactionsRoot":"0x0000000000000000000000000000000000000000000000000000000000000000"}"#; let expected = r#"{"author":"0x0000000000000000000000000000000000000000","difficulty":"0x0","extraData":"0x","gasLimit":"0x0","gasUsed":"0x0","hash":"0x0000000000000000000000000000000000000000000000000000000000000000","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0x0000000000000000000000000000000000000000","number":"0x0","parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000","receiptsRoot":"0x0000000000000000000000000000000000000000000000000000000000000000","sealFields":["0x","0x"],"sha3Uncles":"0x0000000000000000000000000000000000000000000000000000000000000000","size":"0x45","stateRoot":"0x0000000000000000000000000000000000000000000000000000000000000000","timestamp":"0x0","transactionsRoot":"0x0000000000000000000000000000000000000000000000000000000000000000"}"#;
assert_eq!(serde_json::to_string(&header).unwrap(), expected); assert_eq!(serde_json::to_string(&header).unwrap(), expected);
} }

View File

@ -56,7 +56,7 @@ impl Receipt {
fn outcome_to_state_root(outcome: TransactionOutcome) -> Option<H256> { fn outcome_to_state_root(outcome: TransactionOutcome) -> Option<H256> {
match outcome { match outcome {
TransactionOutcome::Unknown | TransactionOutcome::StatusCode(_) => None, TransactionOutcome::Unknown | TransactionOutcome::StatusCode(_) => None,
TransactionOutcome::StateRoot(root) => Some(root.into()), TransactionOutcome::StateRoot(root) => Some(root),
} }
} }
@ -72,18 +72,18 @@ impl From<LocalizedReceipt> for Receipt {
fn from(r: LocalizedReceipt) -> Self { fn from(r: LocalizedReceipt) -> Self {
Receipt { Receipt {
to: r.to.map(Into::into), to: r.to.map(Into::into),
from: Some(r.from.into()), from: Some(r.from),
transaction_hash: Some(r.transaction_hash.into()), transaction_hash: Some(r.transaction_hash),
transaction_index: Some(r.transaction_index.into()), transaction_index: Some(r.transaction_index.into()),
block_hash: Some(r.block_hash.into()), block_hash: Some(r.block_hash),
block_number: Some(r.block_number.into()), block_number: Some(r.block_number.into()),
cumulative_gas_used: r.cumulative_gas_used.into(), cumulative_gas_used: r.cumulative_gas_used,
gas_used: Some(r.gas_used.into()), gas_used: Some(r.gas_used),
contract_address: r.contract_address.map(Into::into), contract_address: r.contract_address.map(Into::into),
logs: r.logs.into_iter().map(Into::into).collect(), logs: r.logs.into_iter().map(Into::into).collect(),
status_code: Self::outcome_to_status_code(&r.outcome), status_code: Self::outcome_to_status_code(&r.outcome),
state_root: Self::outcome_to_state_root(r.outcome), state_root: Self::outcome_to_state_root(r.outcome),
logs_bloom: r.log_bloom.into(), logs_bloom: r.log_bloom,
} }
} }
} }
@ -93,17 +93,17 @@ impl From<RichReceipt> for Receipt {
Receipt { Receipt {
from: None, from: None,
to: None, to: None,
transaction_hash: Some(r.transaction_hash.into()), transaction_hash: Some(r.transaction_hash),
transaction_index: Some(r.transaction_index.into()), transaction_index: Some(r.transaction_index.into()),
block_hash: None, block_hash: None,
block_number: None, block_number: None,
cumulative_gas_used: r.cumulative_gas_used.into(), cumulative_gas_used: r.cumulative_gas_used,
gas_used: Some(r.gas_used.into()), gas_used: Some(r.gas_used),
contract_address: r.contract_address.map(Into::into), contract_address: r.contract_address.map(Into::into),
logs: r.logs.into_iter().map(Into::into).collect(), logs: r.logs.into_iter().map(Into::into).collect(),
status_code: Self::outcome_to_status_code(&r.outcome), status_code: Self::outcome_to_status_code(&r.outcome),
state_root: Self::outcome_to_state_root(r.outcome), state_root: Self::outcome_to_state_root(r.outcome),
logs_bloom: r.log_bloom.into(), logs_bloom: r.log_bloom,
} }
} }
} }
@ -117,13 +117,13 @@ impl From<EthReceipt> for Receipt {
transaction_index: None, transaction_index: None,
block_hash: None, block_hash: None,
block_number: None, block_number: None,
cumulative_gas_used: r.gas_used.into(), cumulative_gas_used: r.gas_used,
gas_used: None, gas_used: None,
contract_address: None, contract_address: None,
logs: r.logs.into_iter().map(Into::into).collect(), logs: r.logs.into_iter().map(Into::into).collect(),
status_code: Self::outcome_to_status_code(&r.outcome), status_code: Self::outcome_to_status_code(&r.outcome),
state_root: Self::outcome_to_state_root(r.outcome), state_root: Self::outcome_to_state_root(r.outcome),
logs_bloom: r.log_bloom.into(), logs_bloom: r.log_bloom,
} }
} }
} }

View File

@ -120,7 +120,7 @@ impl From<sync::PipProtocolInfo> for PipProtocolInfo {
fn from(info: sync::PipProtocolInfo) -> Self { fn from(info: sync::PipProtocolInfo) -> Self {
PipProtocolInfo { PipProtocolInfo {
version: info.version, version: info.version,
difficulty: info.difficulty.into(), difficulty: info.difficulty,
head: format!("{:x}", info.head), head: format!("{:x}", info.head),
} }
} }
@ -179,7 +179,7 @@ impl From<SyncTransactionStats> for TransactionStats {
first_seen: s.first_seen, first_seen: s.first_seen,
propagated_to: s.propagated_to propagated_to: s.propagated_to
.into_iter() .into_iter()
.map(|(id, count)| (id.into(), count)) .map(|(id, count)| (id, count))
.collect(), .collect(),
} }
} }

View File

@ -58,8 +58,8 @@ pub struct StorageDiff {
impl From<et::StorageDiff> for StorageDiff { impl From<et::StorageDiff> for StorageDiff {
fn from(c: et::StorageDiff) -> Self { fn from(c: et::StorageDiff) -> Self {
StorageDiff { StorageDiff {
key: c.location.into(), key: c.location,
val: c.value.into(), val: c.value,
} }
} }
} }
@ -190,7 +190,7 @@ impl From<account_diff::AccountDiff> for AccountDiff {
balance: c.balance.into(), balance: c.balance.into(),
nonce: c.nonce.into(), nonce: c.nonce.into(),
code: c.code.into(), code: c.code.into(),
storage: c.storage.into_iter().map(|(k, v)| (k.into(), v.into())).collect(), storage: c.storage.into_iter().map(|(k, v)| (k, v.into())).collect(),
} }
} }
} }
@ -208,7 +208,7 @@ impl Serialize for StateDiff {
impl From<state_diff::StateDiff> for StateDiff { impl From<state_diff::StateDiff> for StateDiff {
fn from(c: state_diff::StateDiff) -> Self { fn from(c: state_diff::StateDiff) -> Self {
StateDiff(c.raw.into_iter().map(|(k, v)| (k.into(), v.into())).collect()) StateDiff(c.raw.into_iter().map(|(k, v)| (k, v.into())).collect())
} }
} }
@ -228,9 +228,9 @@ pub struct Create {
impl From<trace::Create> for Create { impl From<trace::Create> for Create {
fn from(c: trace::Create) -> Self { fn from(c: trace::Create) -> Self {
Create { Create {
from: c.from.into(), from: c.from,
value: c.value.into(), value: c.value,
gas: c.gas.into(), gas: c.gas,
init: Bytes::new(c.init), init: Bytes::new(c.init),
} }
} }
@ -285,10 +285,10 @@ pub struct Call {
impl From<trace::Call> for Call { impl From<trace::Call> for Call {
fn from(c: trace::Call) -> Self { fn from(c: trace::Call) -> Self {
Call { Call {
from: c.from.into(), from: c.from,
to: c.to.into(), to: c.to,
value: c.value.into(), value: c.value,
gas: c.gas.into(), gas: c.gas,
input: c.input.into(), input: c.input.into(),
call_type: c.call_type.into(), call_type: c.call_type.into(),
} }
@ -335,8 +335,8 @@ pub struct Reward {
impl From<trace::Reward> for Reward { impl From<trace::Reward> for Reward {
fn from(r: trace::Reward) -> Self { fn from(r: trace::Reward) -> Self {
Reward { Reward {
author: r.author.into(), author: r.author,
value: r.value.into(), value: r.value,
reward_type: r.reward_type.into(), reward_type: r.reward_type.into(),
} }
} }
@ -357,9 +357,9 @@ pub struct Suicide {
impl From<trace::Suicide> for Suicide { impl From<trace::Suicide> for Suicide {
fn from(s: trace::Suicide) -> Self { fn from(s: trace::Suicide) -> Self {
Suicide { Suicide {
address: s.address.into(), address: s.address,
refund_address: s.refund_address.into(), refund_address: s.refund_address,
balance: s.balance.into(), balance: s.balance,
} }
} }
} }
@ -401,7 +401,7 @@ pub struct CallResult {
impl From<trace::CallResult> for CallResult { impl From<trace::CallResult> for CallResult {
fn from(c: trace::CallResult) -> Self { fn from(c: trace::CallResult) -> Self {
CallResult { CallResult {
gas_used: c.gas_used.into(), gas_used: c.gas_used,
output: c.output.into(), output: c.output.into(),
} }
} }
@ -422,9 +422,9 @@ pub struct CreateResult {
impl From<trace::CreateResult> for CreateResult { impl From<trace::CreateResult> for CreateResult {
fn from(c: trace::CreateResult) -> Self { fn from(c: trace::CreateResult) -> Self {
CreateResult { CreateResult {
gas_used: c.gas_used.into(), gas_used: c.gas_used,
code: c.code.into(), code: c.code.into(),
address: c.address.into(), address: c.address,
} }
} }
} }
@ -526,11 +526,11 @@ impl From<EthLocalizedTrace> for LocalizedTrace {
action: t.action.into(), action: t.action.into(),
result: t.result.into(), result: t.result.into(),
trace_address: t.trace_address.into_iter().map(Into::into).collect(), trace_address: t.trace_address.into_iter().map(Into::into).collect(),
subtraces: t.subtraces.into(), subtraces: t.subtraces,
transaction_position: t.transaction_number.map(Into::into), transaction_position: t.transaction_number.map(Into::into),
transaction_hash: t.transaction_hash.map(Into::into), transaction_hash: t.transaction_hash.map(Into::into),
block_number: t.block_number.into(), block_number: t.block_number,
block_hash: t.block_hash.into(), block_hash: t.block_hash,
} }
} }
} }
@ -591,7 +591,7 @@ impl From<FlatTrace> for Trace {
fn from(t: FlatTrace) -> Self { fn from(t: FlatTrace) -> Self {
Trace { Trace {
trace_address: t.trace_address.into_iter().map(Into::into).collect(), trace_address: t.trace_address.into_iter().map(Into::into).collect(),
subtraces: t.subtraces.into(), subtraces: t.subtraces,
action: t.action.into(), action: t.action.into(),
result: t.result.into(), result: t.result.into(),
} }
@ -646,7 +646,7 @@ impl From<(H256, Executed)> for TraceResultsWithTransactionHash {
trace: t.1.trace.into_iter().map(Into::into).collect(), trace: t.1.trace.into_iter().map(Into::into).collect(),
vm_trace: t.1.vm_trace.map(Into::into), vm_trace: t.1.vm_trace.map(Into::into),
state_diff: t.1.state_diff.map(Into::into), state_diff: t.1.state_diff.map(Into::into),
transaction_hash: t.0.into(), transaction_hash: t.0,
} }
} }
} }

View File

@ -177,22 +177,22 @@ impl Transaction {
let signature = t.signature(); let signature = t.signature();
let scheme = CreateContractAddress::FromSenderAndNonce; let scheme = CreateContractAddress::FromSenderAndNonce;
Transaction { Transaction {
hash: t.hash().into(), hash: t.hash(),
nonce: t.nonce.into(), nonce: t.nonce,
block_hash: Some(t.block_hash.clone().into()), block_hash: Some(t.block_hash),
block_number: Some(t.block_number.into()), block_number: Some(t.block_number.into()),
transaction_index: Some(t.transaction_index.into()), transaction_index: Some(t.transaction_index.into()),
from: t.sender().into(), from: t.sender(),
to: match t.action { to: match t.action {
Action::Create => None, Action::Create => None,
Action::Call(ref address) => Some(address.clone().into()) Action::Call(ref address) => Some(*address)
}, },
value: t.value.into(), value: t.value,
gas_price: t.gas_price.into(), gas_price: t.gas_price,
gas: t.gas.into(), gas: t.gas,
input: Bytes::new(t.data.clone()), input: Bytes::new(t.data.clone()),
creates: match t.action { creates: match t.action {
Action::Create => Some(contract_address(scheme, &t.sender(), &t.nonce, &t.data).0.into()), Action::Create => Some(contract_address(scheme, &t.sender(), &t.nonce, &t.data).0),
Action::Call(_) => None, Action::Call(_) => None,
}, },
raw: ::rlp::encode(&t.signed).into(), raw: ::rlp::encode(&t.signed).into(),
@ -211,22 +211,22 @@ impl Transaction {
let signature = t.signature(); let signature = t.signature();
let scheme = CreateContractAddress::FromSenderAndNonce; let scheme = CreateContractAddress::FromSenderAndNonce;
Transaction { Transaction {
hash: t.hash().into(), hash: t.hash(),
nonce: t.nonce.into(), nonce: t.nonce,
block_hash: None, block_hash: None,
block_number: None, block_number: None,
transaction_index: None, transaction_index: None,
from: t.sender().into(), from: t.sender(),
to: match t.action { to: match t.action {
Action::Create => None, Action::Create => None,
Action::Call(ref address) => Some(address.clone().into()) Action::Call(ref address) => Some(*address)
}, },
value: t.value.into(), value: t.value,
gas_price: t.gas_price.into(), gas_price: t.gas_price,
gas: t.gas.into(), gas: t.gas,
input: Bytes::new(t.data.clone()), input: Bytes::new(t.data.clone()),
creates: match t.action { creates: match t.action {
Action::Create => Some(contract_address(scheme, &t.sender(), &t.nonce, &t.data).0.into()), Action::Create => Some(contract_address(scheme, &t.sender(), &t.nonce, &t.data).0),
Action::Call(_) => None, Action::Call(_) => None,
}, },
raw: ::rlp::encode(&t).into(), raw: ::rlp::encode(&t).into(),
@ -243,7 +243,7 @@ impl Transaction {
/// Convert `PendingTransaction` into RPC Transaction. /// Convert `PendingTransaction` into RPC Transaction.
pub fn from_pending(t: PendingTransaction) -> Transaction { pub fn from_pending(t: PendingTransaction) -> Transaction {
let mut r = Transaction::from_signed(t.transaction); let mut r = Transaction::from_signed(t.transaction);
r.condition = t.condition.map(|b| b.into()); r.condition = r.condition.map(Into::into);
r r
} }
} }
@ -265,8 +265,8 @@ impl LocalTransactionStatus {
Canceled(tx) => LocalTransactionStatus::Canceled(convert(tx)), Canceled(tx) => LocalTransactionStatus::Canceled(convert(tx)),
Replaced { old, new } => LocalTransactionStatus::Replaced( Replaced { old, new } => LocalTransactionStatus::Replaced(
convert(old), convert(old),
new.signed().gas_price.into(), new.signed().gas_price,
new.signed().hash().into(), new.signed().hash(),
), ),
} }
} }

View File

@ -63,7 +63,7 @@ pub fn format_ether(i: U256) -> String {
impl fmt::Display for TransactionRequest { impl fmt::Display for TransactionRequest {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let eth = self.value.unwrap_or(U256::from(0)); let eth = self.value.unwrap_or_default();
match self.to { match self.to {
Some(ref to) => write!( Some(ref to) => write!(
f, f,
@ -106,14 +106,14 @@ impl From<helpers::TransactionRequest> for TransactionRequest {
impl From<helpers::FilledTransactionRequest> for TransactionRequest { impl From<helpers::FilledTransactionRequest> for TransactionRequest {
fn from(r: helpers::FilledTransactionRequest) -> Self { fn from(r: helpers::FilledTransactionRequest) -> Self {
TransactionRequest { TransactionRequest {
from: Some(r.from.into()), from: Some(r.from),
to: r.to.map(Into::into), to: r.to,
gas_price: Some(r.gas_price.into()), gas_price: Some(r.gas_price),
gas: Some(r.gas.into()), gas: Some(r.gas),
value: Some(r.value.into()), value: Some(r.value),
data: Some(r.data.into()), data: Some(r.data.into()),
nonce: r.nonce.map(Into::into), nonce: r.nonce,
condition: r.condition.map(Into::into), condition: r.condition,
} }
} }
} }