// Copyright 2015-2018 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see .
//! Utilities and helpers for transaction dispatch.
use std::fmt::Debug;
use std::ops::Deref;
use std::sync::Arc;
use light::cache::Cache as LightDataCache;
use light::client::LightChainClient;
use light::on_demand::{request, OnDemand};
use light::TransactionQueue as LightTransactionQueue;
use hash::keccak;
use ethereum_types::{H256, H520, Address, U256};
use bytes::Bytes;
use parking_lot::{Mutex, RwLock};
use stats::Corpus;
use crypto::DEFAULT_MAC;
use ethcore::account_provider::AccountProvider;
use ethcore::basic_account::BasicAccount;
use ethcore::client::BlockChainClient;
use ethcore::ids::BlockId;
use ethcore::miner::{self, MinerService};
use ethkey::{Password, Signature};
use sync::LightSync;
use transaction::{Action, SignedTransaction, PendingTransaction, Transaction, Error as TransactionError};
use jsonrpc_core::{BoxFuture, Result, Error};
use jsonrpc_core::futures::{future, Future, Poll, Async};
use jsonrpc_core::futures::future::Either;
use v1::helpers::{errors, nonce, TransactionRequest, FilledTransactionRequest, ConfirmationPayload};
use v1::types::{
H256 as RpcH256, H520 as RpcH520, Bytes as RpcBytes,
RichRawTransaction as RpcRichRawTransaction,
ConfirmationPayload as RpcConfirmationPayload,
ConfirmationResponse,
EthSignRequest as RpcEthSignRequest,
EIP191SignRequest as RpcSignRequest,
DecryptRequest as RpcDecryptRequest,
};
use rlp;
pub use self::nonce::Reservations;
/// Has the capability to dispatch, sign, and decrypt.
///
/// Requires a clone implementation, with the implication that it be cheap;
/// usually just bumping a reference count or two.
pub trait Dispatcher: Send + Sync + Clone {
// TODO: when ATC exist, use zero-cost
// type Out: IntoFuture
/// Fill optional fields of a transaction request, fetching gas price but not nonce.
fn fill_optional_fields(&self, request: TransactionRequest, default_sender: Address, force_nonce: bool)
-> BoxFuture;
/// Sign the given transaction request without dispatching, fetching appropriate nonce.
fn sign(&self, accounts: Arc, filled: FilledTransactionRequest, password: SignWith)
-> BoxFuture>;
/// Converts a `SignedTransaction` into `RichRawTransaction`
fn enrich(&self, SignedTransaction) -> RpcRichRawTransaction;
/// "Dispatch" a local transaction.
fn dispatch_transaction(&self, signed_transaction: PendingTransaction)
-> Result;
}
/// A dispatcher which uses references to a client and miner in order to sign
/// requests locally.
#[derive(Debug)]
pub struct FullDispatcher {
client: Arc,
miner: Arc,
nonces: Arc>,
gas_price_percentile: usize,
}
impl FullDispatcher {
/// Create a `FullDispatcher` from Arc references to a client and miner.
pub fn new(
client: Arc,
miner: Arc,
nonces: Arc>,
gas_price_percentile: usize,
) -> Self {
FullDispatcher {
client,
miner,
nonces,
gas_price_percentile,
}
}
}
impl Clone for FullDispatcher {
fn clone(&self) -> Self {
FullDispatcher {
client: self.client.clone(),
miner: self.miner.clone(),
nonces: self.nonces.clone(),
gas_price_percentile: self.gas_price_percentile,
}
}
}
impl FullDispatcher {
fn state_nonce(&self, from: &Address) -> U256 {
self.miner.next_nonce(&*self.client, from)
}
/// Imports transaction to the miner's queue.
pub fn dispatch_transaction(client: &C, miner: &M, signed_transaction: PendingTransaction, trusted: bool) -> Result {
let hash = signed_transaction.transaction.hash();
// use `import_claimed_local_transaction` so we can decide (based on config flags) if we want to treat
// it as local or not. Nodes with public RPC interfaces will want these transactions to be treated like
// external transactions.
miner.import_claimed_local_transaction(client, signed_transaction, trusted)
.map_err(errors::transaction)
.map(|_| hash)
}
}
impl Dispatcher for FullDispatcher {
fn fill_optional_fields(&self, request: TransactionRequest, default_sender: Address, force_nonce: bool)
-> BoxFuture
{
let request = request;
let from = request.from.unwrap_or(default_sender);
let nonce = if force_nonce {
request.nonce.or_else(|| Some(self.state_nonce(&from)))
} else {
request.nonce
};
Box::new(future::ok(FilledTransactionRequest {
from,
used_default_from: request.from.is_none(),
to: request.to,
nonce,
gas_price: request.gas_price.unwrap_or_else(|| {
default_gas_price(&*self.client, &*self.miner, self.gas_price_percentile)
}),
gas: request.gas.unwrap_or_else(|| self.miner.sensible_gas_limit()),
value: request.value.unwrap_or_else(|| 0.into()),
data: request.data.unwrap_or_else(Vec::new),
condition: request.condition,
}))
}
fn sign(&self, accounts: Arc, filled: FilledTransactionRequest, password: SignWith)
-> BoxFuture>
{
let chain_id = self.client.signing_chain_id();
if let Some(nonce) = filled.nonce {
return Box::new(future::done(sign_transaction(&*accounts, filled, chain_id, nonce, password)));
}
let state = self.state_nonce(&filled.from);
let reserved = self.nonces.lock().reserve(filled.from, state);
Box::new(ProspectiveSigner::new(accounts, filled, chain_id, reserved, password))
}
fn enrich(&self, signed_transaction: SignedTransaction) -> RpcRichRawTransaction {
RpcRichRawTransaction::from_signed(signed_transaction)
}
fn dispatch_transaction(&self, signed_transaction: PendingTransaction) -> Result {
Self::dispatch_transaction(&*self.client, &*self.miner, signed_transaction, true)
}
}
/// Get a recent gas price corpus.
// TODO: this could be `impl Trait`.
pub fn fetch_gas_price_corpus(
sync: Arc,
client: Arc,
on_demand: Arc,
cache: Arc>,
) -> BoxFuture> {
const GAS_PRICE_SAMPLE_SIZE: usize = 100;
if let Some(cached) = { cache.lock().gas_price_corpus() } {
return Box::new(future::ok(cached))
}
let cache = cache.clone();
let eventual_corpus = sync.with_context(|ctx| {
// get some recent headers with gas used,
// and request each of the blocks from the network.
let block_requests = client.ancestry_iter(BlockId::Latest)
.filter(|hdr| hdr.gas_used() != U256::default())
.take(GAS_PRICE_SAMPLE_SIZE)
.map(|hdr| request::Body(hdr.into()))
.collect::>();
// when the blocks come in, collect gas prices into a vector
on_demand.request(ctx, block_requests)
.expect("no back-references; therefore all back-references are valid; qed")
.map(|bodies| {
bodies.into_iter().fold(Vec::new(), |mut v, block| {
for t in block.transaction_views().iter() {
v.push(t.gas_price())
}
v
})
})
.map(move |prices| {
// produce a corpus from the vector and cache it.
// It's later used to get a percentile for default gas price.
let corpus: ::stats::Corpus<_> = prices.into();
cache.lock().set_gas_price_corpus(corpus.clone());
corpus
})
});
match eventual_corpus {
Some(corp) => Box::new(corp.map_err(|_| errors::no_light_peers())),
None => Box::new(future::err(errors::network_disabled())),
}
}
/// Returns a eth_sign-compatible hash of data to sign.
/// The data is prepended with special message to prevent
/// malicious DApps from using the function to sign forged transactions.
pub fn eth_data_hash(mut data: Bytes) -> H256 {
let mut message_data =
format!("\x19Ethereum Signed Message:\n{}", data.len())
.into_bytes();
message_data.append(&mut data);
keccak(message_data)
}
/// Dispatcher for light clients -- fetches default gas price, next nonce, etc. from network.
#[derive(Clone)]
pub struct LightDispatcher {
/// Sync service.
pub sync: Arc,
/// Header chain client.
pub client: Arc,
/// On-demand request service.
pub on_demand: Arc,
/// Data cache.
pub cache: Arc>,
/// Transaction queue.
pub transaction_queue: Arc>,
/// Nonce reservations
pub nonces: Arc>,
/// Gas Price percentile value used as default gas price.
pub gas_price_percentile: usize,
}
impl LightDispatcher {
/// Create a new `LightDispatcher` from its requisite parts.
///
/// For correct operation, the OnDemand service is assumed to be registered as a network handler,
pub fn new(
sync: Arc,
client: Arc,
on_demand: Arc,
cache: Arc>,
transaction_queue: Arc>,
nonces: Arc>,
gas_price_percentile: usize,
) -> Self {
LightDispatcher {
sync,
client,
on_demand,
cache,
transaction_queue,
nonces,
gas_price_percentile,
}
}
/// Get a recent gas price corpus.
// TODO: this could be `impl Trait`.
pub fn gas_price_corpus(&self) -> BoxFuture> {
fetch_gas_price_corpus(
self.sync.clone(),
self.client.clone(),
self.on_demand.clone(),
self.cache.clone(),
)
}
/// Get an account's state
fn account(&self, addr: Address) -> BoxFuture