Deprecate account management (#10213)

* Extract accounts from ethcore.

* Fix ethcore.

* Get rid of AccountProvider in test_helpers

* Fix rest of the code.

* Re-use EngineSigner, fix tests.

* Simplify EngineSigner to always have an Address.

* Fix RPC tests.

* Add deprecation notice to RPCs.

* Feature to disable accounts.

* extract accounts in RPC

* Run with accounts in tests.

* Fix RPC compilation and tests.

* Fix compilation of the binary.

* Fix compilation of the binary.

* Fix compilation with accounts enabled.

* Fix tests.

* Update submodule.

* Remove android.

* Use derive for Default

* Don't build secretstore by default.

* Add link to issue.

* Refresh Cargo.lock.

* Fix miner tests.

* Update rpc/Cargo.toml

Co-Authored-By: tomusdrw <tomusdrw@users.noreply.github.com>

* Fix private tests.
This commit is contained in:
Tomasz Drwięga
2019-02-07 14:34:24 +01:00
committed by Afri Schoedon
parent 8fa56add47
commit d5c19f8719
102 changed files with 3222 additions and 2393 deletions

View File

@@ -1,27 +0,0 @@
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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 Ethereum 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 Ethereum. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use ethcore::account_provider::AccountProvider;
use jsonrpc_core::Error;
use v1::helpers::errors;
pub fn unwrap_provider(provider: &Option<Arc<AccountProvider>>) -> Result<Arc<AccountProvider>, Error> {
match *provider {
Some(ref arc) => Ok(arc.clone()),
None => Err(errors::public_unsupported(None)),
}
}

View File

@@ -0,0 +1,111 @@
// 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 <http://www.gnu.org/licenses/>.
//! Deprecation notice for RPC methods.
//!
//! Displays a warning but avoids spamming the log.
use std::{
collections::HashMap,
time::{Duration, Instant},
};
use parking_lot::RwLock;
/// Deprecation messages
pub mod msgs {
pub const ACCOUNTS: Option<&str> = Some("Account management is being phased out see #9997 for alternatives.");
}
type MethodName = &'static str;
const PRINT_INTERVAL: Duration = Duration::from_secs(60);
/// Displays a deprecation notice without spamming the log.
pub struct DeprecationNotice<T = fn() -> Instant> {
now: T,
next_warning_at: RwLock<HashMap<String, Instant>>,
printer: Box<Fn(MethodName, Option<&str>) + Send + Sync>,
}
impl Default for DeprecationNotice {
fn default() -> Self {
Self::new(Instant::now, |method, more| {
let more = more.map(|x| format!(": {}", x)).unwrap_or_else(|| ".".into());
warn!(target: "rpc", "{} is deprecated and will be removed in future versions{}", method, more);
})
}
}
impl<N: Fn() -> Instant> DeprecationNotice<N> {
/// Create new deprecation notice printer with custom display and interval.
pub fn new<T>(now: N, printer: T) -> Self where
T: Fn(MethodName, Option<&str>) + Send + Sync + 'static,
{
DeprecationNotice {
now,
next_warning_at: Default::default(),
printer: Box::new(printer),
}
}
/// Print deprecation notice for given method and with some additional details (explanations).
pub fn print<'a, T: Into<Option<&'a str>>>(&self, method: MethodName, details: T) {
let now = (self.now)();
match self.next_warning_at.read().get(method) {
Some(next) if next > &now => return,
_ => {},
}
self.next_warning_at.write().insert(method.to_owned(), now + PRINT_INTERVAL);
(self.printer)(method, details.into());
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
#[test]
fn should_throttle_printing() {
let saved = Arc::new(RwLock::new(None));
let s = saved.clone();
let printer = move |method: MethodName, more: Option<&str>| {
*s.write() = Some((method, more.map(|s| s.to_owned())));
};
let now = Arc::new(RwLock::new(Instant::now()));
let n = now.clone();
let get_now = || n.read().clone();
let notice = DeprecationNotice::new(get_now, printer);
let details = Some("See issue #123456");
notice.print("eth_test", details.clone());
// printer shouldn't be called
notice.print("eth_test", None);
assert_eq!(saved.read().clone().unwrap(), ("eth_test", details.as_ref().map(|x| x.to_string())));
// but calling a different method is fine
notice.print("eth_test2", None);
assert_eq!(saved.read().clone().unwrap(), ("eth_test2", None));
// wait and call again
*now.write() = Instant::now() + PRINT_INTERVAL;
notice.print("eth_test", None);
assert_eq!(saved.read().clone().unwrap(), ("eth_test", None));
}
}

View File

@@ -1,879 +0,0 @@
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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 Ethereum 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 Ethereum. If not, see <http://www.gnu.org/licenses/>.
//! 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::client::BlockChainClient;
use ethcore::miner::{self, MinerService};
use ethkey::{Password, Signature};
use sync::LightSync;
use types::transaction::{Action, SignedTransaction, PendingTransaction, Transaction, Error as TransactionError};
use types::basic_account::BasicAccount;
use types::ids::BlockId;
use jsonrpc_core::{BoxFuture, Result, Error};
use jsonrpc_core::futures::{future, Future, Poll, Async, IntoFuture};
use jsonrpc_core::futures::future::Either;
use v1::helpers::{errors, nonce, TransactionRequest, FilledTransactionRequest, ConfirmationPayload};
use v1::types::{
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<T>: IntoFuture<T, Error>
/// 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<FilledTransactionRequest>;
/// Sign the given transaction request, fetching appropriate nonce and executing the PostSign action
fn sign<P>(
&self,
accounts: Arc<AccountProvider>,
filled: FilledTransactionRequest,
password: SignWith,
post_sign: P
) -> BoxFuture<P::Item>
where
P: PostSign + 'static,
<P::Out as futures::future::IntoFuture>::Future: Send;
/// Converts a `SignedTransaction` into `RichRawTransaction`
fn enrich(&self, signed: SignedTransaction) -> RpcRichRawTransaction;
/// "Dispatch" a local transaction.
fn dispatch_transaction(&self, signed_transaction: PendingTransaction)
-> Result<H256>;
}
/// A dispatcher which uses references to a client and miner in order to sign
/// requests locally.
#[derive(Debug)]
pub struct FullDispatcher<C, M> {
client: Arc<C>,
miner: Arc<M>,
nonces: Arc<Mutex<nonce::Reservations>>,
gas_price_percentile: usize,
}
impl<C, M> FullDispatcher<C, M> {
/// Create a `FullDispatcher` from Arc references to a client and miner.
pub fn new(
client: Arc<C>,
miner: Arc<M>,
nonces: Arc<Mutex<nonce::Reservations>>,
gas_price_percentile: usize,
) -> Self {
FullDispatcher {
client,
miner,
nonces,
gas_price_percentile,
}
}
}
impl<C, M> Clone for FullDispatcher<C, M> {
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<C: miner::BlockChainClient, M: MinerService> FullDispatcher<C, M> {
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<H256> {
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<C: miner::BlockChainClient + BlockChainClient, M: MinerService> Dispatcher for FullDispatcher<C, M> {
fn fill_optional_fields(&self, request: TransactionRequest, default_sender: Address, force_nonce: bool)
-> BoxFuture<FilledTransactionRequest>
{
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<P>(
&self,
accounts: Arc<AccountProvider>,
filled: FilledTransactionRequest,
password: SignWith,
post_sign: P
) -> BoxFuture<P::Item>
where
P: PostSign + 'static,
<P::Out as futures::future::IntoFuture>::Future: Send
{
let chain_id = self.client.signing_chain_id();
if let Some(nonce) = filled.nonce {
let future = sign_transaction(&*accounts, filled, chain_id, nonce, password)
.into_future()
.and_then(move |signed| post_sign.execute(signed));
Box::new(future)
} else {
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, post_sign))
}
}
fn enrich(&self, signed_transaction: SignedTransaction) -> RpcRichRawTransaction {
RpcRichRawTransaction::from_signed(signed_transaction)
}
fn dispatch_transaction(&self, signed_transaction: PendingTransaction) -> Result<H256> {
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<LightSync>,
client: Arc<LightChainClient>,
on_demand: Arc<OnDemand>,
cache: Arc<Mutex<LightDataCache>>,
) -> BoxFuture<Corpus<U256>> {
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::<Vec<_>>();
// 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<LightSync>,
/// Header chain client.
pub client: Arc<LightChainClient>,
/// On-demand request service.
pub on_demand: Arc<OnDemand>,
/// Data cache.
pub cache: Arc<Mutex<LightDataCache>>,
/// Transaction queue.
pub transaction_queue: Arc<RwLock<LightTransactionQueue>>,
/// Nonce reservations
pub nonces: Arc<Mutex<nonce::Reservations>>,
/// 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<LightSync>,
client: Arc<LightChainClient>,
on_demand: Arc<OnDemand>,
cache: Arc<Mutex<LightDataCache>>,
transaction_queue: Arc<RwLock<LightTransactionQueue>>,
nonces: Arc<Mutex<nonce::Reservations>>,
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<Corpus<U256>> {
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<Option<BasicAccount>> {
let best_header = self.client.best_block_header();
let account_future = self.sync.with_context(|ctx| self.on_demand.request(ctx, request::Account {
header: best_header.into(),
address: addr,
}).expect("no back-references; therefore all back-references valid; qed"));
match account_future {
Some(response) => Box::new(response.map_err(|_| errors::no_light_peers())),
None => Box::new(future::err(errors::network_disabled())),
}
}
/// Get an account's next nonce.
pub fn next_nonce(&self, addr: Address) -> BoxFuture<U256> {
let account_start_nonce = self.client.engine().account_start_nonce(self.client.best_block_header().number());
Box::new(self.account(addr)
.and_then(move |maybe_account| {
future::ok(maybe_account.map_or(account_start_nonce, |account| account.nonce))
})
)
}
}
impl Dispatcher for LightDispatcher {
// Ignore the `force_nonce` flag in order to always query the network when fetching the nonce and
// the account state. If the nonce is specified in the transaction use that nonce instead but do the
// network request anyway to the account state (balance)
fn fill_optional_fields(&self, request: TransactionRequest, default_sender: Address, _force_nonce: bool)
-> BoxFuture<FilledTransactionRequest>
{
const DEFAULT_GAS_PRICE: U256 = U256([0, 0, 0, 21_000_000]);
let gas_limit = self.client.best_block_header().gas_limit();
let request_gas_price = request.gas_price.clone();
let from = request.from.unwrap_or(default_sender);
let with_gas_price = move |gas_price| {
let request = request;
FilledTransactionRequest {
from: from.clone(),
used_default_from: request.from.is_none(),
to: request.to,
nonce: request.nonce,
gas_price: gas_price,
gas: request.gas.unwrap_or_else(|| gas_limit / 3),
value: request.value.unwrap_or_else(|| 0.into()),
data: request.data.unwrap_or_else(Vec::new),
condition: request.condition,
}
};
// fast path for known gas price.
let gas_price_percentile = self.gas_price_percentile;
let gas_price = match request_gas_price {
Some(gas_price) => Either::A(future::ok(with_gas_price(gas_price))),
None => Either::B(fetch_gas_price_corpus(
self.sync.clone(),
self.client.clone(),
self.on_demand.clone(),
self.cache.clone()
).and_then(move |corp| match corp.percentile(gas_price_percentile) {
Some(percentile) => Ok(*percentile),
None => Ok(DEFAULT_GAS_PRICE), // fall back to default on error.
}).map(with_gas_price))
};
let future_account = self.account(from);
Box::new(gas_price.and_then(move |mut filled| {
future_account
.and_then(move |maybe_account| {
let cost = filled.value.saturating_add(filled.gas.saturating_mul(filled.gas_price));
match maybe_account {
Some(ref account) if cost > account.balance => {
Err(errors::transaction(TransactionError::InsufficientBalance {
balance: account.balance,
cost,
}))
}
Some(account) => {
if filled.nonce.is_none() {
filled.nonce = Some(account.nonce);
}
Ok(filled)
}
None => Err(errors::account("Account not found", "")),
}
})
}))
}
fn sign<P>(
&self,
accounts: Arc<AccountProvider>,
filled: FilledTransactionRequest,
password: SignWith,
post_sign: P
) -> BoxFuture<P::Item>
where
P: PostSign + 'static,
<P::Out as futures::future::IntoFuture>::Future: Send
{
let chain_id = self.client.signing_chain_id();
let nonce = filled.nonce.expect("nonce is always provided; qed");
let future = sign_transaction(&*accounts, filled, chain_id, nonce, password)
.into_future()
.and_then(move |signed| post_sign.execute(signed));
Box::new(future)
}
fn enrich(&self, signed_transaction: SignedTransaction) -> RpcRichRawTransaction {
RpcRichRawTransaction::from_signed(signed_transaction)
}
fn dispatch_transaction(&self, signed_transaction: PendingTransaction) -> Result<H256> {
let hash = signed_transaction.transaction.hash();
self.transaction_queue.write().import(signed_transaction)
.map_err(errors::transaction)
.map(|_| hash)
}
}
fn sign_transaction(
accounts: &AccountProvider,
filled: FilledTransactionRequest,
chain_id: Option<u64>,
nonce: U256,
password: SignWith,
) -> Result<WithToken<SignedTransaction>> {
let t = Transaction {
nonce: nonce,
action: filled.to.map_or(Action::Create, Action::Call),
gas: filled.gas,
gas_price: filled.gas_price,
value: filled.value,
data: filled.data,
};
if accounts.is_hardware_address(&filled.from) {
return hardware_signature(accounts, filled.from, t, chain_id).map(WithToken::No)
}
let hash = t.hash(chain_id);
let signature = signature(accounts, filled.from, hash, password)?;
Ok(signature.map(|sig| {
SignedTransaction::new(t.with_signature(sig, chain_id))
.expect("Transaction was signed by AccountsProvider; it never produces invalid signatures; qed")
}))
}
#[derive(Debug, Clone, Copy)]
enum ProspectiveSignerState {
TryProspectiveSign,
WaitForPostSign,
WaitForNonce,
}
struct ProspectiveSigner<P: PostSign> {
accounts: Arc<AccountProvider>,
filled: FilledTransactionRequest,
chain_id: Option<u64>,
reserved: nonce::Reserved,
password: SignWith,
state: ProspectiveSignerState,
prospective: Option<WithToken<SignedTransaction>>,
ready: Option<nonce::Ready>,
post_sign: Option<P>,
post_sign_future: Option<<P::Out as IntoFuture>::Future>
}
/// action to execute after signing
/// e.g importing a transaction into the chain
pub trait PostSign: Send {
/// item that this PostSign returns
type Item: Send;
/// incase you need to perform async PostSign actions
type Out: IntoFuture<Item = Self::Item, Error = Error> + Send;
/// perform an action with the signed transaction
fn execute(self, signer: WithToken<SignedTransaction>) -> Self::Out;
}
impl PostSign for () {
type Item = WithToken<SignedTransaction>;
type Out = Result<Self::Item>;
fn execute(self, signed: WithToken<SignedTransaction>) -> Self::Out {
Ok(signed)
}
}
impl<F: Send, T: Send> PostSign for F
where F: FnOnce(WithToken<SignedTransaction>) -> Result<T>
{
type Item = T;
type Out = Result<Self::Item>;
fn execute(self, signed: WithToken<SignedTransaction>) -> Self::Out {
(self)(signed)
}
}
impl<P: PostSign> ProspectiveSigner<P> {
pub fn new(
accounts: Arc<AccountProvider>,
filled: FilledTransactionRequest,
chain_id: Option<u64>,
reserved: nonce::Reserved,
password: SignWith,
post_sign: P
) -> Self {
// If the account is permanently unlocked we can try to sign
// using prospective nonce. This should speed up sending
// multiple subsequent transactions in multi-threaded RPC environment.
let is_unlocked_permanently = accounts.is_unlocked_permanently(&filled.from);
let has_password = password.is_password();
ProspectiveSigner {
accounts,
filled,
chain_id,
reserved,
password,
state: if is_unlocked_permanently || has_password {
ProspectiveSignerState::TryProspectiveSign
} else {
ProspectiveSignerState::WaitForNonce
},
prospective: None,
ready: None,
post_sign: Some(post_sign),
post_sign_future: None
}
}
fn sign(&self, nonce: &U256) -> Result<WithToken<SignedTransaction>> {
sign_transaction(
&*self.accounts,
self.filled.clone(),
self.chain_id,
*nonce,
self.password.clone()
)
}
fn poll_reserved(&mut self) -> Poll<nonce::Ready, Error> {
self.reserved.poll().map_err(|_| errors::internal("Nonce reservation failure", ""))
}
}
impl<P: PostSign> Future for ProspectiveSigner<P> {
type Item = P::Item;
type Error = Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
use self::ProspectiveSignerState::*;
loop {
match self.state {
TryProspectiveSign => {
// Try to poll reserved, it might be ready.
match self.poll_reserved()? {
Async::NotReady => {
self.state = WaitForNonce;
self.prospective = Some(self.sign(self.reserved.prospective_value())?);
},
Async::Ready(nonce) => {
self.state = WaitForPostSign;
self.post_sign_future = Some(self.post_sign.take()
.expect("post_sign is set on creation; qed")
.execute(self.sign(nonce.value())?)
.into_future());
self.ready = Some(nonce);
},
}
},
WaitForNonce => {
let nonce = try_ready!(self.poll_reserved());
let prospective = match (self.prospective.take(), nonce.matches_prospective()) {
(Some(prospective), true) => prospective,
_ => self.sign(nonce.value())?,
};
self.ready = Some(nonce);
self.state = WaitForPostSign;
self.post_sign_future = Some(self.post_sign.take()
.expect("post_sign is set on creation; qed")
.execute(prospective)
.into_future());
},
WaitForPostSign => {
if let Some(mut fut) = self.post_sign_future.as_mut() {
match fut.poll()? {
Async::Ready(item) => {
let nonce = self.ready
.take()
.expect("nonce is set before state transitions to WaitForPostSign; qed");
nonce.mark_used();
return Ok(Async::Ready(item))
},
Async::NotReady => {
return Ok(Async::NotReady)
}
}
} else {
panic!("Poll after ready.");
}
}
}
}
}
}
/// Single-use account token.
pub type AccountToken = Password;
/// Values used to unlock accounts for signing.
#[derive(Clone, PartialEq)]
pub enum SignWith {
/// Nothing -- implies the account is already unlocked.
Nothing,
/// Unlock with password.
Password(Password),
/// Unlock with single-use token.
Token(AccountToken),
}
impl SignWith {
fn is_password(&self) -> bool {
if let SignWith::Password(_) = *self {
true
} else {
false
}
}
}
/// A value, potentially accompanied by a signing token.
pub enum WithToken<T> {
/// No token.
No(T),
/// With token.
Yes(T, AccountToken),
}
impl<T: Debug> Deref for WithToken<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
match *self {
WithToken::No(ref v) => v,
WithToken::Yes(ref v, _) => v,
}
}
}
impl<T: Debug> WithToken<T> {
/// Map the value with the given closure, preserving the token.
pub fn map<S, F>(self, f: F) -> WithToken<S> where
S: Debug,
F: FnOnce(T) -> S,
{
match self {
WithToken::No(v) => WithToken::No(f(v)),
WithToken::Yes(v, token) => WithToken::Yes(f(v), token),
}
}
/// Convert into inner value, ignoring possible token.
pub fn into_value(self) -> T {
match self {
WithToken::No(v) => v,
WithToken::Yes(v, _) => v,
}
}
/// Convert the `WithToken` into a tuple.
pub fn into_tuple(self) -> (T, Option<AccountToken>) {
match self {
WithToken::No(v) => (v, None),
WithToken::Yes(v, token) => (v, Some(token))
}
}
}
impl<T: Debug> From<(T, AccountToken)> for WithToken<T> {
fn from(tuple: (T, AccountToken)) -> Self {
WithToken::Yes(tuple.0, tuple.1)
}
}
impl<T: Debug> From<(T, Option<AccountToken>)> for WithToken<T> {
fn from(tuple: (T, Option<AccountToken>)) -> Self {
match tuple.1 {
Some(token) => WithToken::Yes(tuple.0, token),
None => WithToken::No(tuple.0),
}
}
}
/// Execute a confirmation payload.
pub fn execute<D: Dispatcher + 'static>(
dispatcher: D,
accounts: Arc<AccountProvider>,
payload: ConfirmationPayload,
pass: SignWith
) -> BoxFuture<WithToken<ConfirmationResponse>> {
match payload {
ConfirmationPayload::SendTransaction(request) => {
let condition = request.condition.clone().map(Into::into);
let cloned_dispatcher = dispatcher.clone();
let post_sign = move |with_token_signed: WithToken<SignedTransaction>| {
let (signed, token) = with_token_signed.into_tuple();
let signed_transaction = PendingTransaction::new(signed, condition);
cloned_dispatcher.dispatch_transaction(signed_transaction)
.map(|hash| (hash, token))
};
let future = dispatcher.sign(accounts, request, pass, post_sign)
.map(|(hash, token)| {
WithToken::from((ConfirmationResponse::SendTransaction(hash.into()), token))
});
Box::new(future)
},
ConfirmationPayload::SignTransaction(request) => {
Box::new(dispatcher.sign(accounts, request, pass, ())
.map(move |result| result
.map(move |tx| dispatcher.enrich(tx))
.map(ConfirmationResponse::SignTransaction)
))
},
ConfirmationPayload::EthSignMessage(address, data) => {
if accounts.is_hardware_address(&address) {
let signature = accounts.sign_message_with_hardware(&address, &data)
.map(|s| H520(s.into_electrum()))
.map(RpcH520::from)
.map(ConfirmationResponse::Signature)
// TODO: is this correct? I guess the `token` is the wallet in this context
.map(WithToken::No)
.map_err(|e| errors::account("Error signing message with hardware_wallet", e));
return Box::new(future::done(signature));
}
let hash = eth_data_hash(data);
let res = signature(&accounts, address, hash, pass)
.map(|result| result
.map(|rsv| H520(rsv.into_electrum()))
.map(RpcH520::from)
.map(ConfirmationResponse::Signature)
);
Box::new(future::done(res))
},
ConfirmationPayload::SignMessage(address, data) => {
if accounts.is_hardware_address(&address) {
return Box::new(future::err(errors::account("Error signing message with hardware_wallet",
"Message signing is unsupported")));
}
let res = signature(&accounts, address, data, pass)
.map(|result| result
.map(|rsv| H520(rsv.into_electrum()))
.map(RpcH520::from)
.map(ConfirmationResponse::Signature)
);
Box::new(future::done(res))
},
ConfirmationPayload::Decrypt(address, data) => {
if accounts.is_hardware_address(&address) {
return Box::new(future::err(errors::unsupported("Decrypting via hardware wallets is not supported.", None)));
}
let res = decrypt(&accounts, address, data, pass)
.map(|result| result
.map(RpcBytes)
.map(ConfirmationResponse::Decrypt)
);
Box::new(future::done(res))
},
}
}
fn signature(accounts: &AccountProvider, address: Address, hash: H256, password: SignWith) -> Result<WithToken<Signature>> {
match password.clone() {
SignWith::Nothing => accounts.sign(address, None, hash).map(WithToken::No),
SignWith::Password(pass) => accounts.sign(address, Some(pass), hash).map(WithToken::No),
SignWith::Token(token) => accounts.sign_with_token(address, token, hash).map(Into::into),
}.map_err(|e| match password {
SignWith::Nothing => errors::signing(e),
_ => errors::password(e),
})
}
// obtain a hardware signature from the given account.
fn hardware_signature(accounts: &AccountProvider, address: Address, t: Transaction, chain_id: Option<u64>)
-> Result<SignedTransaction>
{
debug_assert!(accounts.is_hardware_address(&address));
let mut stream = rlp::RlpStream::new();
t.rlp_append_unsigned_transaction(&mut stream, chain_id);
let signature = accounts.sign_transaction_with_hardware(&address, &t, chain_id, &stream.as_raw())
.map_err(|e| {
debug!(target: "miner", "Error signing transaction with hardware wallet: {}", e);
errors::account("Error signing transaction with hardware wallet", e)
})?;
SignedTransaction::new(t.with_signature(signature, chain_id))
.map_err(|e| {
debug!(target: "miner", "Hardware wallet has produced invalid signature: {}", e);
errors::account("Invalid signature generated", e)
})
}
fn decrypt(accounts: &AccountProvider, address: Address, msg: Bytes, password: SignWith) -> Result<WithToken<Bytes>> {
match password.clone() {
SignWith::Nothing => accounts.decrypt(address, None, &DEFAULT_MAC, &msg).map(WithToken::No),
SignWith::Password(pass) => accounts.decrypt(address, Some(pass), &DEFAULT_MAC, &msg).map(WithToken::No),
SignWith::Token(token) => accounts.decrypt_with_token(address, token, &DEFAULT_MAC, &msg).map(Into::into),
}.map_err(|e| match password {
SignWith::Nothing => errors::signing(e),
_ => errors::password(e),
})
}
/// Extract the default gas price from a client and miner.
pub fn default_gas_price<C, M>(client: &C, miner: &M, percentile: usize) -> U256 where
C: BlockChainClient,
M: MinerService,
{
client.gas_price_corpus(100).percentile(percentile).cloned().unwrap_or_else(|| miner.sensible_gas_price())
}
/// Convert RPC confirmation payload to signer confirmation payload.
/// May need to resolve in the future to fetch things like gas price.
pub fn from_rpc<D>(payload: RpcConfirmationPayload, default_account: Address, dispatcher: &D) -> BoxFuture<ConfirmationPayload>
where D: Dispatcher
{
match payload {
RpcConfirmationPayload::SendTransaction(request) => {
Box::new(dispatcher.fill_optional_fields(request.into(), default_account, false)
.map(ConfirmationPayload::SendTransaction))
},
RpcConfirmationPayload::SignTransaction(request) => {
Box::new(dispatcher.fill_optional_fields(request.into(), default_account, false)
.map(ConfirmationPayload::SignTransaction))
},
RpcConfirmationPayload::Decrypt(RpcDecryptRequest { address, msg }) => {
Box::new(future::ok(ConfirmationPayload::Decrypt(address.into(), msg.into())))
},
RpcConfirmationPayload::EthSignMessage(RpcEthSignRequest { address, data }) => {
Box::new(future::ok(ConfirmationPayload::EthSignMessage(address.into(), data.into())))
},
RpcConfirmationPayload::EIP191SignMessage(RpcSignRequest { address, data }) => {
Box::new(future::ok(ConfirmationPayload::SignMessage(address.into(), data.into())))
},
}
}

View File

@@ -0,0 +1,151 @@
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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 Ethereum 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 Ethereum. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use ethcore::client::BlockChainClient;
use ethcore::miner::{self, MinerService};
use ethereum_types::{H256, U256, Address};
use types::transaction::{SignedTransaction, PendingTransaction};
use parking_lot::Mutex;
use jsonrpc_core::{BoxFuture, Result};
use jsonrpc_core::futures::{future, Future, IntoFuture};
use v1::helpers::{errors, nonce, TransactionRequest, FilledTransactionRequest};
use v1::types::{RichRawTransaction as RpcRichRawTransaction};
use super::prospective_signer::ProspectiveSigner;
use super::{Dispatcher, Accounts, SignWith, PostSign, default_gas_price};
/// A dispatcher which uses references to a client and miner in order to sign
/// requests locally.
#[derive(Debug)]
pub struct FullDispatcher<C, M> {
client: Arc<C>,
miner: Arc<M>,
nonces: Arc<Mutex<nonce::Reservations>>,
gas_price_percentile: usize,
}
impl<C, M> FullDispatcher<C, M> {
/// Create a `FullDispatcher` from Arc references to a client and miner.
pub fn new(
client: Arc<C>,
miner: Arc<M>,
nonces: Arc<Mutex<nonce::Reservations>>,
gas_price_percentile: usize,
) -> Self {
FullDispatcher {
client,
miner,
nonces,
gas_price_percentile,
}
}
}
impl<C, M> Clone for FullDispatcher<C, M> {
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<C: miner::BlockChainClient, M: MinerService> FullDispatcher<C, M> {
fn state_nonce(&self, from: &Address) -> U256 {
self.miner.next_nonce(&*self.client, from)
}
/// Post transaction to the network.
///
/// If transaction is trusted we are more likely to assume it is coming from a local account.
pub fn dispatch_transaction(client: &C, miner: &M, signed_transaction: PendingTransaction, trusted: bool) -> Result<H256> {
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<C: miner::BlockChainClient + BlockChainClient, M: MinerService> Dispatcher for FullDispatcher<C, M> {
fn fill_optional_fields(&self, request: TransactionRequest, default_sender: Address, force_nonce: bool)
-> BoxFuture<FilledTransactionRequest>
{
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<P>(
&self,
filled: FilledTransactionRequest,
signer: &Arc<Accounts>,
password: SignWith,
post_sign: P,
) -> BoxFuture<P::Item>
where
P: PostSign + 'static,
<P::Out as IntoFuture>::Future: Send,
{
let chain_id = self.client.signing_chain_id();
if let Some(nonce) = filled.nonce {
let future = signer.sign_transaction(filled, chain_id, nonce, password)
.into_future()
.and_then(move |signed| post_sign.execute(signed));
Box::new(future)
} else {
let state = self.state_nonce(&filled.from);
let reserved = self.nonces.lock().reserve(filled.from, state);
Box::new(ProspectiveSigner::new(signer.clone(), filled, chain_id, reserved, password, post_sign))
}
}
fn enrich(&self, signed_transaction: SignedTransaction) -> RpcRichRawTransaction {
RpcRichRawTransaction::from_signed(signed_transaction)
}
fn dispatch_transaction(&self, signed_transaction: PendingTransaction) -> Result<H256> {
Self::dispatch_transaction(&*self.client, &*self.miner, signed_transaction, true)
}
}

View File

@@ -0,0 +1,266 @@
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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 Ethereum 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 Ethereum. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use ethereum_types::{H256, Address, U256};
use light::TransactionQueue as LightTransactionQueue;
use light::cache::Cache as LightDataCache;
use light::client::LightChainClient;
use light::on_demand::{request, OnDemand};
use parking_lot::{Mutex, RwLock};
use stats::Corpus;
use sync::LightSync;
use types::basic_account::BasicAccount;
use types::ids::BlockId;
use types::transaction::{SignedTransaction, PendingTransaction, Error as TransactionError};
use jsonrpc_core::{BoxFuture, Result};
use jsonrpc_core::futures::{future, Future, IntoFuture};
use jsonrpc_core::futures::future::Either;
use v1::helpers::{errors, nonce, TransactionRequest, FilledTransactionRequest};
use v1::types::{RichRawTransaction as RpcRichRawTransaction,};
use super::{Dispatcher, Accounts, SignWith, PostSign};
/// Dispatcher for light clients -- fetches default gas price, next nonce, etc. from network.
#[derive(Clone)]
pub struct LightDispatcher {
/// Sync service.
pub sync: Arc<LightSync>,
/// Header chain client.
pub client: Arc<LightChainClient>,
/// On-demand request service.
pub on_demand: Arc<OnDemand>,
/// Data cache.
pub cache: Arc<Mutex<LightDataCache>>,
/// Transaction queue.
pub transaction_queue: Arc<RwLock<LightTransactionQueue>>,
/// Nonce reservations
pub nonces: Arc<Mutex<nonce::Reservations>>,
/// 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<LightSync>,
client: Arc<LightChainClient>,
on_demand: Arc<OnDemand>,
cache: Arc<Mutex<LightDataCache>>,
transaction_queue: Arc<RwLock<LightTransactionQueue>>,
nonces: Arc<Mutex<nonce::Reservations>>,
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<Corpus<U256>> {
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<Option<BasicAccount>> {
let best_header = self.client.best_block_header();
let account_future = self.sync.with_context(|ctx| self.on_demand.request(ctx, request::Account {
header: best_header.into(),
address: addr,
}).expect("no back-references; therefore all back-references valid; qed"));
match account_future {
Some(response) => Box::new(response.map_err(|_| errors::no_light_peers())),
None => Box::new(future::err(errors::network_disabled())),
}
}
/// Get an account's next nonce.
pub fn next_nonce(&self, addr: Address) -> BoxFuture<U256> {
let account_start_nonce = self.client.engine().account_start_nonce(self.client.best_block_header().number());
Box::new(self.account(addr)
.and_then(move |maybe_account| {
future::ok(maybe_account.map_or(account_start_nonce, |account| account.nonce))
})
)
}
}
impl Dispatcher for LightDispatcher {
// Ignore the `force_nonce` flag in order to always query the network when fetching the nonce and
// the account state. If the nonce is specified in the transaction use that nonce instead but do the
// network request anyway to the account state (balance)
fn fill_optional_fields(&self, request: TransactionRequest, default_sender: Address, _force_nonce: bool)
-> BoxFuture<FilledTransactionRequest>
{
const DEFAULT_GAS_PRICE: U256 = U256([0, 0, 0, 21_000_000]);
let gas_limit = self.client.best_block_header().gas_limit();
let request_gas_price = request.gas_price.clone();
let from = request.from.unwrap_or(default_sender);
let with_gas_price = move |gas_price| {
let request = request;
FilledTransactionRequest {
from: from.clone(),
used_default_from: request.from.is_none(),
to: request.to,
nonce: request.nonce,
gas_price: gas_price,
gas: request.gas.unwrap_or_else(|| gas_limit / 3),
value: request.value.unwrap_or_else(|| 0.into()),
data: request.data.unwrap_or_else(Vec::new),
condition: request.condition,
}
};
// fast path for known gas price.
let gas_price_percentile = self.gas_price_percentile;
let gas_price = match request_gas_price {
Some(gas_price) => Either::A(future::ok(with_gas_price(gas_price))),
None => Either::B(fetch_gas_price_corpus(
self.sync.clone(),
self.client.clone(),
self.on_demand.clone(),
self.cache.clone()
).and_then(move |corp| match corp.percentile(gas_price_percentile) {
Some(percentile) => Ok(*percentile),
None => Ok(DEFAULT_GAS_PRICE), // fall back to default on error.
}).map(with_gas_price))
};
let future_account = self.account(from);
Box::new(gas_price.and_then(move |mut filled| {
future_account
.and_then(move |maybe_account| {
let cost = filled.value.saturating_add(filled.gas.saturating_mul(filled.gas_price));
match maybe_account {
Some(ref account) if cost > account.balance => {
Err(errors::transaction(TransactionError::InsufficientBalance {
balance: account.balance,
cost,
}))
}
Some(account) => {
if filled.nonce.is_none() {
filled.nonce = Some(account.nonce);
}
Ok(filled)
}
None => Err(errors::account("Account not found", "")),
}
})
}))
}
fn sign<P>(
&self,
filled: FilledTransactionRequest,
signer: &Arc<Accounts>,
password: SignWith,
post_sign: P
) -> BoxFuture<P::Item>
where
P: PostSign + 'static,
<P::Out as futures::future::IntoFuture>::Future: Send,
{
let chain_id = self.client.signing_chain_id();
let nonce = filled.nonce.expect("nonce is always provided; qed");
let future = signer.sign_transaction(filled, chain_id, nonce, password)
.into_future()
.and_then(move |signed| post_sign.execute(signed));
Box::new(future)
}
fn enrich(&self, signed_transaction: SignedTransaction) -> RpcRichRawTransaction {
RpcRichRawTransaction::from_signed(signed_transaction)
}
fn dispatch_transaction(&self, signed_transaction: PendingTransaction) -> Result<H256> {
let hash = signed_transaction.transaction.hash();
self.transaction_queue.write().import(signed_transaction)
.map_err(errors::transaction)
.map(|_| hash)
}
}
/// Get a recent gas price corpus.
// TODO: this could be `impl Trait`.
pub fn fetch_gas_price_corpus(
sync: Arc<LightSync>,
client: Arc<LightChainClient>,
on_demand: Arc<OnDemand>,
cache: Arc<Mutex<LightDataCache>>,
) -> BoxFuture<Corpus<U256>> {
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::<Vec<_>>();
// 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())),
}
}

View File

@@ -0,0 +1,381 @@
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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 Ethereum 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 Ethereum. If not, see <http://www.gnu.org/licenses/>.
//! Utilities and helpers for transaction dispatch.
pub(crate) mod light;
mod full;
mod prospective_signer;
#[cfg(any(test, feature = "accounts"))]
mod signing;
#[cfg(not(any(test, feature = "accounts")))]
mod signing {
use super::*;
use v1::helpers::errors;
/// Dummy signer implementation
#[derive(Debug, Clone)]
pub struct Signer;
impl Signer {
/// Create new instance of dummy signer (accept any AccountProvider)
pub fn new<T>(_ap: T) -> Self {
Signer
}
}
impl super::Accounts for Signer {
fn sign_transaction(&self, _filled: FilledTransactionRequest, _chain_id: Option<u64>, _nonce: U256, _password: SignWith) -> Result<WithToken<SignedTransaction>> {
Err(errors::account("Signing unsupported", "See #9997"))
}
fn sign_message(&self, _address: Address, _password: SignWith, _hash: SignMessage) -> Result<WithToken<Signature>> {
Err(errors::account("Signing unsupported", "See #9997"))
}
fn decrypt(&self, _address: Address, _password: SignWith, _data: Bytes) -> Result<WithToken<Bytes>> {
Err(errors::account("Signing unsupported", "See #9997"))
}
fn supports_prospective_signing(&self, _address: &Address, _password: &SignWith) -> bool {
false
}
fn default_account(&self) -> Address {
Default::default()
}
fn is_unlocked(&self, _address: &Address) -> bool {
false
}
}
}
pub use self::light::LightDispatcher;
pub use self::full::FullDispatcher;
pub use self::signing::Signer;
pub use v1::helpers::nonce::Reservations;
use std::fmt::Debug;
use std::ops::Deref;
use std::sync::Arc;
use bytes::Bytes;
use ethcore::client::BlockChainClient;
use ethcore::miner::MinerService;
use ethereum_types::{H520, H256, U256, Address};
use ethkey::{Password, Signature};
use hash::keccak;
use types::transaction::{SignedTransaction, PendingTransaction};
use jsonrpc_core::{BoxFuture, Result, Error};
use jsonrpc_core::futures::{future, Future, IntoFuture};
use v1::helpers::{TransactionRequest, FilledTransactionRequest, ConfirmationPayload};
use v1::types::{
H520 as RpcH520, Bytes as RpcBytes,
RichRawTransaction as RpcRichRawTransaction,
ConfirmationPayload as RpcConfirmationPayload,
ConfirmationResponse,
EthSignRequest as RpcEthSignRequest,
EIP191SignRequest as RpcSignRequest,
DecryptRequest as RpcDecryptRequest,
};
/// 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<T>: IntoFuture<T, Error>
/// 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<FilledTransactionRequest>;
/// Sign the given transaction request without dispatching, fetching appropriate nonce.
fn sign<P>(
&self,
filled: FilledTransactionRequest,
signer: &Arc<Accounts>,
password: SignWith,
post_sign: P,
) -> BoxFuture<P::Item> where
P: PostSign + 'static,
<P::Out as futures::future::IntoFuture>::Future: Send;
/// Converts a `SignedTransaction` into `RichRawTransaction`
fn enrich(&self, SignedTransaction) -> RpcRichRawTransaction;
/// "Dispatch" a local transaction.
fn dispatch_transaction(&self, signed_transaction: PendingTransaction) -> Result<H256>;
}
/// Payload to sign
pub enum SignMessage {
/// Eth-sign kind data (requires prefixing)
Data(Bytes),
/// Prefixed data hash
Hash(H256),
}
/// Abstract transaction signer.
///
/// NOTE This signer is semi-correct, it's a temporary measure to avoid moving too much code.
/// If accounts are ultimately removed all password-dealing endpoints will be wiped out.
pub trait Accounts: Send + Sync {
/// Sign given filled transaction request for the specified chain_id.
fn sign_transaction(&self, filled: FilledTransactionRequest, chain_id: Option<u64>, nonce: U256, password: SignWith) -> Result<WithToken<SignedTransaction>>;
/// Sign given message.
fn sign_message(&self, address: Address, password: SignWith, hash: SignMessage) -> Result<WithToken<Signature>>;
/// Decrypt given message.
fn decrypt(&self, address: Address, password: SignWith, data: Bytes) -> Result<WithToken<Bytes>>;
/// Returns `true` if the accounts can sign multiple times.
fn supports_prospective_signing(&self, address: &Address, password: &SignWith) -> bool;
/// Returns default account.
fn default_account(&self) -> Address;
/// Returns true if account is unlocked (i.e. can sign without a password)
fn is_unlocked(&self, address: &Address) -> bool;
}
/// action to execute after signing
/// e.g importing a transaction into the chain
pub trait PostSign: Send {
/// item that this PostSign returns
type Item: Send;
/// incase you need to perform async PostSign actions
type Out: IntoFuture<Item = Self::Item, Error = Error> + Send;
/// perform an action with the signed transaction
fn execute(self, signer: WithToken<SignedTransaction>) -> Self::Out;
}
impl PostSign for () {
type Item = WithToken<SignedTransaction>;
type Out = Result<Self::Item>;
fn execute(self, signed: WithToken<SignedTransaction>) -> Self::Out {
Ok(signed)
}
}
impl<F: Send, T: Send> PostSign for F
where F: FnOnce(WithToken<SignedTransaction>) -> Result<T>
{
type Item = T;
type Out = Result<Self::Item>;
fn execute(self, signed: WithToken<SignedTransaction>) -> Self::Out {
(self)(signed)
}
}
/// Single-use account token.
pub type AccountToken = Password;
/// Values used to unlock accounts for signing.
#[derive(Clone, PartialEq)]
pub enum SignWith {
/// Nothing -- implies the account is already unlocked.
Nothing,
/// Unlock with password.
Password(Password),
/// Unlock with single-use token.
Token(AccountToken),
}
impl SignWith {
fn is_password(&self) -> bool {
if let SignWith::Password(_) = *self {
true
} else {
false
}
}
}
/// A value, potentially accompanied by a signing token.
pub enum WithToken<T> {
/// No token.
No(T),
/// With token.
Yes(T, AccountToken),
}
impl<T: Debug> Deref for WithToken<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
match *self {
WithToken::No(ref v) => v,
WithToken::Yes(ref v, _) => v,
}
}
}
impl<T: Debug> WithToken<T> {
/// Map the value with the given closure, preserving the token.
pub fn map<S, F>(self, f: F) -> WithToken<S> where
S: Debug,
F: FnOnce(T) -> S,
{
match self {
WithToken::No(v) => WithToken::No(f(v)),
WithToken::Yes(v, token) => WithToken::Yes(f(v), token),
}
}
/// Convert into inner value, ignoring possible token.
pub fn into_value(self) -> T {
match self {
WithToken::No(v) => v,
WithToken::Yes(v, _) => v,
}
}
/// Convert the `WithToken` into a tuple.
pub fn into_tuple(self) -> (T, Option<AccountToken>) {
match self {
WithToken::No(v) => (v, None),
WithToken::Yes(v, token) => (v, Some(token))
}
}
}
impl<T: Debug> From<(T, AccountToken)> for WithToken<T> {
fn from(tuple: (T, AccountToken)) -> Self {
WithToken::Yes(tuple.0, tuple.1)
}
}
impl<T: Debug> From<(T, Option<AccountToken>)> for WithToken<T> {
fn from(tuple: (T, Option<AccountToken>)) -> Self {
match tuple.1 {
Some(token) => WithToken::Yes(tuple.0, token),
None => WithToken::No(tuple.0),
}
}
}
/// Execute a confirmation payload.
pub fn execute<D: Dispatcher + 'static>(
dispatcher: D,
signer: &Arc<Accounts>,
payload: ConfirmationPayload,
pass: SignWith
) -> BoxFuture<WithToken<ConfirmationResponse>> {
match payload {
ConfirmationPayload::SendTransaction(request) => {
let condition = request.condition.clone().map(Into::into);
let cloned_dispatcher = dispatcher.clone();
let post_sign = move |with_token_signed: WithToken<SignedTransaction>| {
let (signed, token) = with_token_signed.into_tuple();
let signed_transaction = PendingTransaction::new(signed, condition);
cloned_dispatcher.dispatch_transaction(signed_transaction)
.map(|hash| (hash, token))
};
Box::new(
dispatcher.sign(request, &signer, pass, post_sign).map(|(hash, token)| {
WithToken::from((ConfirmationResponse::SendTransaction(hash.into()), token))
})
)
},
ConfirmationPayload::SignTransaction(request) => {
Box::new(dispatcher.sign(request, &signer, pass, ())
.map(move |result| result
.map(move |tx| dispatcher.enrich(tx))
.map(ConfirmationResponse::SignTransaction)
))
},
ConfirmationPayload::EthSignMessage(address, data) => {
let res = signer.sign_message(address, pass, SignMessage::Data(data))
.map(|result| result
.map(|s| H520(s.into_electrum()))
.map(RpcH520::from)
.map(ConfirmationResponse::Signature)
);
Box::new(future::done(res))
},
ConfirmationPayload::SignMessage(address, data) => {
let res = signer.sign_message(address, pass, SignMessage::Hash(data))
.map(|result| result
.map(|rsv| H520(rsv.into_electrum()))
.map(RpcH520::from)
.map(ConfirmationResponse::Signature)
);
Box::new(future::done(res))
},
ConfirmationPayload::Decrypt(address, data) => {
let res = signer.decrypt(address, pass, data)
.map(|result| result
.map(RpcBytes)
.map(ConfirmationResponse::Decrypt)
);
Box::new(future::done(res))
},
}
}
/// 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)
}
/// Extract the default gas price from a client and miner.
pub fn default_gas_price<C, M>(client: &C, miner: &M, percentile: usize) -> U256 where
C: BlockChainClient,
M: MinerService,
{
client.gas_price_corpus(100).percentile(percentile).cloned().unwrap_or_else(|| miner.sensible_gas_price())
}
/// Convert RPC confirmation payload to signer confirmation payload.
/// May need to resolve in the future to fetch things like gas price.
pub fn from_rpc<D>(payload: RpcConfirmationPayload, default_account: Address, dispatcher: &D) -> BoxFuture<ConfirmationPayload>
where D: Dispatcher
{
match payload {
RpcConfirmationPayload::SendTransaction(request) => {
Box::new(dispatcher.fill_optional_fields(request.into(), default_account, false)
.map(ConfirmationPayload::SendTransaction))
},
RpcConfirmationPayload::SignTransaction(request) => {
Box::new(dispatcher.fill_optional_fields(request.into(), default_account, false)
.map(ConfirmationPayload::SignTransaction))
},
RpcConfirmationPayload::Decrypt(RpcDecryptRequest { address, msg }) => {
Box::new(future::ok(ConfirmationPayload::Decrypt(address.into(), msg.into())))
},
RpcConfirmationPayload::EthSignMessage(RpcEthSignRequest { address, data }) => {
Box::new(future::ok(ConfirmationPayload::EthSignMessage(address.into(), data.into())))
},
RpcConfirmationPayload::EIP191SignMessage(RpcSignRequest { address, data }) => {
Box::new(future::ok(ConfirmationPayload::SignMessage(address.into(), data.into())))
},
}
}

View File

@@ -0,0 +1,152 @@
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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 Ethereum 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 Ethereum. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use ethereum_types::U256;
use jsonrpc_core::{Result, Error};
use jsonrpc_core::futures::{Future, Poll, Async, IntoFuture};
use types::transaction::SignedTransaction;
use v1::helpers::{errors, nonce, FilledTransactionRequest};
use super::{Accounts, SignWith, WithToken, PostSign};
#[derive(Debug, Clone, Copy)]
enum ProspectiveSignerState {
TryProspectiveSign,
WaitForPostSign,
WaitForNonce,
}
pub struct ProspectiveSigner<P: PostSign> {
signer: Arc<Accounts>,
filled: FilledTransactionRequest,
chain_id: Option<u64>,
reserved: nonce::Reserved,
password: SignWith,
state: ProspectiveSignerState,
prospective: Option<WithToken<SignedTransaction>>,
ready: Option<nonce::Ready>,
post_sign: Option<P>,
post_sign_future: Option<<P::Out as IntoFuture>::Future>
}
impl<P: PostSign> ProspectiveSigner<P> {
pub fn new(
signer: Arc<Accounts>,
filled: FilledTransactionRequest,
chain_id: Option<u64>,
reserved: nonce::Reserved,
password: SignWith,
post_sign: P
) -> Self {
let supports_prospective = signer.supports_prospective_signing(&filled.from, &password);
ProspectiveSigner {
signer,
filled,
chain_id,
reserved,
password,
state: if supports_prospective {
ProspectiveSignerState::TryProspectiveSign
} else {
ProspectiveSignerState::WaitForNonce
},
prospective: None,
ready: None,
post_sign: Some(post_sign),
post_sign_future: None
}
}
fn sign(&self, nonce: &U256) -> Result<WithToken<SignedTransaction>> {
self.signer.sign_transaction(
self.filled.clone(),
self.chain_id,
*nonce,
self.password.clone()
)
}
fn poll_reserved(&mut self) -> Poll<nonce::Ready, Error> {
self.reserved.poll().map_err(|_| errors::internal("Nonce reservation failure", ""))
}
}
impl<P: PostSign> Future for ProspectiveSigner<P> {
type Item = P::Item;
type Error = Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
use self::ProspectiveSignerState::*;
loop {
match self.state {
TryProspectiveSign => {
// Try to poll reserved, it might be ready.
match self.poll_reserved()? {
Async::NotReady => {
self.state = WaitForNonce;
self.prospective = Some(self.sign(self.reserved.prospective_value())?);
},
Async::Ready(nonce) => {
self.state = WaitForPostSign;
self.post_sign_future = Some(
self.post_sign.take()
.expect("post_sign is set on creation; qed")
.execute(self.sign(nonce.value())?)
.into_future()
);
self.ready = Some(nonce);
},
}
},
WaitForNonce => {
let nonce = try_ready!(self.poll_reserved());
let prospective = match (self.prospective.take(), nonce.matches_prospective()) {
(Some(prospective), true) => prospective,
_ => self.sign(nonce.value())?,
};
self.ready = Some(nonce);
self.state = WaitForPostSign;
self.post_sign_future = Some(self.post_sign.take()
.expect("post_sign is set on creation; qed")
.execute(prospective)
.into_future());
},
WaitForPostSign => {
if let Some(mut fut) = self.post_sign_future.as_mut() {
match fut.poll()? {
Async::Ready(item) => {
let nonce = self.ready
.take()
.expect("nonce is set before state transitions to WaitForPostSign; qed");
nonce.mark_used();
return Ok(Async::Ready(item))
},
Async::NotReady => {
return Ok(Async::NotReady)
}
}
} else {
panic!("Poll after ready.");
}
}
}
}
}
}

View File

@@ -0,0 +1,156 @@
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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 Ethereum 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 Ethereum. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use accounts::AccountProvider;
use bytes::Bytes;
use crypto::DEFAULT_MAC;
use ethereum_types::{H256, U256, Address};
use ethkey::{Signature};
use types::transaction::{Transaction, Action, SignedTransaction};
use jsonrpc_core::Result;
use v1::helpers::{errors, FilledTransactionRequest};
use super::{eth_data_hash, WithToken, SignWith, SignMessage};
/// Account-aware signer
pub struct Signer {
accounts: Arc<AccountProvider>,
}
impl Signer {
/// Create new instance of signer
pub fn new(accounts: Arc<AccountProvider>) -> Self {
Signer { accounts }
}
}
impl super::Accounts for Signer {
fn sign_transaction(&self, filled: FilledTransactionRequest, chain_id: Option<u64>, nonce: U256, password: SignWith) -> Result<WithToken<SignedTransaction>> {
let t = Transaction {
nonce: nonce,
action: filled.to.map_or(Action::Create, Action::Call),
gas: filled.gas,
gas_price: filled.gas_price,
value: filled.value,
data: filled.data,
};
if self.accounts.is_hardware_address(&filled.from) {
return hardware_signature(&*self.accounts, filled.from, t, chain_id).map(WithToken::No)
}
let hash = t.hash(chain_id);
let signature = signature(&*self.accounts, filled.from, hash, password)?;
Ok(signature.map(|sig| {
SignedTransaction::new(t.with_signature(sig, chain_id))
.expect("Transaction was signed by AccountsProvider; it never produces invalid signatures; qed")
}))
}
fn sign_message(&self, address: Address, password: SignWith, hash: SignMessage) -> Result<WithToken<Signature>> {
if self.accounts.is_hardware_address(&address) {
return if let SignMessage::Data(data) = hash {
let signature = self.accounts.sign_message_with_hardware(&address, &data)
// TODO: is this correct? I guess the `token` is the wallet in this context
.map(WithToken::No)
.map_err(|e| errors::account("Error signing message with hardware_wallet", e));
signature
} else {
Err(errors::account("Error signing message with hardware_wallet", "Message signing is unsupported"))
}
}
match hash {
SignMessage::Data(data) => {
let hash = eth_data_hash(data);
signature(&self.accounts, address, hash, password)
},
SignMessage::Hash(hash) => {
signature(&self.accounts, address, hash, password)
}
}
}
fn decrypt(&self, address: Address, password: SignWith, data: Bytes) -> Result<WithToken<Bytes>> {
if self.accounts.is_hardware_address(&address) {
return Err(errors::unsupported("Decrypting via hardware wallets is not supported.", None));
}
match password.clone() {
SignWith::Nothing => self.accounts.decrypt(address, None, &DEFAULT_MAC, &data).map(WithToken::No),
SignWith::Password(pass) => self.accounts.decrypt(address, Some(pass), &DEFAULT_MAC, &data).map(WithToken::No),
SignWith::Token(token) => self.accounts.decrypt_with_token(address, token, &DEFAULT_MAC, &data).map(Into::into),
}.map_err(|e| match password {
SignWith::Nothing => errors::signing(e),
_ => errors::password(e),
})
}
fn supports_prospective_signing(&self, address: &Address, password: &SignWith) -> bool {
// If the account is permanently unlocked we can try to sign
// using prospective nonce. This should speed up sending
// multiple subsequent transactions in multi-threaded RPC environment.
let is_unlocked_permanently = self.accounts.is_unlocked_permanently(address);
let has_password = password.is_password();
is_unlocked_permanently || has_password
}
fn default_account(&self) -> Address {
self.accounts.default_account().ok().unwrap_or_default()
}
fn is_unlocked(&self, address: &Address) -> bool {
self.accounts.is_unlocked(address)
}
}
fn signature(accounts: &AccountProvider, address: Address, hash: H256, password: SignWith) -> Result<WithToken<Signature>> {
match password.clone() {
SignWith::Nothing => accounts.sign(address, None, hash).map(WithToken::No),
SignWith::Password(pass) => accounts.sign(address, Some(pass), hash).map(WithToken::No),
SignWith::Token(token) => accounts.sign_with_token(address, token, hash).map(Into::into),
}.map_err(|e| match password {
SignWith::Nothing => errors::signing(e),
_ => errors::password(e),
})
}
// obtain a hardware signature from the given account.
fn hardware_signature(accounts: &AccountProvider, address: Address, t: Transaction, chain_id: Option<u64>)
-> Result<SignedTransaction>
{
debug_assert!(accounts.is_hardware_address(&address));
let mut stream = rlp::RlpStream::new();
t.rlp_append_unsigned_transaction(&mut stream, chain_id);
let signature = accounts.sign_transaction_with_hardware(&address, &t, chain_id, &stream.as_raw())
.map_err(|e| {
debug!(target: "miner", "Error signing transaction with hardware wallet: {}", e);
errors::account("Error signing transaction with hardware wallet", e)
})?;
SignedTransaction::new(t.with_signature(signature, chain_id))
.map_err(|e| {
debug!(target: "miner", "Hardware wallet has produced invalid signature: {}", e);
errors::account("Invalid signature generated", e)
})
}

View File

@@ -0,0 +1,51 @@
// 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 <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use accounts::AccountProvider;
use ethkey::{self, Address, Password};
/// An implementation of EngineSigner using internal account management.
pub struct EngineSigner {
accounts: Arc<AccountProvider>,
address: Address,
password: Password,
}
impl EngineSigner {
/// Creates new `EngineSigner` given account manager and account details.
pub fn new(accounts: Arc<AccountProvider>, address: Address, password: Password) -> Self {
EngineSigner { accounts, address, password }
}
}
impl ethcore::engines::EngineSigner for EngineSigner {
fn sign(&self, message: ethkey::Message) -> Result<ethkey::Signature, ethkey::Error> {
match self.accounts.sign(self.address, Some(self.password.clone()), message) {
Ok(ok) => Ok(ok),
Err(e) => {
warn!("Unable to sign consensus message: {:?}", e);
Err(ethkey::Error::InvalidSecret)
},
}
}
fn address(&self) -> Address {
self.address
}
}

View File

@@ -18,7 +18,6 @@
use std::fmt;
use ethcore::account_provider::SignError as AccountError;
use ethcore::error::{Error as EthcoreError, ErrorKind, CallError};
use ethcore::client::BlockId;
use jsonrpc_core::{futures, Result as RpcResult, Error, ErrorCode, Value};
@@ -337,14 +336,6 @@ pub fn fetch<T: fmt::Debug>(error: T) -> Error {
}
}
pub fn signing(error: AccountError) -> Error {
Error {
code: ErrorCode::ServerError(codes::ACCOUNT_LOCKED),
message: "Your account is locked. Unlock the account via CLI, personal_unlockAccount or use Trusted Signer.".into(),
data: Some(Value::String(format!("{:?}", error))),
}
}
pub fn invalid_call_data<T: fmt::Display>(error: T) -> Error {
Error {
code: ErrorCode::ServerError(codes::ENCODING_ERROR),
@@ -353,7 +344,17 @@ pub fn invalid_call_data<T: fmt::Display>(error: T) -> Error {
}
}
pub fn password(error: AccountError) -> Error {
#[cfg(any(test, feature = "accounts"))]
pub fn signing(error: ::accounts::SignError) -> Error {
Error {
code: ErrorCode::ServerError(codes::ACCOUNT_LOCKED),
message: "Your account is locked. Unlock the account via CLI, personal_unlockAccount or use Trusted Signer.".into(),
data: Some(Value::String(format!("{:?}", error))),
}
}
#[cfg(any(test, feature = "accounts"))]
pub fn password(error: ::accounts::SignError) -> Error {
Error {
code: ErrorCode::ServerError(codes::PASSWORD_INVALID),
message: "Account password is invalid or account does not exist.".into(),

View File

@@ -14,23 +14,22 @@
// You should have received a copy of the GNU General Public License
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
//! An list of requests to be confirmed or signed by an external approver/signer.
use std::sync::Arc;
use std::ops::Deref;
use http::Origin;
use parking_lot::Mutex;
use transient_hashmap::TransientHashMap;
use ethstore::random_string;
mod oneshot;
mod signing_queue;
use v1::helpers::signing_queue::{ConfirmationsQueue};
const TOKEN_LIFETIME_SECS: u32 = 3600;
pub use self::signing_queue::{SigningQueue, ConfirmationsQueue, ConfirmationReceiver, ConfirmationResult};
#[cfg(test)]
pub use self::signing_queue::QueueEvent;
/// Manages communication with Signer crate
pub struct SignerService {
is_enabled: bool,
queue: Arc<ConfirmationsQueue>,
web_proxy_tokens: Mutex<TransientHashMap<String, Origin>>,
generate_new_token: Box<Fn() -> Result<String, String> + Send + Sync + 'static>,
}
@@ -40,26 +39,11 @@ impl SignerService {
where F: Fn() -> Result<String, String> + Send + Sync + 'static {
SignerService {
queue: Arc::new(ConfirmationsQueue::default()),
web_proxy_tokens: Mutex::new(TransientHashMap::new(TOKEN_LIFETIME_SECS)),
generate_new_token: Box::new(new_token),
is_enabled: is_enabled,
}
}
/// Checks if the token is valid web proxy access token.
pub fn web_proxy_access_token_domain(&self, token: &String) -> Option<Origin> {
self.web_proxy_tokens.lock().get(token).cloned()
}
/// Generates a new web proxy access token.
pub fn generate_web_proxy_access_token(&self, domain: Origin) -> String {
let token = random_string(16);
let mut tokens = self.web_proxy_tokens.lock();
tokens.prune();
tokens.insert(token.clone(), domain);
token
}
/// Generates new signer authorization token.
pub fn generate_token(&self) -> Result<String, String> {
(self.generate_new_token)()

View File

@@ -15,28 +15,18 @@
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
use std::collections::BTreeMap;
use ethereum_types::{U256, Address};
use ethereum_types::U256;
use parking_lot::{Mutex, RwLock};
use v1::helpers::{ConfirmationRequest, ConfirmationPayload, oneshot, errors};
use v1::types::{ConfirmationResponse, H160 as RpcH160, Origin};
use super::oneshot;
use v1::helpers::errors;
use v1::helpers::requests::{ConfirmationRequest, ConfirmationPayload};
use v1::types::{ConfirmationResponse, Origin};
use jsonrpc_core::Error;
/// Result that can be returned from JSON RPC.
pub type ConfirmationResult = Result<ConfirmationResponse, Error>;
/// Type of default account
pub enum DefaultAccount {
/// Default account is known
Provided(Address),
}
impl From<RpcH160> for DefaultAccount {
fn from(address: RpcH160) -> Self {
DefaultAccount::Provided(address.into())
}
}
/// Possible events happening in the queue that can be listened to.
#[derive(Debug, PartialEq, Clone)]
pub enum QueueEvent {
@@ -225,9 +215,8 @@ mod test {
use ethereum_types::{U256, Address};
use parking_lot::Mutex;
use jsonrpc_core::futures::Future;
use v1::helpers::{
SigningQueue, ConfirmationsQueue, QueueEvent, FilledTransactionRequest, ConfirmationPayload,
};
use v1::helpers::external_signer::{SigningQueue, ConfirmationsQueue, QueueEvent};
use v1::helpers::{FilledTransactionRequest, ConfirmationPayload};
use v1::types::ConfirmationResponse;
fn request() -> ConfirmationPayload {
@@ -299,3 +288,4 @@ mod test {
assert_eq!(el.payload, request);
}
}

View File

@@ -231,7 +231,7 @@ impl LightFetch {
let gas_price_percentile = self.gas_price_percentile;
let gas_price_fut = match req.gas_price {
Some(price) => Either::A(future::ok(price)),
None => Either::B(dispatch::fetch_gas_price_corpus(
None => Either::B(dispatch::light::fetch_gas_price_corpus(
self.sync.clone(),
self.client.clone(),
self.on_demand.clone(),

View File

@@ -18,21 +18,22 @@
pub mod errors;
pub mod block_import;
pub mod deprecated;
pub mod dispatch;
pub mod eip191;
#[cfg(any(test, feature = "accounts"))]
pub mod engine_signer;
pub mod external_signer;
pub mod fake_sign;
pub mod ipfs;
pub mod light_fetch;
pub mod nonce;
pub mod oneshot;
pub mod secretstore;
pub mod eip191;
mod network_settings;
mod poll_filter;
mod poll_manager;
mod requests;
mod signer;
mod signing_queue;
mod subscribers;
mod subscription_manager;
mod work;
@@ -46,12 +47,6 @@ pub use self::poll_filter::{PollFilter, SyncPollFilter, limit_logs};
pub use self::requests::{
TransactionRequest, FilledTransactionRequest, ConfirmationRequest, ConfirmationPayload, CallRequest,
};
pub use self::signing_queue::{
ConfirmationsQueue, ConfirmationReceiver, ConfirmationResult, ConfirmationSender,
SigningQueue, QueueEvent, DefaultAccount,
QUEUE_LIMIT as SIGNING_QUEUE_LIMIT,
};
pub use self::signer::SignerService;
pub use self::subscribers::Subscribers;
pub use self::subscription_manager::GenericPollManager;
pub use self::work::submit_work_detail;

View File

@@ -14,11 +14,10 @@
// You should have received a copy of the GNU General Public License
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
use ethereum_types::{U256, Address};
use ethereum_types::{U256, H256, Address};
use bytes::Bytes;
use v1::types::{Origin, TransactionCondition};
use ethereum_types::H256;
/// Transaction request coming from RPC
#[derive(Debug, Clone, Default, Eq, PartialEq, Hash)]

View File

@@ -53,8 +53,7 @@ pub fn verify_signature(
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use ethcore::account_provider::AccountProvider;
use ethkey::Generator;
use v1::types::H160;
pub fn add_chain_replay_protection(v: u64, chain_id: Option<u64>) -> u64 {
@@ -71,9 +70,9 @@ mod tests {
/// mocked signer
fn sign(should_prefix: bool, data: Vec<u8>, signing_chain_id: Option<u64>) -> (H160, [u8; 32], [u8; 32], U64) {
let hash = if should_prefix { eth_data_hash(data) } else { keccak(data) };
let accounts = Arc::new(AccountProvider::transient_provider());
let address = accounts.new_account(&"password123".into()).unwrap();
let sig = accounts.sign(address, Some("password123".into()), hash).unwrap();
let account = ethkey::Random.generate().unwrap();
let address = account.address();
let sig = ethkey::sign(account.secret(), &hash).unwrap();
let (r, s, v) = (sig.r(), sig.s(), sig.v());
let v = add_chain_replay_protection(v as u64, signing_chain_id);
let (r_buf, s_buf) = {

View File

@@ -25,7 +25,6 @@ use ethereum_types::{U256, H256, H160, Address};
use parking_lot::Mutex;
use ethash::{self, SeedHashCompute};
use ethcore::account_provider::AccountProvider;
use ethcore::client::{BlockChainClient, BlockId, TransactionId, UncleId, StateOrBlock, StateClient, StateInfo, Call, EngineInfo, ProvingBlockChainClient};
use ethcore::miner::{self, MinerService};
use ethcore::snapshot::SnapshotService;
@@ -41,6 +40,7 @@ use jsonrpc_core::{BoxFuture, Result};
use jsonrpc_core::futures::future;
use v1::helpers::{self, errors, limit_logs, fake_sign};
use v1::helpers::deprecated::{self, DeprecationNotice};
use v1::helpers::dispatch::{FullDispatcher, default_gas_price};
use v1::helpers::block_import::is_major_importing;
use v1::traits::Eth;
@@ -105,11 +105,12 @@ pub struct EthClient<C, SN: ?Sized, S: ?Sized, M, EM> where
client: Arc<C>,
snapshot: Arc<SN>,
sync: Arc<S>,
accounts: Arc<AccountProvider>,
accounts: Arc<Fn() -> Vec<Address> + Send + Sync>,
miner: Arc<M>,
external_miner: Arc<EM>,
seed_compute: Mutex<SeedHashCompute>,
options: EthClientOptions,
deprecation_notice: DeprecationNotice,
}
#[derive(Debug)]
@@ -184,7 +185,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> EthClient<C, SN, S
client: &Arc<C>,
snapshot: &Arc<SN>,
sync: &Arc<S>,
accounts: &Arc<AccountProvider>,
accounts: &Arc<Fn() -> Vec<Address> + Send + Sync>,
miner: &Arc<M>,
em: &Arc<EM>,
options: EthClientOptions
@@ -198,6 +199,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> EthClient<C, SN, S
external_miner: em.clone(),
seed_compute: Mutex::new(SeedHashCompute::default()),
options: options,
deprecation_notice: Default::default(),
}
}
@@ -531,9 +533,9 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
fn author(&self) -> Result<RpcH160> {
let miner = self.miner.authoring_params().author;
if miner == 0.into() {
self.accounts.accounts()
.ok()
.and_then(|a| a.first().cloned())
(self.accounts)()
.first()
.cloned()
.map(From::from)
.ok_or_else(|| errors::account("No accounts were found", ""))
} else {
@@ -558,8 +560,9 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
}
fn accounts(&self) -> Result<Vec<RpcH160>> {
let accounts = self.accounts.accounts()
.map_err(|e| errors::account("Could not fetch accounts.", e))?;
self.deprecation_notice.print("eth_accounts", deprecated::msgs::ACCOUNTS);
let accounts = (self.accounts)();
Ok(accounts.into_iter().map(Into::into).collect())
}
@@ -593,7 +596,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
BlockNumber::Earliest => BlockId::Earliest,
BlockNumber::Latest => BlockId::Latest,
BlockNumber::Pending => {
warn!("`Pending` is deprecated and may be removed in future versions. Falling back to `Latest`");
self.deprecation_notice.print("`Pending`", Some("falling back to `Latest`"));
BlockId::Latest
}
};

View File

@@ -28,8 +28,7 @@ use light::client::LightChainClient;
use light::{cht, TransactionQueue};
use light::on_demand::{request, OnDemand};
use ethcore::account_provider::AccountProvider;
use ethereum_types::U256;
use ethereum_types::{U256, Address};
use hash::{KECCAK_NULL_RLP, KECCAK_EMPTY_LIST_RLP};
use parking_lot::{RwLock, Mutex};
use rlp::Rlp;
@@ -42,6 +41,7 @@ use types::ids::BlockId;
use v1::impls::eth_filter::Filterable;
use v1::helpers::{errors, limit_logs};
use v1::helpers::{SyncPollFilter, PollManager};
use v1::helpers::deprecated::{self, DeprecationNotice};
use v1::helpers::light_fetch::{self, LightFetch};
use v1::traits::Eth;
use v1::types::{
@@ -60,11 +60,12 @@ pub struct EthClient<T> {
client: Arc<T>,
on_demand: Arc<OnDemand>,
transaction_queue: Arc<RwLock<TransactionQueue>>,
accounts: Arc<AccountProvider>,
accounts: Arc<Fn() -> Vec<Address> + Send + Sync>,
cache: Arc<Mutex<LightDataCache>>,
polls: Mutex<PollManager<SyncPollFilter>>,
poll_lifetime: u32,
gas_price_percentile: usize,
deprecation_notice: DeprecationNotice,
}
impl<T> Clone for EthClient<T> {
@@ -80,6 +81,7 @@ impl<T> Clone for EthClient<T> {
polls: Mutex::new(PollManager::new(self.poll_lifetime)),
poll_lifetime: self.poll_lifetime,
gas_price_percentile: self.gas_price_percentile,
deprecation_notice: Default::default(),
}
}
}
@@ -92,7 +94,7 @@ impl<T: LightChainClient + 'static> EthClient<T> {
client: Arc<T>,
on_demand: Arc<OnDemand>,
transaction_queue: Arc<RwLock<TransactionQueue>>,
accounts: Arc<AccountProvider>,
accounts: Arc<Fn() -> Vec<Address> + Send + Sync>,
cache: Arc<Mutex<LightDataCache>>,
gas_price_percentile: usize,
poll_lifetime: u32
@@ -107,6 +109,7 @@ impl<T: LightChainClient + 'static> EthClient<T> {
polls: Mutex::new(PollManager::new(poll_lifetime)),
poll_lifetime,
gas_price_percentile,
deprecation_notice: Default::default(),
}
}
@@ -235,9 +238,9 @@ impl<T: LightChainClient + 'static> Eth for EthClient<T> {
}
fn author(&self) -> Result<RpcH160> {
self.accounts.accounts()
.ok()
.and_then(|a| a.first().cloned())
(self.accounts)()
.first()
.cloned()
.map(From::from)
.ok_or_else(|| errors::account("No accounts were found", ""))
}
@@ -262,9 +265,12 @@ impl<T: LightChainClient + 'static> Eth for EthClient<T> {
}
fn accounts(&self) -> Result<Vec<RpcH160>> {
self.accounts.accounts()
.map_err(|e| errors::account("Could not fetch accounts.", e))
.map(|accs| accs.into_iter().map(Into::<RpcH160>::into).collect())
self.deprecation_notice.print("eth_accounts", deprecated::msgs::ACCOUNTS);
Ok((self.accounts)()
.into_iter()
.map(Into::into)
.collect())
}
fn block_number(&self) -> Result<RpcU256> {

View File

@@ -16,7 +16,7 @@
//! Parity-specific rpc implementation.
use std::sync::Arc;
use std::collections::{BTreeMap, HashSet};
use std::collections::BTreeMap;
use version::version_data;
@@ -24,12 +24,12 @@ use crypto::DEFAULT_MAC;
use ethkey::{crypto::ecies, Brain, Generator};
use ethstore::random_phrase;
use sync::LightSyncProvider;
use ethcore::account_provider::AccountProvider;
use ethcore_logger::RotatingLogger;
use jsonrpc_core::{Result, BoxFuture};
use jsonrpc_core::futures::{future, Future};
use v1::helpers::{self, errors, ipfs, SigningQueue, SignerService, NetworkSettings, verify_signature};
use v1::helpers::{self, errors, ipfs, NetworkSettings, verify_signature};
use v1::helpers::external_signer::{SignerService, SigningQueue};
use v1::helpers::dispatch::LightDispatcher;
use v1::helpers::light_fetch::{LightFetch, light_all_transactions};
use v1::metadata::Metadata;
@@ -40,7 +40,7 @@ use v1::types::{
TransactionStats, LocalTransactionStatus,
LightBlockNumber, ChainStatus, Receipt,
BlockNumber, ConsensusCapability, VersionInfo,
OperationsInfo, AccountInfo, HwAccountInfo, Header, RichHeader, RecoveredAccount,
OperationsInfo, Header, RichHeader, RecoveredAccount,
Log, Filter,
};
use Host;
@@ -48,7 +48,6 @@ use Host;
/// Parity implementation for light client.
pub struct ParityClient {
light_dispatch: Arc<LightDispatcher>,
accounts: Arc<AccountProvider>,
logger: Arc<RotatingLogger>,
settings: Arc<NetworkSettings>,
signer: Option<Arc<SignerService>>,
@@ -60,7 +59,6 @@ impl ParityClient {
/// Creates new `ParityClient`.
pub fn new(
light_dispatch: Arc<LightDispatcher>,
accounts: Arc<AccountProvider>,
logger: Arc<RotatingLogger>,
settings: Arc<NetworkSettings>,
signer: Option<Arc<SignerService>>,
@@ -69,7 +67,6 @@ impl ParityClient {
) -> Self {
ParityClient {
light_dispatch,
accounts,
logger,
settings,
signer,
@@ -93,49 +90,6 @@ impl ParityClient {
impl Parity for ParityClient {
type Metadata = Metadata;
fn accounts_info(&self) -> Result<BTreeMap<H160, AccountInfo>> {
let store = &self.accounts;
let dapp_accounts = store
.accounts()
.map_err(|e| errors::account("Could not fetch accounts.", e))?
.into_iter().collect::<HashSet<_>>();
let info = store.accounts_info().map_err(|e| errors::account("Could not fetch account info.", e))?;
let other = store.addresses_info();
Ok(info
.into_iter()
.chain(other.into_iter())
.filter(|&(ref a, _)| dapp_accounts.contains(a))
.map(|(a, v)| (H160::from(a), AccountInfo { name: v.name }))
.collect()
)
}
fn hardware_accounts_info(&self) -> Result<BTreeMap<H160, HwAccountInfo>> {
let store = &self.accounts;
let info = store.hardware_accounts_info().map_err(|e| errors::account("Could not fetch account info.", e))?;
Ok(info
.into_iter()
.map(|(a, v)| (H160::from(a), HwAccountInfo { name: v.name, manufacturer: v.meta }))
.collect()
)
}
fn locked_hardware_accounts_info(&self) -> Result<Vec<String>> {
let store = &self.accounts;
Ok(store.locked_hardware_accounts().map_err(|e| errors::account("Error communicating with hardware wallet.", e))?)
}
fn default_account(&self) -> Result<H160> {
Ok(self.accounts
.accounts()
.ok()
.and_then(|accounts| accounts.get(0).cloned())
.map(|acc| acc.into())
.unwrap_or_default())
}
fn transactions_limit(&self) -> Result<usize> {
Ok(usize::max_value())
}

View File

@@ -67,7 +67,7 @@ impl<F: Fetch> ParitySet for ParitySetClient<F> {
Err(errors::light_unimplemented(None))
}
fn set_engine_signer(&self, _address: H160, _password: String) -> Result<bool> {
fn set_engine_signer_secret(&self, _secret: H256) -> Result<bool> {
Err(errors::light_unimplemented(None))
}

View File

@@ -22,12 +22,15 @@ mod eth_filter;
mod eth_pubsub;
mod net;
mod parity;
#[cfg(any(test, feature = "accounts"))]
mod parity_accounts;
mod parity_set;
#[cfg(any(test, feature = "accounts"))]
mod personal;
mod private;
mod pubsub;
mod rpc;
#[cfg(any(test, feature = "accounts"))]
mod secretstore;
mod signer;
mod signing;
@@ -43,12 +46,17 @@ pub use self::eth_filter::EthFilterClient;
pub use self::eth_pubsub::EthPubSubClient;
pub use self::net::NetClient;
pub use self::parity::ParityClient;
#[cfg(any(test, feature = "accounts"))]
pub use self::parity_accounts::ParityAccountsClient;
pub use self::parity_set::ParitySetClient;
#[cfg(any(test, feature = "accounts"))]
pub use self::parity_set::accounts::ParitySetAccountsClient;
#[cfg(any(test, feature = "accounts"))]
pub use self::personal::PersonalClient;
pub use self::private::PrivateClient;
pub use self::pubsub::PubSubClient;
pub use self::rpc::RpcClient;
#[cfg(any(test, feature = "accounts"))]
pub use self::secretstore::SecretStoreClient;
pub use self::signer::SignerClient;
pub use self::signing::SigningQueueClient;

View File

@@ -17,18 +17,15 @@
//! Parity-specific rpc implementation.
use std::sync::Arc;
use std::str::FromStr;
use std::collections::{BTreeMap, HashSet};
use ethereum_types::Address;
use version::version_data;
use std::collections::BTreeMap;
use crypto::DEFAULT_MAC;
use ethcore::account_provider::AccountProvider;
use ethcore::client::{BlockChainClient, StateClient, Call};
use ethcore::miner::{self, MinerService};
use ethcore::snapshot::{SnapshotService, RestorationStatus};
use ethcore::state::StateInfo;
use ethcore_logger::RotatingLogger;
use ethereum_types::Address;
use ethkey::{crypto::ecies, Brain, Generator};
use ethstore::random_phrase;
use jsonrpc_core::futures::future;
@@ -36,9 +33,11 @@ use jsonrpc_core::{BoxFuture, Result};
use sync::{SyncProvider, ManageNetwork};
use types::ids::BlockId;
use updater::{Service as UpdateService};
use version::version_data;
use v1::helpers::block_import::is_major_importing;
use v1::helpers::{self, errors, fake_sign, ipfs, SigningQueue, SignerService, NetworkSettings, verify_signature};
use v1::helpers::{self, errors, fake_sign, ipfs, NetworkSettings, verify_signature};
use v1::helpers::external_signer::{SigningQueue, SignerService};
use v1::metadata::Metadata;
use v1::traits::Parity;
use v1::types::{
@@ -47,7 +46,7 @@ use v1::types::{
TransactionStats, LocalTransactionStatus,
BlockNumber, ConsensusCapability, VersionInfo,
OperationsInfo, ChainStatus, Log, Filter,
AccountInfo, HwAccountInfo, RichHeader, Receipt, RecoveredAccount,
RichHeader, Receipt, RecoveredAccount,
block_number_to_id
};
use Host;
@@ -59,7 +58,6 @@ pub struct ParityClient<C, M, U> {
updater: Arc<U>,
sync: Arc<SyncProvider>,
net: Arc<ManageNetwork>,
accounts: Arc<AccountProvider>,
logger: Arc<RotatingLogger>,
settings: Arc<NetworkSettings>,
signer: Option<Arc<SignerService>>,
@@ -77,7 +75,6 @@ impl<C, M, U> ParityClient<C, M, U> where
sync: Arc<SyncProvider>,
updater: Arc<U>,
net: Arc<ManageNetwork>,
accounts: Arc<AccountProvider>,
logger: Arc<RotatingLogger>,
settings: Arc<NetworkSettings>,
signer: Option<Arc<SignerService>>,
@@ -90,7 +87,6 @@ impl<C, M, U> ParityClient<C, M, U> where
sync,
updater,
net,
accounts,
logger,
settings,
signer,
@@ -108,43 +104,6 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
{
type Metadata = Metadata;
fn accounts_info(&self) -> Result<BTreeMap<H160, AccountInfo>> {
let dapp_accounts = self.accounts.accounts()
.map_err(|e| errors::account("Could not fetch accounts.", e))?
.into_iter().collect::<HashSet<_>>();
let info = self.accounts.accounts_info().map_err(|e| errors::account("Could not fetch account info.", e))?;
let other = self.accounts.addresses_info();
Ok(info
.into_iter()
.chain(other.into_iter())
.filter(|&(ref a, _)| dapp_accounts.contains(a))
.map(|(a, v)| (H160::from(a), AccountInfo { name: v.name }))
.collect()
)
}
fn hardware_accounts_info(&self) -> Result<BTreeMap<H160, HwAccountInfo>> {
let info = self.accounts.hardware_accounts_info().map_err(|e| errors::account("Could not fetch account info.", e))?;
Ok(info
.into_iter()
.map(|(a, v)| (H160::from(a), HwAccountInfo { name: v.name, manufacturer: v.meta }))
.collect()
)
}
fn locked_hardware_accounts_info(&self) -> Result<Vec<String>> {
self.accounts.locked_hardware_accounts().map_err(|e| errors::account("Error communicating with hardware wallet.", e))
}
fn default_account(&self) -> Result<H160> {
Ok(self.accounts.default_account()
.map(Into::into)
.ok()
.unwrap_or_default())
}
fn transactions_limit(&self) -> Result<usize> {
Ok(self.miner.queue_status().limits.max_count)
}

View File

@@ -16,21 +16,29 @@
//! Account management (personal) rpc implementation
use std::sync::Arc;
use std::collections::btree_map::{BTreeMap, Entry};
use std::collections::{
btree_map::{BTreeMap, Entry},
HashSet,
};
use ethereum_types::Address;
use ethkey::{Brain, Generator, Secret};
use ethstore::KeyFile;
use ethcore::account_provider::AccountProvider;
use accounts::AccountProvider;
use jsonrpc_core::Result;
use v1::helpers::deprecated::{self, DeprecationNotice};
use v1::helpers::errors;
use v1::traits::ParityAccounts;
use v1::types::{H160 as RpcH160, H256 as RpcH256, H520 as RpcH520, Derive, DeriveHierarchical, DeriveHash, ExtAccountInfo};
use v1::traits::{ParityAccounts, ParityAccountsInfo};
use v1::types::{
H160 as RpcH160, H256 as RpcH256, H520 as RpcH520, Derive, DeriveHierarchical, DeriveHash,
ExtAccountInfo, AccountInfo, HwAccountInfo,
};
use ethkey::Password;
/// Account management (personal) rpc implementation.
pub struct ParityAccountsClient {
accounts: Arc<AccountProvider>,
deprecation_notice: DeprecationNotice,
}
impl ParityAccountsClient {
@@ -38,12 +46,68 @@ impl ParityAccountsClient {
pub fn new(store: &Arc<AccountProvider>) -> Self {
ParityAccountsClient {
accounts: store.clone(),
deprecation_notice: Default::default(),
}
}
}
impl ParityAccountsClient {
fn deprecation_notice(&self, method: &'static str) {
self.deprecation_notice.print(method, deprecated::msgs::ACCOUNTS);
}
}
impl ParityAccountsInfo for ParityAccountsClient {
fn accounts_info(&self) -> Result<BTreeMap<RpcH160, AccountInfo>> {
self.deprecation_notice("parity_accountsInfo");
let dapp_accounts = self.accounts.accounts()
.map_err(|e| errors::account("Could not fetch accounts.", e))?
.into_iter().collect::<HashSet<_>>();
let info = self.accounts.accounts_info().map_err(|e| errors::account("Could not fetch account info.", e))?;
let other = self.accounts.addresses_info();
Ok(info
.into_iter()
.chain(other.into_iter())
.filter(|&(ref a, _)| dapp_accounts.contains(a))
.map(|(a, v)| (RpcH160::from(a), AccountInfo { name: v.name }))
.collect()
)
}
fn hardware_accounts_info(&self) -> Result<BTreeMap<RpcH160, HwAccountInfo>> {
self.deprecation_notice("parity_hardwareAccountsInfo");
let info = self.accounts.hardware_accounts_info().map_err(|e| errors::account("Could not fetch account info.", e))?;
Ok(info
.into_iter()
.map(|(a, v)| (RpcH160::from(a), HwAccountInfo { name: v.name, manufacturer: v.meta }))
.collect()
)
}
fn locked_hardware_accounts_info(&self) -> Result<Vec<String>> {
self.deprecation_notice("parity_lockedHardwareAccountsInfo");
self.accounts.locked_hardware_accounts().map_err(|e| errors::account("Error communicating with hardware wallet.", e))
}
fn default_account(&self) -> Result<RpcH160> {
self.deprecation_notice("parity_defaultAccount");
Ok(self.accounts.default_account()
.map(Into::into)
.ok()
.unwrap_or_default())
}
}
impl ParityAccounts for ParityAccountsClient {
fn all_accounts_info(&self) -> Result<BTreeMap<RpcH160, ExtAccountInfo>> {
self.deprecation_notice("parity_allAccountsInfo");
let info = self.accounts.accounts_info().map_err(|e| errors::account("Could not fetch account info.", e))?;
let other = self.accounts.addresses_info();
@@ -75,6 +139,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn new_account_from_phrase(&self, phrase: String, pass: Password) -> Result<RpcH160> {
self.deprecation_notice("parity_newAccountFromPhrase");
let brain = Brain::new(phrase).generate().unwrap();
self.accounts.insert_account(brain.secret().clone(), &pass)
.map(Into::into)
@@ -82,6 +148,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn new_account_from_wallet(&self, json: String, pass: Password) -> Result<RpcH160> {
self.deprecation_notice("parity_newAccountFromWallet");
self.accounts.import_presale(json.as_bytes(), &pass)
.or_else(|_| self.accounts.import_wallet(json.as_bytes(), &pass, true))
.map(Into::into)
@@ -89,6 +157,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn new_account_from_secret(&self, secret: RpcH256, pass: Password) -> Result<RpcH160> {
self.deprecation_notice("parity_newAccountFromSecret");
let secret = Secret::from_unsafe_slice(&secret.0)
.map_err(|e| errors::account("Could not create account.", e))?;
self.accounts.insert_account(secret, &pass)
@@ -97,6 +167,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn test_password(&self, account: RpcH160, password: Password) -> Result<bool> {
self.deprecation_notice("parity_testPassword");
let account: Address = account.into();
self.accounts
@@ -105,6 +177,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn change_password(&self, account: RpcH160, password: Password, new_password: Password) -> Result<bool> {
self.deprecation_notice("parity_changePassword");
let account: Address = account.into();
self.accounts
.change_password(&account, password, new_password)
@@ -113,6 +187,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn kill_account(&self, account: RpcH160, password: Password) -> Result<bool> {
self.deprecation_notice("parity_killAccount");
let account: Address = account.into();
self.accounts
.kill_account(&account, &password)
@@ -121,6 +197,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn remove_address(&self, addr: RpcH160) -> Result<bool> {
self.deprecation_notice("parity_removeAddresss");
let addr: Address = addr.into();
self.accounts.remove_address(addr);
@@ -128,6 +206,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn set_account_name(&self, addr: RpcH160, name: String) -> Result<bool> {
self.deprecation_notice("parity_setAccountName");
let addr: Address = addr.into();
self.accounts.set_account_name(addr.clone(), name.clone())
@@ -136,6 +216,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn set_account_meta(&self, addr: RpcH160, meta: String) -> Result<bool> {
self.deprecation_notice("parity_setAccountMeta");
let addr: Address = addr.into();
self.accounts.set_account_meta(addr.clone(), meta.clone())
@@ -144,6 +226,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn import_geth_accounts(&self, addresses: Vec<RpcH160>) -> Result<Vec<RpcH160>> {
self.deprecation_notice("parity_importGethAccounts");
self.accounts
.import_geth_accounts(into_vec(addresses), false)
.map(into_vec)
@@ -151,10 +235,14 @@ impl ParityAccounts for ParityAccountsClient {
}
fn geth_accounts(&self) -> Result<Vec<RpcH160>> {
self.deprecation_notice("parity_listGethAccounts");
Ok(into_vec(self.accounts.list_geth_accounts(false)))
}
fn create_vault(&self, name: String, password: Password) -> Result<bool> {
self.deprecation_notice("parity_newVault");
self.accounts
.create_vault(&name, &password)
.map_err(|e| errors::account("Could not create vault.", e))
@@ -162,6 +250,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn open_vault(&self, name: String, password: Password) -> Result<bool> {
self.deprecation_notice("parity_openVault");
self.accounts
.open_vault(&name, &password)
.map_err(|e| errors::account("Could not open vault.", e))
@@ -169,6 +259,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn close_vault(&self, name: String) -> Result<bool> {
self.deprecation_notice("parity_closeVault");
self.accounts
.close_vault(&name)
.map_err(|e| errors::account("Could not close vault.", e))
@@ -176,18 +268,24 @@ impl ParityAccounts for ParityAccountsClient {
}
fn list_vaults(&self) -> Result<Vec<String>> {
self.deprecation_notice("parity_listVaults");
self.accounts
.list_vaults()
.map_err(|e| errors::account("Could not list vaults.", e))
}
fn list_opened_vaults(&self) -> Result<Vec<String>> {
self.deprecation_notice("parity_listOpenedVaults");
self.accounts
.list_opened_vaults()
.map_err(|e| errors::account("Could not list vaults.", e))
}
fn change_vault_password(&self, name: String, new_password: Password) -> Result<bool> {
self.deprecation_notice("parity_changeVaultPassword");
self.accounts
.change_vault_password(&name, &new_password)
.map_err(|e| errors::account("Could not change vault password.", e))
@@ -195,6 +293,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn change_vault(&self, address: RpcH160, new_vault: String) -> Result<bool> {
self.deprecation_notice("parity_changeVault");
self.accounts
.change_vault(address.into(), &new_vault)
.map_err(|e| errors::account("Could not change vault.", e))
@@ -202,12 +302,16 @@ impl ParityAccounts for ParityAccountsClient {
}
fn get_vault_meta(&self, name: String) -> Result<String> {
self.deprecation_notice("parity_getVaultMeta");
self.accounts
.get_vault_meta(&name)
.map_err(|e| errors::account("Could not get vault metadata.", e))
}
fn set_vault_meta(&self, name: String, meta: String) -> Result<bool> {
self.deprecation_notice("parity_setVaultMeta");
self.accounts
.set_vault_meta(&name, &meta)
.map_err(|e| errors::account("Could not update vault metadata.", e))
@@ -215,6 +319,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn derive_key_index(&self, addr: RpcH160, password: Password, derivation: DeriveHierarchical, save_as_account: bool) -> Result<RpcH160> {
self.deprecation_notice("parity_deriveAddressIndex");
let addr: Address = addr.into();
self.accounts
.derive_account(
@@ -228,6 +334,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn derive_key_hash(&self, addr: RpcH160, password: Password, derivation: DeriveHash, save_as_account: bool) -> Result<RpcH160> {
self.deprecation_notice("parity_deriveAddressHash");
let addr: Address = addr.into();
self.accounts
.derive_account(
@@ -241,6 +349,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn export_account(&self, addr: RpcH160, password: Password) -> Result<KeyFile> {
self.deprecation_notice("parity_exportAccount");
let addr = addr.into();
self.accounts
.export_account(
@@ -252,6 +362,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn sign_message(&self, addr: RpcH160, password: Password, message: RpcH256) -> Result<RpcH520> {
self.deprecation_notice("parity_signMessage");
self.accounts
.sign(
addr.into(),
@@ -263,6 +375,8 @@ impl ParityAccounts for ParityAccountsClient {
}
fn hardware_pin_matrix_ack(&self, path: String, pin: String) -> Result<bool> {
self.deprecation_notice("parity_hardwarePinMatrixAck");
self.accounts.hardware_pin_matrix_ack(&path, &pin).map_err(|e| errors::account("Error communicating with hardware wallet.", e))
}
}

View File

@@ -20,10 +20,12 @@ use std::sync::Arc;
use std::time::Duration;
use ethcore::client::{BlockChainClient, Mode};
use ethcore::miner::MinerService;
use sync::ManageNetwork;
use ethcore::miner::{self, MinerService};
use ethereum_types::H256 as EthH256;
use ethkey;
use fetch::{self, Fetch};
use hash::keccak_buffer;
use sync::ManageNetwork;
use updater::{Service as UpdateService};
use jsonrpc_core::{BoxFuture, Result};
@@ -32,6 +34,53 @@ use v1::helpers::errors;
use v1::traits::ParitySet;
use v1::types::{Bytes, H160, H256, U256, ReleaseInfo, Transaction};
#[cfg(any(test, feature = "accounts"))]
pub mod accounts {
use super::*;
use accounts::AccountProvider;
use v1::traits::ParitySetAccounts;
use v1::helpers::deprecated::DeprecationNotice;
use v1::helpers::engine_signer::EngineSigner;
/// Parity-specific account-touching RPC interfaces.
pub struct ParitySetAccountsClient<M> {
miner: Arc<M>,
accounts: Arc<AccountProvider>,
deprecation_notice: DeprecationNotice,
}
impl<M> ParitySetAccountsClient<M> {
/// Creates new ParitySetAccountsClient
pub fn new(
accounts: &Arc<AccountProvider>,
miner: &Arc<M>,
) -> Self {
ParitySetAccountsClient {
accounts: accounts.clone(),
miner: miner.clone(),
deprecation_notice: Default::default(),
}
}
}
impl<M: MinerService + 'static> ParitySetAccounts for ParitySetAccountsClient<M> {
fn set_engine_signer(&self, address: H160, password: String) -> Result<bool> {
self.deprecation_notice.print(
"parity_setEngineSigner",
"use `parity_setEngineSignerSecret` instead. See #9997 for context."
);
let signer = Box::new(EngineSigner::new(
self.accounts.clone(),
address.clone().into(),
password.into(),
));
self.miner.set_author(miner::Author::Sealer(signer));
Ok(true)
}
}
}
/// Parity-specific rpc interface for operations altering the settings.
pub struct ParitySetClient<C, M, U, F = fetch::Client> {
client: Arc<C>,
@@ -57,7 +106,7 @@ impl<C, M, U, F> ParitySetClient<C, M, U, F>
miner: miner.clone(),
updater: updater.clone(),
net: net.clone(),
fetch: fetch,
fetch,
}
}
}
@@ -104,12 +153,14 @@ impl<C, M, U, F> ParitySet for ParitySetClient<C, M, U, F> where
}
fn set_author(&self, address: H160) -> Result<bool> {
self.miner.set_author(address.into(), None).map_err(Into::into).map_err(errors::password)?;
self.miner.set_author(miner::Author::External(address.into()));
Ok(true)
}
fn set_engine_signer(&self, address: H160, password: String) -> Result<bool> {
self.miner.set_author(address.into(), Some(password.into())).map_err(Into::into).map_err(errors::password)?;
fn set_engine_signer_secret(&self, secret: H256) -> Result<bool> {
let secret: EthH256 = secret.into();
let keypair = ethkey::KeyPair::from_secret(secret.into()).map_err(|e| errors::account("Invalid secret", e))?;
self.miner.set_author(miner::Author::Sealer(ethcore::engines::signer::from_keypair(keypair)));
Ok(true)
}

View File

@@ -18,17 +18,20 @@
use std::sync::Arc;
use std::time::Duration;
use accounts::AccountProvider;
use bytes::Bytes;
use ethcore::account_provider::AccountProvider;
use types::transaction::{PendingTransaction, SignedTransaction};
use eip_712::{EIP712, hash_structured_data};
use ethereum_types::{H520, U128, Address};
use ethkey::{public_to_address, recover, Signature};
use types::transaction::{PendingTransaction, SignedTransaction};
use jsonrpc_core::{BoxFuture, Result};
use jsonrpc_core::futures::{future, Future};
use v1::helpers::{errors, eip191};
use jsonrpc_core::types::Value;
use jsonrpc_core::{BoxFuture, Result};
use v1::helpers::deprecated::{self, DeprecationNotice};
use v1::helpers::dispatch::{self, eth_data_hash, Dispatcher, SignWith, PostSign, WithToken};
use v1::helpers::{errors, eip191};
use v1::metadata::Metadata;
use v1::traits::Personal;
use v1::types::{
H160 as RpcH160, H256 as RpcH256, H520 as RpcH520, U128 as RpcU128,
@@ -39,9 +42,6 @@ use v1::types::{
RichRawTransaction as RpcRichRawTransaction,
EIP191Version,
};
use v1::metadata::Metadata;
use eip_712::{EIP712, hash_structured_data};
use jsonrpc_core::types::Value;
/// Account management (personal) rpc implementation.
pub struct PersonalClient<D: Dispatcher> {
@@ -49,6 +49,7 @@ pub struct PersonalClient<D: Dispatcher> {
dispatcher: D,
allow_perm_unlock: bool,
allow_experimental_rpcs: bool,
deprecation_notice: DeprecationNotice,
}
impl<D: Dispatcher> PersonalClient<D> {
@@ -64,6 +65,7 @@ impl<D: Dispatcher> PersonalClient<D> {
dispatcher,
allow_perm_unlock,
allow_experimental_rpcs,
deprecation_notice: DeprecationNotice::default(),
}
}
}
@@ -94,9 +96,10 @@ impl<D: Dispatcher + 'static> PersonalClient<D> {
Err(e) => return Box::new(future::err(e)),
};
let accounts = Arc::new(dispatch::Signer::new(accounts)) as _;
Box::new(dispatcher.fill_optional_fields(request.into(), default, false)
.and_then(move |filled| {
dispatcher.sign(accounts, filled, SignWith::Password(password.into()), post_sign)
dispatcher.sign(filled, &accounts, SignWith::Password(password.into()), post_sign)
})
)
}
@@ -106,17 +109,23 @@ impl<D: Dispatcher + 'static> Personal for PersonalClient<D> {
type Metadata = Metadata;
fn accounts(&self) -> Result<Vec<RpcH160>> {
self.deprecation_notice.print("personal_accounts", deprecated::msgs::ACCOUNTS);
let accounts = self.accounts.accounts().map_err(|e| errors::account("Could not fetch accounts.", e))?;
Ok(accounts.into_iter().map(Into::into).collect::<Vec<RpcH160>>())
}
fn new_account(&self, pass: String) -> Result<RpcH160> {
self.deprecation_notice.print("personal_newAccount", deprecated::msgs::ACCOUNTS);
self.accounts.new_account(&pass.into())
.map(Into::into)
.map_err(|e| errors::account("Could not create account.", e))
}
fn unlock_account(&self, account: RpcH160, account_pass: String, duration: Option<RpcU128>) -> Result<bool> {
self.deprecation_notice.print("personal_unlockAccount", deprecated::msgs::ACCOUNTS);
let account: Address = account.into();
let store = self.accounts.clone();
let duration = match duration {
@@ -149,14 +158,16 @@ impl<D: Dispatcher + 'static> Personal for PersonalClient<D> {
}
fn sign(&self, data: RpcBytes, account: RpcH160, password: String) -> BoxFuture<RpcH520> {
self.deprecation_notice.print("personal_sign", deprecated::msgs::ACCOUNTS);
let dispatcher = self.dispatcher.clone();
let accounts = self.accounts.clone();
let accounts = Arc::new(dispatch::Signer::new(self.accounts.clone())) as _;
let payload = RpcConfirmationPayload::EthSignMessage((account.clone(), data).into());
Box::new(dispatch::from_rpc(payload, account.into(), &dispatcher)
.and_then(|payload| {
dispatch::execute(dispatcher, accounts, payload, dispatch::SignWith::Password(password.into()))
.and_then(move |payload| {
dispatch::execute(dispatcher, &accounts, payload, dispatch::SignWith::Password(password.into()))
})
.map(|v| v.into_value())
.then(|res| match res {
@@ -167,17 +178,19 @@ impl<D: Dispatcher + 'static> Personal for PersonalClient<D> {
}
fn sign_191(&self, version: EIP191Version, data: Value, account: RpcH160, password: String) -> BoxFuture<RpcH520> {
self.deprecation_notice.print("personal_sign191", deprecated::msgs::ACCOUNTS);
try_bf!(errors::require_experimental(self.allow_experimental_rpcs, "191"));
let data = try_bf!(eip191::hash_message(version, data));
let dispatcher = self.dispatcher.clone();
let accounts = self.accounts.clone();
let accounts = Arc::new(dispatch::Signer::new(self.accounts.clone())) as _;
let payload = RpcConfirmationPayload::EIP191SignMessage((account.clone(), data.into()).into());
Box::new(dispatch::from_rpc(payload, account.into(), &dispatcher)
.and_then(|payload| {
dispatch::execute(dispatcher, accounts, payload, dispatch::SignWith::Password(password.into()))
.and_then(move |payload| {
dispatch::execute(dispatcher, &accounts, payload, dispatch::SignWith::Password(password.into()))
})
.map(|v| v.into_value())
.then(|res| match res {
@@ -189,6 +202,8 @@ impl<D: Dispatcher + 'static> Personal for PersonalClient<D> {
}
fn sign_typed_data(&self, typed_data: EIP712, account: RpcH160, password: String) -> BoxFuture<RpcH520> {
self.deprecation_notice.print("personal_signTypedData", deprecated::msgs::ACCOUNTS);
try_bf!(errors::require_experimental(self.allow_experimental_rpcs, "712"));
let data = match hash_structured_data(typed_data) {
@@ -196,13 +211,13 @@ impl<D: Dispatcher + 'static> Personal for PersonalClient<D> {
Err(err) => return Box::new(future::err(errors::invalid_call_data(err.kind()))),
};
let dispatcher = self.dispatcher.clone();
let accounts = self.accounts.clone();
let accounts = Arc::new(dispatch::Signer::new(self.accounts.clone())) as _;
let payload = RpcConfirmationPayload::EIP191SignMessage((account.clone(), data.into()).into());
Box::new(dispatch::from_rpc(payload, account.into(), &dispatcher)
.and_then(|payload| {
dispatch::execute(dispatcher, accounts, payload, dispatch::SignWith::Password(password.into()))
.and_then(move |payload| {
dispatch::execute(dispatcher, &accounts, payload, dispatch::SignWith::Password(password.into()))
})
.map(|v| v.into_value())
.then(|res| match res {
@@ -229,6 +244,8 @@ impl<D: Dispatcher + 'static> Personal for PersonalClient<D> {
}
fn sign_transaction(&self, meta: Metadata, request: TransactionRequest, password: String) -> BoxFuture<RpcRichRawTransaction> {
self.deprecation_notice.print("personal_signTransaction", deprecated::msgs::ACCOUNTS);
let condition = request.condition.clone().map(Into::into);
let dispatcher = self.dispatcher.clone();
Box::new(self.do_sign_transaction(meta, request, password, ())
@@ -237,24 +254,27 @@ impl<D: Dispatcher + 'static> Personal for PersonalClient<D> {
}
fn send_transaction(&self, meta: Metadata, request: TransactionRequest, password: String) -> BoxFuture<RpcH256> {
self.deprecation_notice.print("personal_sendTransaction", deprecated::msgs::ACCOUNTS);
let condition = request.condition.clone().map(Into::into);
let dispatcher = self.dispatcher.clone();
Box::new(self.do_sign_transaction(meta, request, password, move |signed: WithToken<SignedTransaction>| {
dispatcher.dispatch_transaction(
PendingTransaction::new(
signed.into_value(),
condition
Box::new(
self.do_sign_transaction(meta, request, password, move |signed: WithToken<SignedTransaction>| {
dispatcher.dispatch_transaction(
PendingTransaction::new(
signed.into_value(),
condition
)
)
)
})
.and_then(|hash| {
}).and_then(|hash| {
Ok(RpcH256::from(hash))
})
)
}
fn sign_and_send_transaction(&self, meta: Metadata, request: TransactionRequest, password: String) -> BoxFuture<RpcH256> {
warn!("Using deprecated personal_signAndSendTransaction, use personal_sendTransaction instead.");
self.deprecation_notice.print("personal_signAndSendTransaction", Some("use personal_sendTransaction instead."));
self.send_transaction(meta, request, password)
}
}

View File

@@ -21,7 +21,7 @@ use std::sync::Arc;
use crypto::DEFAULT_MAC;
use ethkey::Secret;
use ethcore::account_provider::AccountProvider;
use accounts::AccountProvider;
use jsonrpc_core::Result;
use v1::helpers::errors;

View File

@@ -18,7 +18,6 @@
use std::sync::Arc;
use ethcore::account_provider::AccountProvider;
use ethkey;
use parity_runtime::Executor;
use parking_lot::Mutex;
@@ -29,8 +28,10 @@ use jsonrpc_core::{Result, BoxFuture, Error};
use jsonrpc_core::futures::{future, Future, IntoFuture};
use jsonrpc_core::futures::future::Either;
use jsonrpc_pubsub::{SubscriptionId, typed::{Sink, Subscriber}};
use v1::helpers::deprecated::{self, DeprecationNotice};
use v1::helpers::dispatch::{self, Dispatcher, WithToken, eth_data_hash};
use v1::helpers::{errors, SignerService, SigningQueue, ConfirmationPayload, FilledTransactionRequest, Subscribers};
use v1::helpers::{errors, ConfirmationPayload, FilledTransactionRequest, Subscribers};
use v1::helpers::external_signer::{SigningQueue, SignerService};
use v1::metadata::Metadata;
use v1::traits::Signer;
use v1::types::{TransactionModification, ConfirmationRequest, ConfirmationResponse, ConfirmationResponseWithToken, U256, Bytes};
@@ -38,15 +39,16 @@ use v1::types::{TransactionModification, ConfirmationRequest, ConfirmationRespon
/// Transactions confirmation (personal) rpc implementation.
pub struct SignerClient<D: Dispatcher> {
signer: Arc<SignerService>,
accounts: Arc<AccountProvider>,
accounts: Arc<dispatch::Accounts>,
dispatcher: D,
subscribers: Arc<Mutex<Subscribers<Sink<Vec<ConfirmationRequest>>>>>,
deprecation_notice: DeprecationNotice,
}
impl<D: Dispatcher + 'static> SignerClient<D> {
/// Create new instance of signer client.
pub fn new(
store: &Arc<AccountProvider>,
accounts: Arc<dispatch::Accounts>,
dispatcher: D,
signer: &Arc<SignerService>,
executor: Executor,
@@ -70,14 +72,15 @@ impl<D: Dispatcher + 'static> SignerClient<D> {
SignerClient {
signer: signer.clone(),
accounts: store.clone(),
accounts: accounts.clone(),
dispatcher,
subscribers,
deprecation_notice: Default::default(),
}
}
fn confirm_internal<F, T>(&self, id: U256, modification: TransactionModification, f: F) -> BoxFuture<WithToken<ConfirmationResponse>> where
F: FnOnce(D, Arc<AccountProvider>, ConfirmationPayload) -> T,
F: FnOnce(D, &Arc<dispatch::Accounts>, ConfirmationPayload) -> T,
T: IntoFuture<Item=WithToken<ConfirmationResponse>, Error=Error>,
T::Future: Send + 'static
{
@@ -104,7 +107,7 @@ impl<D: Dispatcher + 'static> SignerClient<D> {
request.condition = condition.clone().map(Into::into);
}
}
let fut = f(dispatcher, self.accounts.clone(), payload);
let fut = f(dispatcher, &self.accounts, payload);
Either::A(fut.into_future().then(move |result| {
// Execute
if let Ok(ref response) = result {
@@ -155,6 +158,8 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
type Metadata = Metadata;
fn requests_to_confirm(&self) -> Result<Vec<ConfirmationRequest>> {
self.deprecation_notice.print("signer_requestsToConfirm", deprecated::msgs::ACCOUNTS);
Ok(self.signer.requests()
.into_iter()
.map(Into::into)
@@ -167,6 +172,8 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
fn confirm_request(&self, id: U256, modification: TransactionModification, pass: String)
-> BoxFuture<ConfirmationResponse>
{
self.deprecation_notice.print("signer_confirmRequest", deprecated::msgs::ACCOUNTS);
Box::new(self.confirm_internal(id, modification, move |dis, accounts, payload| {
dispatch::execute(dis, accounts, payload, dispatch::SignWith::Password(pass.into()))
}).map(|v| v.into_value()))
@@ -175,6 +182,8 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
fn confirm_request_with_token(&self, id: U256, modification: TransactionModification, token: String)
-> BoxFuture<ConfirmationResponseWithToken>
{
self.deprecation_notice.print("signer_confirmRequestWithToken", deprecated::msgs::ACCOUNTS);
Box::new(self.confirm_internal(id, modification, move |dis, accounts, payload| {
dispatch::execute(dis, accounts, payload, dispatch::SignWith::Token(token.into()))
}).and_then(|v| match v {
@@ -187,6 +196,8 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
}
fn confirm_request_raw(&self, id: U256, bytes: Bytes) -> Result<ConfirmationResponse> {
self.deprecation_notice.print("signer_confirmRequestRaw", deprecated::msgs::ACCOUNTS);
let id = id.into();
self.signer.take(&id).map(|sender| {
@@ -237,20 +248,22 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
}
fn reject_request(&self, id: U256) -> Result<bool> {
self.deprecation_notice.print("signer_rejectRequest", deprecated::msgs::ACCOUNTS);
let res = self.signer.take(&id.into()).map(|sender| self.signer.request_rejected(sender));
Ok(res.is_some())
}
fn generate_token(&self) -> Result<String> {
self.deprecation_notice.print("signer_generateAuthorizationToken", deprecated::msgs::ACCOUNTS);
self.signer.generate_token()
.map_err(|e| errors::token(e))
}
fn generate_web_proxy_token(&self, domain: String) -> Result<String> {
Ok(self.signer.generate_web_proxy_access_token(domain.into()))
}
fn subscribe_pending(&self, _meta: Self::Metadata, sub: Subscriber<Vec<ConfirmationRequest>>) {
self.deprecation_notice.print("signer_subscribePending", deprecated::msgs::ACCOUNTS);
self.subscribers.lock().push(sub)
}

View File

@@ -21,17 +21,18 @@ use transient_hashmap::TransientHashMap;
use ethereum_types::U256;
use parking_lot::Mutex;
use ethcore::account_provider::AccountProvider;
use jsonrpc_core::{BoxFuture, Result, Error};
use jsonrpc_core::futures::{future, Future, Poll, Async};
use jsonrpc_core::futures::future::Either;
use v1::helpers::{
errors, DefaultAccount, SignerService, SigningQueue,
use v1::helpers::deprecated::{self, DeprecationNotice};
use v1::helpers::dispatch::{self, Dispatcher};
use v1::helpers::errors;
use v1::helpers::external_signer::{
SignerService, SigningQueue,
ConfirmationReceiver as RpcConfirmationReceiver,
ConfirmationResult as RpcConfirmationResult,
};
use v1::helpers::dispatch::{self, Dispatcher};
use v1::metadata::Metadata;
use v1::traits::{EthSigning, ParitySigning};
use v1::types::{
@@ -89,38 +90,37 @@ fn schedule(executor: Executor,
/// Implementation of functions that require signing when no trusted signer is used.
pub struct SigningQueueClient<D> {
signer: Arc<SignerService>,
accounts: Arc<AccountProvider>,
accounts: Arc<dispatch::Accounts>,
dispatcher: D,
executor: Executor,
// None here means that the request hasn't yet been confirmed
confirmations: Arc<Mutex<TransientHashMap<U256, Option<RpcConfirmationResult>>>>,
deprecation_notice: DeprecationNotice,
}
impl<D: Dispatcher + 'static> SigningQueueClient<D> {
/// Creates a new signing queue client given shared signing queue.
pub fn new(signer: &Arc<SignerService>, dispatcher: D, executor: Executor, accounts: &Arc<AccountProvider>) -> Self {
pub fn new(signer: &Arc<SignerService>, dispatcher: D, executor: Executor, accounts: &Arc<dispatch::Accounts>) -> Self {
SigningQueueClient {
signer: signer.clone(),
accounts: accounts.clone(),
dispatcher,
executor,
confirmations: Arc::new(Mutex::new(TransientHashMap::new(MAX_PENDING_DURATION_SEC))),
deprecation_notice: Default::default(),
}
}
fn dispatch(&self, payload: RpcConfirmationPayload, default_account: DefaultAccount, origin: Origin) -> BoxFuture<DispatchResult> {
fn dispatch(&self, payload: RpcConfirmationPayload, origin: Origin) -> BoxFuture<DispatchResult> {
let default_account = self.accounts.default_account();
let accounts = self.accounts.clone();
let default_account = match default_account {
DefaultAccount::Provided(acc) => acc,
};
let dispatcher = self.dispatcher.clone();
let signer = self.signer.clone();
Box::new(dispatch::from_rpc(payload, default_account, &dispatcher)
.and_then(move |payload| {
let sender = payload.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(DispatchResult::Value))
} else {
@@ -138,17 +138,18 @@ impl<D: Dispatcher + 'static> ParitySigning for SigningQueueClient<D> {
type Metadata = Metadata;
fn compose_transaction(&self, _meta: Metadata, transaction: RpcTransactionRequest) -> BoxFuture<RpcTransactionRequest> {
let default_account = self.accounts.default_account().ok().unwrap_or_default();
let default_account = self.accounts.default_account();
Box::new(self.dispatcher.fill_optional_fields(transaction.into(), default_account, true).map(Into::into))
}
fn post_sign(&self, meta: Metadata, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcEither<RpcU256, RpcConfirmationResponse>> {
self.deprecation_notice.print("parity_postSign", deprecated::msgs::ACCOUNTS);
let executor = self.executor.clone();
let confirmations = self.confirmations.clone();
Box::new(self.dispatch(
RpcConfirmationPayload::EthSignMessage((address.clone(), data).into()),
DefaultAccount::Provided(address.into()),
meta.origin
).map(move |result| match result {
DispatchResult::Value(v) => RpcEither::Or(v),
@@ -160,10 +161,12 @@ impl<D: Dispatcher + 'static> ParitySigning for SigningQueueClient<D> {
}
fn post_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcEither<RpcU256, RpcConfirmationResponse>> {
self.deprecation_notice.print("parity_postTransaction", deprecated::msgs::ACCOUNTS);
let executor = self.executor.clone();
let confirmations = self.confirmations.clone();
Box::new(self.dispatch(RpcConfirmationPayload::SendTransaction(request), DefaultAccount::Provided(self.accounts.default_account().ok().unwrap_or_default()), meta.origin)
Box::new(self.dispatch(RpcConfirmationPayload::SendTransaction(request), meta.origin)
.map(|result| match result {
DispatchResult::Value(v) => RpcEither::Or(v),
DispatchResult::Future(id, future) => {
@@ -174,6 +177,8 @@ impl<D: Dispatcher + 'static> ParitySigning for SigningQueueClient<D> {
}
fn check_request(&self, id: RpcU256) -> Result<Option<RpcConfirmationResponse>> {
self.deprecation_notice.print("parity_checkRequest", deprecated::msgs::ACCOUNTS);
let id: U256 = id.into();
match self.confirmations.lock().get(&id) {
None => Err(errors::request_not_found()), // Request info has been dropped, or even never been there
@@ -183,9 +188,10 @@ impl<D: Dispatcher + 'static> ParitySigning for SigningQueueClient<D> {
}
fn decrypt_message(&self, meta: Metadata, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcBytes> {
self.deprecation_notice.print("parity_decryptMessage", deprecated::msgs::ACCOUNTS);
let res = self.dispatch(
RpcConfirmationPayload::Decrypt((address.clone(), data).into()),
address.into(),
meta.origin,
);
@@ -203,9 +209,10 @@ impl<D: Dispatcher + 'static> EthSigning for SigningQueueClient<D> {
type Metadata = Metadata;
fn sign(&self, meta: Metadata, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcH520> {
self.deprecation_notice.print("eth_sign", deprecated::msgs::ACCOUNTS);
let res = self.dispatch(
RpcConfirmationPayload::EthSignMessage((address.clone(), data).into()),
address.into(),
meta.origin,
);
@@ -218,9 +225,10 @@ impl<D: Dispatcher + 'static> EthSigning for SigningQueueClient<D> {
}
fn send_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcH256> {
self.deprecation_notice.print("eth_sendTransaction", deprecated::msgs::ACCOUNTS);
let res = self.dispatch(
RpcConfirmationPayload::SendTransaction(request),
DefaultAccount::Provided(self.accounts.default_account().ok().unwrap_or_default()),
meta.origin,
);
@@ -233,9 +241,10 @@ impl<D: Dispatcher + 'static> EthSigning for SigningQueueClient<D> {
}
fn sign_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcRichRawTransaction> {
self.deprecation_notice.print("eth_signTransaction", deprecated::msgs::ACCOUNTS);
let res = self.dispatch(
RpcConfirmationPayload::SignTransaction(request),
DefaultAccount::Provided(self.accounts.default_account().ok().unwrap_or_default()),
meta.origin,
);

View File

@@ -18,11 +18,12 @@
use std::sync::Arc;
use ethcore::account_provider::AccountProvider;
use ethereum_types::Address;
use jsonrpc_core::{BoxFuture, Result};
use jsonrpc_core::futures::{future, Future};
use v1::helpers::{errors, DefaultAccount};
use v1::helpers::{errors};
use v1::helpers::deprecated::{self, DeprecationNotice};
use v1::helpers::dispatch::{self, Dispatcher};
use v1::metadata::Metadata;
use v1::traits::{EthSigning, ParitySigning};
@@ -38,29 +39,28 @@ use v1::types::{
/// Implementation of functions that require signing when no trusted signer is used.
pub struct SigningUnsafeClient<D> {
accounts: Arc<AccountProvider>,
accounts: Arc<dispatch::Accounts>,
dispatcher: D,
deprecation_notice: DeprecationNotice,
}
impl<D: Dispatcher + 'static> SigningUnsafeClient<D> {
/// Creates new SigningUnsafeClient.
pub fn new(accounts: &Arc<AccountProvider>, dispatcher: D) -> Self {
pub fn new(accounts: &Arc<dispatch::Accounts>, dispatcher: D) -> Self {
SigningUnsafeClient {
accounts: accounts.clone(),
dispatcher: dispatcher,
dispatcher,
deprecation_notice: Default::default(),
}
}
fn handle(&self, payload: RpcConfirmationPayload, account: DefaultAccount) -> BoxFuture<RpcConfirmationResponse> {
fn handle(&self, payload: RpcConfirmationPayload, account: Address) -> BoxFuture<RpcConfirmationResponse> {
let accounts = self.accounts.clone();
let default = match account {
DefaultAccount::Provided(acc) => acc,
};
let dis = self.dispatcher.clone();
Box::new(dispatch::from_rpc(payload, default, &dis)
Box::new(dispatch::from_rpc(payload, account, &dis)
.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()))
}
@@ -71,6 +71,8 @@ impl<D: Dispatcher + 'static> EthSigning for SigningUnsafeClient<D>
type Metadata = Metadata;
fn sign(&self, _: Metadata, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcH520> {
self.deprecation_notice.print("eth_sign", deprecated::msgs::ACCOUNTS);
Box::new(self.handle(RpcConfirmationPayload::EthSignMessage((address.clone(), data).into()), address.into())
.then(|res| match res {
Ok(RpcConfirmationResponse::Signature(signature)) => Ok(signature),
@@ -80,7 +82,9 @@ impl<D: Dispatcher + 'static> EthSigning for SigningUnsafeClient<D>
}
fn send_transaction(&self, _meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcH256> {
Box::new(self.handle(RpcConfirmationPayload::SendTransaction(request), DefaultAccount::Provided(self.accounts.default_account().ok().unwrap_or_default()))
self.deprecation_notice.print("eth_sendTransaction", deprecated::msgs::ACCOUNTS);
Box::new(self.handle(RpcConfirmationPayload::SendTransaction(request), self.accounts.default_account())
.then(|res| match res {
Ok(RpcConfirmationResponse::SendTransaction(hash)) => Ok(hash),
Err(e) => Err(e),
@@ -89,7 +93,9 @@ impl<D: Dispatcher + 'static> EthSigning for SigningUnsafeClient<D>
}
fn sign_transaction(&self, _meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcRichRawTransaction> {
Box::new(self.handle(RpcConfirmationPayload::SignTransaction(request), DefaultAccount::Provided(self.accounts.default_account().ok().unwrap_or_default()))
self.deprecation_notice.print("eth_signTransaction", deprecated::msgs::ACCOUNTS);
Box::new(self.handle(RpcConfirmationPayload::SignTransaction(request), self.accounts.default_account())
.then(|res| match res {
Ok(RpcConfirmationResponse::SignTransaction(tx)) => Ok(tx),
Err(e) => Err(e),
@@ -103,11 +109,13 @@ impl<D: Dispatcher + 'static> ParitySigning for SigningUnsafeClient<D> {
fn compose_transaction(&self, _meta: Metadata, transaction: RpcTransactionRequest) -> BoxFuture<RpcTransactionRequest> {
let accounts = self.accounts.clone();
let default_account = accounts.default_account().ok().unwrap_or_default();
let default_account = accounts.default_account();
Box::new(self.dispatcher.fill_optional_fields(transaction.into(), default_account, true).map(Into::into))
}
fn decrypt_message(&self, _: Metadata, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcBytes> {
self.deprecation_notice.print("parity_decryptMessage", deprecated::msgs::ACCOUNTS);
Box::new(self.handle(RpcConfirmationPayload::Decrypt((address.clone(), data).into()), address.into())
.then(|res| match res {
Ok(RpcConfirmationResponse::Decrypt(data)) => Ok(data),

View File

@@ -41,7 +41,7 @@ pub mod informant;
pub mod metadata;
pub mod traits;
pub use self::traits::{Debug, Eth, EthFilter, EthPubSub, EthSigning, Net, Parity, ParityAccounts, ParitySet, ParitySigning, Personal, PubSub, Private, Rpc, SecretStore, Signer, Traces, Web3};
pub use self::traits::{Debug, Eth, EthFilter, EthPubSub, EthSigning, Net, Parity, ParityAccountsInfo, ParityAccounts, ParitySet, ParitySetAccounts, ParitySigning, Personal, PubSub, Private, Rpc, SecretStore, Signer, Traces, Web3};
pub use self::impls::*;
pub use self::helpers::{NetworkSettings, block_import, dispatch};
pub use self::metadata::Metadata;
@@ -50,6 +50,8 @@ pub use self::extractors::{RpcExtractor, WsExtractor, WsStats, WsDispatcher};
/// Signer utilities
pub mod signer {
pub use super::helpers::{SigningQueue, SignerService, ConfirmationsQueue};
#[cfg(any(test, feature = "accounts"))]
pub use super::helpers::engine_signer::EngineSigner;
pub use super::helpers::external_signer::{SignerService, ConfirmationsQueue};
pub use super::types::{ConfirmationRequest, TransactionModification, U256, TransactionCondition};
}

View File

@@ -18,7 +18,7 @@
use std::env;
use std::sync::Arc;
use ethcore::account_provider::AccountProvider;
use accounts::AccountProvider;
use ethcore::client::{BlockChainClient, Client, ClientConfig, ChainInfo, ImportBlock};
use ethcore::ethereum;
use ethcore::miner::Miner;
@@ -36,13 +36,12 @@ use parking_lot::Mutex;
use types::ids::BlockId;
use jsonrpc_core::IoHandler;
use v1::helpers::dispatch::FullDispatcher;
use v1::helpers::dispatch::{self, FullDispatcher};
use v1::helpers::nonce;
use v1::impls::{EthClient, EthClientOptions, SigningUnsafeClient};
use v1::metadata::Metadata;
use v1::tests::helpers::{TestSnapshotService, TestSyncProvider, Config};
use v1::traits::eth::Eth;
use v1::traits::eth_signing::EthSigning;
use v1::traits::{Eth, EthSigning};
use v1::types::U256 as NU256;
fn account_provider() -> Arc<AccountProvider> {
@@ -56,8 +55,8 @@ fn sync_provider() -> Arc<TestSyncProvider> {
}))
}
fn miner_service(spec: &Spec, accounts: Arc<AccountProvider>) -> Arc<Miner> {
Arc::new(Miner::new_for_tests(spec, Some(accounts)))
fn miner_service(spec: &Spec) -> Arc<Miner> {
Arc::new(Miner::new_for_tests(spec, None))
}
fn snapshot_service() -> Arc<TestSnapshotService> {
@@ -75,11 +74,11 @@ fn make_spec(chain: &BlockChain) -> Spec {
}
struct EthTester {
_runtime: Runtime,
client: Arc<Client>,
_miner: Arc<Miner>,
_runtime: Runtime,
_snapshot: Arc<TestSnapshotService>,
accounts: Arc<AccountProvider>,
client: Arc<Client>,
handler: IoHandler<Metadata>,
}
@@ -115,11 +114,11 @@ impl EthTester {
}
fn from_spec_conf(spec: Spec, config: ClientConfig) -> Self {
let runtime = Runtime::with_thread_count(1);
let account_provider = account_provider();
let opt_account_provider = account_provider.clone();
let miner_service = miner_service(&spec, account_provider.clone());
let ap = account_provider.clone();
let accounts = Arc::new(move || ap.accounts().unwrap_or_default()) as _;
let miner_service = miner_service(&spec);
let snapshot_service = snapshot_service();
let client = Client::new(
@@ -136,7 +135,7 @@ impl EthTester {
&client,
&snapshot_service,
&sync_provider,
&opt_account_provider,
&accounts,
&miner_service,
&external_miner,
EthClientOptions {
@@ -152,8 +151,9 @@ impl EthTester {
let reservations = Arc::new(Mutex::new(nonce::Reservations::new(runtime.executor())));
let dispatcher = FullDispatcher::new(client.clone(), miner_service.clone(), reservations, 50);
let signer = Arc::new(dispatch::Signer::new(account_provider.clone())) as _;
let eth_sign = SigningUnsafeClient::new(
&opt_account_provider,
&signer,
dispatcher,
);
@@ -162,11 +162,11 @@ impl EthTester {
handler.extend_with(eth_sign.to_delegate());
EthTester {
_runtime: runtime,
_miner: miner_service,
_runtime: runtime,
_snapshot: snapshot_service,
client: client,
accounts: account_provider,
client: client,
handler: handler,
}
}

View File

@@ -20,14 +20,12 @@ use std::sync::Arc;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use bytes::Bytes;
use ethcore::account_provider::SignError as AccountError;
use ethcore::block::{SealedBlock, IsBlock};
use ethcore::client::{Nonce, PrepareOpenBlock, StateClient, EngineInfo};
use ethcore::engines::EthEngine;
use ethcore::engines::{EthEngine, signer::EngineSigner};
use ethcore::error::Error;
use ethcore::miner::{self, MinerService, AuthoringParams};
use ethereum_types::{H256, U256, Address};
use ethkey::Password;
use miner::pool::local_transactions::Status as LocalTransactionStatus;
use miner::pool::{verifier, VerifiedTransaction, QueueStatus};
use parking_lot::{RwLock, Mutex};
@@ -51,8 +49,8 @@ pub struct TestMinerService {
pub pending_receipts: Mutex<Vec<RichReceipt>>,
/// Next nonces.
pub next_nonces: RwLock<HashMap<Address, U256>>,
/// Password held by Engine.
pub password: RwLock<Password>,
/// Signer (if any)
pub signer: RwLock<Option<Box<EngineSigner>>>,
authoring_params: RwLock<AuthoringParams>,
}
@@ -65,12 +63,12 @@ impl Default for TestMinerService {
local_transactions: Default::default(),
pending_receipts: Default::default(),
next_nonces: Default::default(),
password: RwLock::new("".into()),
authoring_params: RwLock::new(AuthoringParams {
author: Address::zero(),
gas_range_target: (12345.into(), 54321.into()),
extra_data: vec![1, 2, 3, 4],
}),
signer: RwLock::new(None),
}
}
}
@@ -122,12 +120,11 @@ impl MinerService for TestMinerService {
self.authoring_params.read().clone()
}
fn set_author(&self, author: Address, password: Option<Password>) -> Result<(), AccountError> {
self.authoring_params.write().author = author;
if let Some(password) = password {
*self.password.write() = password;
fn set_author(&self, author: miner::Author) {
self.authoring_params.write().author = author.address();
if let miner::Author::Sealer(signer) = author {
*self.signer.write() = Some(signer);
}
Ok(())
}
fn set_extra_data(&self, extra_data: Bytes) {

View File

@@ -19,11 +19,10 @@ use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Instant, Duration, SystemTime, UNIX_EPOCH};
use ethcore::account_provider::AccountProvider;
use accounts::AccountProvider;
use ethcore::client::{BlockChainClient, BlockId, EachBlockWith, Executed, TestBlockChainClient, TransactionId};
use ethcore::miner::MinerService;
use ethcore::miner::{self, MinerService};
use ethereum_types::{H160, H256, U256, Address};
use ethkey::Secret;
use miner::external::ExternalMiner;
use parity_runtime::Runtime;
use parking_lot::Mutex;
@@ -35,9 +34,7 @@ use types::log_entry::{LocalizedLogEntry, LogEntry};
use types::receipt::{LocalizedReceipt, TransactionOutcome};
use jsonrpc_core::IoHandler;
use v1::{Eth, EthClient, EthClientOptions, EthFilter, EthFilterClient, EthSigning, SigningUnsafeClient};
use v1::helpers::nonce;
use v1::helpers::dispatch::FullDispatcher;
use v1::{Eth, EthClient, EthClientOptions, EthFilter, EthFilterClient};
use v1::tests::helpers::{TestSyncProvider, Config, TestMinerService, TestSnapshotService};
use v1::metadata::Metadata;
@@ -88,21 +85,17 @@ impl EthTester {
let client = blockchain_client();
let sync = sync_provider();
let ap = accounts_provider();
let opt_ap = ap.clone();
let ap2 = ap.clone();
let opt_ap = Arc::new(move || ap2.accounts().unwrap_or_default()) as _;
let miner = miner_service();
let snapshot = snapshot_service();
let hashrates = Arc::new(Mutex::new(HashMap::new()));
let external_miner = Arc::new(ExternalMiner::new(hashrates.clone()));
let gas_price_percentile = options.gas_price_percentile;
let eth = EthClient::new(&client, &snapshot, &sync, &opt_ap, &miner, &external_miner, options).to_delegate();
let filter = EthFilterClient::new(client.clone(), miner.clone(), 60).to_delegate();
let reservations = Arc::new(Mutex::new(nonce::Reservations::new(runtime.executor())));
let dispatcher = FullDispatcher::new(client.clone(), miner.clone(), reservations, gas_price_percentile);
let sign = SigningUnsafeClient::new(&opt_ap, dispatcher).to_delegate();
let mut io: IoHandler<Metadata> = IoHandler::default();
io.extend_with(eth);
io.extend_with(sign);
io.extend_with(filter);
EthTester {
@@ -360,28 +353,6 @@ fn rpc_eth_submit_hashrate() {
U256::from(0x500_000));
}
#[test]
fn rpc_eth_sign() {
let tester = EthTester::default();
let account = tester.accounts_provider.insert_account(Secret::from([69u8; 32]), &"abcd".into()).unwrap();
tester.accounts_provider.unlock_account_permanently(account, "abcd".into()).unwrap();
let _message = "0cc175b9c0f1b6a831c399e26977266192eb5ffee6ae2fec3ad71c777531578f".from_hex().unwrap();
let req = r#"{
"jsonrpc": "2.0",
"method": "eth_sign",
"params": [
""#.to_owned() + &format!("0x{:x}", account) + r#"",
"0x0cc175b9c0f1b6a831c399e26977266192eb5ffee6ae2fec3ad71c777531578f"
],
"id": 1
}"#;
let res = r#"{"jsonrpc":"2.0","result":"0xa2870db1d0c26ef93c7b72d2a0830fa6b841e0593f7186bc6c7cc317af8cf3a42fda03bd589a49949aa05db83300cdb553116274518dbe9d90c65d0213f4af491b","id":1}"#;
assert_eq!(tester.io.handle_request_sync(&req), Some(res.into()));
}
#[test]
fn rpc_eth_author() {
let make_res = |addr| r#"{"jsonrpc":"2.0","result":""#.to_owned() + &format!("0x{:x}", addr) + r#"","id":1}"#;
@@ -405,7 +376,7 @@ fn rpc_eth_author() {
for i in 0..20 {
let addr = tester.accounts_provider.new_account(&format!("{}", i).into()).unwrap();
tester.miner.set_author(addr.clone(), None).unwrap();
tester.miner.set_author(miner::Author::External(addr));
assert_eq!(tester.io.handle_request_sync(request), Some(make_res(addr)));
}
@@ -414,7 +385,7 @@ fn rpc_eth_author() {
#[test]
fn rpc_eth_mining() {
let tester = EthTester::default();
tester.miner.set_author(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap(), None).unwrap();
tester.miner.set_author(miner::Author::External(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()));
let request = r#"{"jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":false,"id":1}"#;
@@ -824,157 +795,6 @@ fn rpc_eth_estimate_gas_default_block() {
assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_eth_send_transaction() {
let tester = EthTester::default();
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
tester.accounts_provider.unlock_account_permanently(address, "".into()).unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_sendTransaction",
"params": [{
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a"
}],
"id": 1
}"#;
let t = Transaction {
nonce: U256::zero(),
gas_price: U256::from(0x9184e72a000u64),
gas: U256::from(0x76c0),
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
value: U256::from(0x9184e72au64),
data: vec![]
};
let signature = tester.accounts_provider.sign(address, None, t.hash(None)).unwrap();
let t = t.with_signature(signature, None);
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:x}", t.hash()).as_ref() + r#"","id":1}"#;
assert_eq!(tester.io.handle_request_sync(&request), Some(response));
tester.miner.increment_nonce(&address);
let t = Transaction {
nonce: U256::one(),
gas_price: U256::from(0x9184e72a000u64),
gas: U256::from(0x76c0),
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
value: U256::from(0x9184e72au64),
data: vec![]
};
let signature = tester.accounts_provider.sign(address, None, t.hash(None)).unwrap();
let t = t.with_signature(signature, None);
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:x}", t.hash()).as_ref() + r#"","id":1}"#;
assert_eq!(tester.io.handle_request_sync(&request), Some(response));
}
#[test]
fn rpc_eth_sign_transaction() {
let tester = EthTester::default();
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
tester.accounts_provider.unlock_account_permanently(address, "".into()).unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_signTransaction",
"params": [{
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a"
}],
"id": 1
}"#;
let t = Transaction {
nonce: U256::one(),
gas_price: U256::from(0x9184e72a000u64),
gas: U256::from(0x76c0),
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
value: U256::from(0x9184e72au64),
data: vec![]
};
let signature = tester.accounts_provider.sign(address, None, t.hash(None)).unwrap();
let t = t.with_signature(signature, None);
let signature = t.signature();
let rlp = rlp::encode(&t);
let response = r#"{"jsonrpc":"2.0","result":{"#.to_owned() +
r#""raw":"0x"# + &rlp.to_hex() + r#"","# +
r#""tx":{"# +
r#""blockHash":null,"blockNumber":null,"# +
&format!("\"chainId\":{},", t.chain_id().map_or("null".to_owned(), |n| format!("{}", n))) +
r#""condition":null,"creates":null,"# +
&format!("\"from\":\"0x{:x}\",", &address) +
r#""gas":"0x76c0","gasPrice":"0x9184e72a000","# +
&format!("\"hash\":\"0x{:x}\",", t.hash()) +
r#""input":"0x","# +
r#""nonce":"0x1","# +
&format!("\"publicKey\":\"0x{:x}\",", t.recover_public().unwrap()) +
&format!("\"r\":\"0x{:x}\",", U256::from(signature.r())) +
&format!("\"raw\":\"0x{}\",", rlp.to_hex()) +
&format!("\"s\":\"0x{:x}\",", U256::from(signature.s())) +
&format!("\"standardV\":\"0x{:x}\",", U256::from(t.standard_v())) +
r#""to":"0xd46e8dd67c5d32be8058bb8eb970870f07244567","transactionIndex":null,"# +
&format!("\"v\":\"0x{:x}\",", U256::from(t.original_v())) +
r#""value":"0x9184e72a""# +
r#"}},"id":1}"#;
tester.miner.increment_nonce(&address);
assert_eq!(tester.io.handle_request_sync(&request), Some(response));
}
#[test]
fn rpc_eth_send_transaction_with_bad_to() {
let tester = EthTester::default();
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_sendTransaction",
"params": [{
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
"to": "",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a"
}],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params: expected a hex-encoded hash with 0x prefix."},"id":1}"#;
assert_eq!(tester.io.handle_request_sync(&request), Some(response.into()));
}
#[test]
fn rpc_eth_send_transaction_error() {
let tester = EthTester::default();
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_sendTransaction",
"params": [{
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a"
}],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","error":{"code":-32020,"message":"Your account is locked. Unlock the account via CLI, personal_unlockAccount or use Trusted Signer.","data":"NotUnlocked"},"id":1}"#;
assert_eq!(tester.io.handle_request_sync(&request), Some(response.into()));
}
#[test]
fn rpc_eth_send_raw_transaction_error() {
let tester = EthTester::default();
@@ -1141,7 +961,7 @@ fn rpc_get_work_returns_no_work_if_cant_mine() {
#[test]
fn rpc_get_work_returns_correct_work_package() {
let eth_tester = EthTester::default();
eth_tester.miner.set_author(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap(), None).unwrap();
eth_tester.miner.set_author(miner::Author::External(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()));
let request = r#"{"jsonrpc": "2.0", "method": "eth_getWork", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":["0x76c7bd86693aee93d1a80a408a09a0585b1a1292afcb56192f171d925ea18e2d","0x0000000000000000000000000000000000000000000000000000000000000000","0x0000800000000000000000000000000000000000000000000000000000000000","0x1"],"id":1}"#;
@@ -1154,7 +974,7 @@ fn rpc_get_work_should_not_return_block_number() {
let eth_tester = EthTester::new_with_options(EthClientOptions::with(|options| {
options.send_block_number_in_get_work = false;
}));
eth_tester.miner.set_author(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap(), None).unwrap();
eth_tester.miner.set_author(miner::Author::External(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()));
let request = r#"{"jsonrpc": "2.0", "method": "eth_getWork", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":["0x76c7bd86693aee93d1a80a408a09a0585b1a1292afcb56192f171d925ea18e2d","0x0000000000000000000000000000000000000000000000000000000000000000","0x0000800000000000000000000000000000000000000000000000000000000000"],"id":1}"#;
@@ -1165,7 +985,7 @@ fn rpc_get_work_should_not_return_block_number() {
#[test]
fn rpc_get_work_should_timeout() {
let eth_tester = EthTester::default();
eth_tester.miner.set_author(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap(), None).unwrap();
eth_tester.miner.set_author(miner::Author::External(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()));
let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() - 1000; // Set latest block to 1000 seconds ago
eth_tester.client.set_latest_block_timestamp(timestamp);
let hash = eth_tester.miner.work_package(&*eth_tester.client).unwrap().0;

View File

@@ -23,13 +23,19 @@ mod eth_pubsub;
mod manage_network;
mod net;
mod parity;
#[cfg(any(test, feature = "accounts"))]
mod parity_accounts;
mod parity_set;
#[cfg(any(test, feature = "accounts"))]
mod personal;
mod pubsub;
mod rpc;
#[cfg(any(test, feature = "accounts"))]
mod secretstore;
mod signer;
#[cfg(any(test, feature = "accounts"))]
mod signing;
#[cfg(any(test, feature = "accounts"))]
mod signing_unsafe;
mod traces;
mod web3;

View File

@@ -15,7 +15,6 @@
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use ethcore::account_provider::AccountProvider;
use ethcore::client::{TestBlockChainClient, Executed, TransactionId};
use ethcore_logger::RotatingLogger;
use ethereum_types::{Address, U256, H256};
@@ -27,7 +26,8 @@ use types::receipt::{LocalizedReceipt, TransactionOutcome};
use jsonrpc_core::IoHandler;
use v1::{Parity, ParityClient};
use v1::metadata::Metadata;
use v1::helpers::{SignerService, NetworkSettings};
use v1::helpers::NetworkSettings;
use v1::helpers::external_signer::SignerService;
use v1::tests::helpers::{TestSyncProvider, Config, TestMinerService, TestUpdater};
use super::manage_network::TestManageNetwork;
use Host;
@@ -42,7 +42,6 @@ pub struct Dependencies {
pub logger: Arc<RotatingLogger>,
pub settings: Arc<NetworkSettings>,
pub network: Arc<ManageNetwork>,
pub accounts: Arc<AccountProvider>,
pub ws_address: Option<Host>,
}
@@ -67,7 +66,6 @@ impl Dependencies {
rpc_port: 8545,
}),
network: Arc::new(TestManageNetwork),
accounts: Arc::new(AccountProvider::transient_provider()),
ws_address: Some("127.0.0.1:18546".into()),
}
}
@@ -79,7 +77,6 @@ impl Dependencies {
self.sync.clone(),
self.updater.clone(),
self.network.clone(),
self.accounts.clone(),
self.logger.clone(),
self.settings.clone(),
signer,
@@ -101,47 +98,6 @@ impl Dependencies {
}
}
#[test]
fn rpc_parity_accounts_info() {
let deps = Dependencies::new();
let io = deps.default_client();
deps.accounts.new_account(&"".into()).unwrap();
let accounts = deps.accounts.accounts().unwrap();
assert_eq!(accounts.len(), 1);
let address = accounts[0];
deps.accounts.set_address_name(1.into(), "XX".into());
deps.accounts.set_account_name(address.clone(), "Test".into()).unwrap();
deps.accounts.set_account_meta(address.clone(), "{foo: 69}".into()).unwrap();
let request = r#"{"jsonrpc": "2.0", "method": "parity_accountsInfo", "params": [], "id": 1}"#;
let response = format!("{{\"jsonrpc\":\"2.0\",\"result\":{{\"0x{:x}\":{{\"name\":\"Test\"}}}},\"id\":1}}", address);
assert_eq!(io.handle_request_sync(request), Some(response));
}
#[test]
fn rpc_parity_default_account() {
let deps = Dependencies::new();
let io = deps.default_client();
// Check empty
let address = Address::default();
let request = r#"{"jsonrpc": "2.0", "method": "parity_defaultAccount", "params": [], "id": 1}"#;
let response = format!("{{\"jsonrpc\":\"2.0\",\"result\":\"0x{:x}\",\"id\":1}}", address);
assert_eq!(io.handle_request_sync(request), Some(response));
// With account
deps.accounts.new_account(&"".into()).unwrap();
let accounts = deps.accounts.accounts().unwrap();
assert_eq!(accounts.len(), 1);
let address = accounts[0];
let request = r#"{"jsonrpc": "2.0", "method": "parity_defaultAccount", "params": [], "id": 1}"#;
let response = format!("{{\"jsonrpc\":\"2.0\",\"result\":\"0x{:x}\",\"id\":1}}", address);
assert_eq!(io.handle_request_sync(request), Some(response));
}
#[test]
fn rpc_parity_consensus_capability() {
let deps = Dependencies::new();

View File

@@ -16,13 +16,14 @@
use std::sync::Arc;
use ethcore::account_provider::{AccountProvider, AccountProviderSettings};
use accounts::{AccountProvider, AccountProviderSettings};
use ethereum_types::Address;
use ethstore::EthStore;
use ethstore::accounts_dir::RootDiskDirectory;
use tempdir::TempDir;
use jsonrpc_core::IoHandler;
use v1::{ParityAccounts, ParityAccountsClient};
use v1::{ParityAccounts, ParityAccountsInfo, ParityAccountsClient};
struct ParityAccountsTester {
accounts: Arc<AccountProvider>,
@@ -42,8 +43,10 @@ fn accounts_provider_with_vaults_support(temp_path: &str) -> Arc<AccountProvider
fn setup_with_accounts_provider(accounts_provider: Arc<AccountProvider>) -> ParityAccountsTester {
let opt_ap = accounts_provider.clone();
let parity_accounts = ParityAccountsClient::new(&opt_ap);
let parity_accounts2 = ParityAccountsClient::new(&opt_ap);
let mut io = IoHandler::default();
io.extend_with(parity_accounts.to_delegate());
io.extend_with(ParityAccounts::to_delegate(parity_accounts));
io.extend_with(ParityAccountsInfo::to_delegate(parity_accounts2));
let tester = ParityAccountsTester {
accounts: accounts_provider,
@@ -61,6 +64,47 @@ fn setup_with_vaults_support(temp_path: &str) -> ParityAccountsTester {
setup_with_accounts_provider(accounts_provider_with_vaults_support(temp_path))
}
#[test]
fn rpc_parity_accounts_info() {
let tester = setup();
let io = tester.io;
tester.accounts.new_account(&"".into()).unwrap();
let accounts = tester.accounts.accounts().unwrap();
assert_eq!(accounts.len(), 1);
let address = accounts[0];
tester.accounts.set_address_name(1.into(), "XX".into());
tester.accounts.set_account_name(address.clone(), "Test".into()).unwrap();
tester.accounts.set_account_meta(address.clone(), "{foo: 69}".into()).unwrap();
let request = r#"{"jsonrpc": "2.0", "method": "parity_accountsInfo", "params": [], "id": 1}"#;
let response = format!("{{\"jsonrpc\":\"2.0\",\"result\":{{\"0x{:x}\":{{\"name\":\"Test\"}}}},\"id\":1}}", address);
assert_eq!(io.handle_request_sync(request), Some(response));
}
#[test]
fn rpc_parity_default_account() {
let tester = setup();
let io = tester.io;
// Check empty
let address = Address::default();
let request = r#"{"jsonrpc": "2.0", "method": "parity_defaultAccount", "params": [], "id": 1}"#;
let response = format!("{{\"jsonrpc\":\"2.0\",\"result\":\"0x{:x}\",\"id\":1}}", address);
assert_eq!(io.handle_request_sync(request), Some(response));
// With account
tester.accounts.new_account(&"".into()).unwrap();
let accounts = tester.accounts.accounts().unwrap();
assert_eq!(accounts.len(), 1);
let address = accounts[0];
let request = r#"{"jsonrpc": "2.0", "method": "parity_defaultAccount", "params": [], "id": 1}"#;
let response = format!("{{\"jsonrpc\":\"2.0\",\"result\":\"0x{:x}\",\"id\":1}}", address);
assert_eq!(io.handle_request_sync(request), Some(response));
}
#[test]
fn should_be_able_to_get_account_info() {
let tester = setup();

View File

@@ -54,7 +54,13 @@ fn parity_set_client(
updater: &Arc<TestUpdater>,
net: &Arc<TestManageNetwork>,
) -> TestParitySetClient {
ParitySetClient::new(client, miner, updater, &(net.clone() as Arc<ManageNetwork>), FakeFetch::new(Some(1)))
ParitySetClient::new(
client,
miner,
updater,
&(net.clone() as Arc<ManageNetwork>),
FakeFetch::new(Some(1)),
)
}
#[test]
@@ -161,23 +167,6 @@ fn rpc_parity_set_author() {
assert_eq!(miner.authoring_params().author, Address::from_str("cd1722f3947def4cf144679da39c4c32bdc35681").unwrap());
}
#[test]
fn rpc_parity_set_engine_signer() {
let miner = miner_service();
let client = client_service();
let network = network_service();
let updater = updater_service();
let mut io = IoHandler::new();
io.extend_with(parity_set_client(&client, &miner, &updater, &network).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "parity_setEngineSigner", "params":["0xcd1722f3947def4cf144679da39c4c32bdc35681", "password"], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
assert_eq!(miner.authoring_params().author, Address::from_str("cd1722f3947def4cf144679da39c4c32bdc35681").unwrap());
assert_eq!(*miner.password.read(), "password".into());
}
#[test]
fn rpc_parity_set_transactions_limit() {
let miner = miner_service();
@@ -236,3 +225,29 @@ fn rpc_parity_remove_transaction() {
miner.pending_transactions.lock().insert(hash, signed);
assert_eq!(io.handle_request_sync(&request), Some(response.to_owned()));
}
#[test]
fn rpc_parity_set_engine_signer() {
use accounts::AccountProvider;
use bytes::ToPretty;
use v1::impls::ParitySetAccountsClient;
use v1::traits::ParitySetAccounts;
let account_provider = Arc::new(AccountProvider::transient_provider());
account_provider.insert_account(::hash::keccak("cow").into(), &"password".into()).unwrap();
let miner = miner_service();
let mut io = IoHandler::new();
io.extend_with(
ParitySetAccountsClient::new(&account_provider, &miner).to_delegate()
);
let request = r#"{"jsonrpc": "2.0", "method": "parity_setEngineSigner", "params":["0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826", "password"], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
assert_eq!(miner.authoring_params().author, Address::from_str("cd2a3d9f938e13cd947ec05abc7fe734df8dd826").unwrap());
let signature = miner.signer.read().as_ref().unwrap().sign(::hash::keccak("x")).unwrap().to_vec();
assert_eq!(&format!("{}", signature.pretty()), "6f46069ded2154af6e806706e4f7f6fd310ac45f3c6dccb85f11c0059ee20a09245df0a0008bb84a10882b1298284bc93058e7bc5938ea728e77620061687a6401");
}

View File

@@ -19,7 +19,7 @@ use std::str::FromStr;
use bytes::ToPretty;
use ethereum_types::{U256, Address};
use ethcore::account_provider::AccountProvider;
use accounts::AccountProvider;
use ethcore::client::TestBlockChainClient;
use jsonrpc_core::IoHandler;
use parking_lot::Mutex;

View File

@@ -17,7 +17,7 @@
use std::sync::Arc;
use crypto::DEFAULT_MAC;
use ethcore::account_provider::AccountProvider;
use accounts::AccountProvider;
use ethkey::{KeyPair, Signature, verify_public};
use serde_json;

View File

@@ -19,7 +19,7 @@ use std::str::FromStr;
use ethereum_types::{U256, Address};
use bytes::ToPretty;
use ethcore::account_provider::AccountProvider;
use accounts::AccountProvider;
use ethcore::client::TestBlockChainClient;
use parity_runtime::Runtime;
use parking_lot::Mutex;
@@ -32,8 +32,9 @@ use v1::{SignerClient, Signer, Origin};
use v1::metadata::Metadata;
use v1::tests::helpers::TestMinerService;
use v1::types::{Bytes as RpcBytes, H520};
use v1::helpers::{nonce, SigningQueue, SignerService, FilledTransactionRequest, ConfirmationPayload};
use v1::helpers::dispatch::{FullDispatcher, eth_data_hash};
use v1::helpers::{nonce, FilledTransactionRequest, ConfirmationPayload};
use v1::helpers::external_signer::{SigningQueue, SignerService};
use v1::helpers::dispatch::{self, FullDispatcher, eth_data_hash};
struct SignerTester {
_runtime: Runtime,
@@ -60,13 +61,14 @@ fn signer_tester() -> SignerTester {
let runtime = Runtime::with_thread_count(1);
let signer = Arc::new(SignerService::new_test(false));
let accounts = accounts_provider();
let account_signer = Arc::new(dispatch::Signer::new(accounts.clone()));
let client = blockchain_client();
let miner = miner_service();
let reservations = Arc::new(Mutex::new(nonce::Reservations::new(runtime.executor())));
let dispatcher = FullDispatcher::new(client, miner.clone(), reservations, 50);
let mut io = IoHandler::default();
io.extend_with(SignerClient::new(&accounts, dispatcher, &signer, runtime.executor()).to_delegate());
io.extend_with(SignerClient::new(account_signer, dispatcher, &signer, runtime.executor()).to_delegate());
SignerTester {
_runtime: runtime,
@@ -555,29 +557,3 @@ fn should_generate_new_token() {
// then
assert_eq!(tester.io.handle_request_sync(&request), Some(response.to_owned()));
}
#[test]
fn should_generate_new_web_proxy_token() {
use jsonrpc_core::{Response, Output, Value};
// given
let tester = signer_tester();
// when
let request = r#"{
"jsonrpc":"2.0",
"method":"signer_generateWebProxyAccessToken",
"params":["https://parity.io"],
"id":1
}"#;
let response = tester.io.handle_request_sync(&request).unwrap();
let result = serde_json::from_str(&response).unwrap();
if let Response::Single(Output::Success(ref success)) = result {
if let Value::String(ref token) = success.result {
assert_eq!(tester.signer.web_proxy_access_token_domain(&token), Some("https://parity.io".into()));
return;
}
}
assert!(false, "Expected successful response, got: {:?}", result);
}

View File

@@ -25,14 +25,15 @@ use jsonrpc_core::futures::Future;
use v1::impls::SigningQueueClient;
use v1::metadata::Metadata;
use v1::traits::{EthSigning, ParitySigning, Parity};
use v1::helpers::{nonce, SignerService, SigningQueue, FullDispatcher};
use v1::helpers::{nonce, dispatch, FullDispatcher};
use v1::helpers::external_signer::{SignerService, SigningQueue};
use v1::types::{ConfirmationResponse, RichRawTransaction};
use v1::tests::helpers::TestMinerService;
use v1::tests::mocked::parity;
use ethereum_types::{U256, Address};
use accounts::AccountProvider;
use bytes::ToPretty;
use ethcore::account_provider::AccountProvider;
use ethereum_types::{U256, Address};
use ethcore::client::TestBlockChainClient;
use ethkey::Secret;
use ethstore::ethkey::{Generator, Random};
@@ -57,6 +58,7 @@ impl Default for SigningTester {
let client = Arc::new(TestBlockChainClient::default());
let miner = Arc::new(TestMinerService::default());
let accounts = Arc::new(AccountProvider::transient_provider());
let account_signer = Arc::new(dispatch::Signer::new(accounts.clone())) as _;
let reservations = Arc::new(Mutex::new(nonce::Reservations::new(runtime.executor())));
let mut io = IoHandler::default();
@@ -64,9 +66,9 @@ impl Default for SigningTester {
let executor = Executor::new_thread_per_future();
let rpc = SigningQueueClient::new(&signer, dispatcher.clone(), executor.clone(), &accounts);
let rpc = SigningQueueClient::new(&signer, dispatcher.clone(), executor.clone(), &account_signer);
io.extend_with(EthSigning::to_delegate(rpc));
let rpc = SigningQueueClient::new(&signer, dispatcher, executor, &accounts);
let rpc = SigningQueueClient::new(&signer, dispatcher, executor, &account_signer);
io.extend_with(ParitySigning::to_delegate(rpc));
SigningTester {
@@ -84,6 +86,30 @@ fn eth_signing() -> SigningTester {
SigningTester::default()
}
#[test]
fn rpc_eth_sign() {
use rustc_hex::FromHex;
let tester = eth_signing();
let account = tester.accounts.insert_account(Secret::from([69u8; 32]), &"abcd".into()).unwrap();
tester.accounts.unlock_account_permanently(account, "abcd".into()).unwrap();
let _message = "0cc175b9c0f1b6a831c399e26977266192eb5ffee6ae2fec3ad71c777531578f".from_hex().unwrap();
let req = r#"{
"jsonrpc": "2.0",
"method": "eth_sign",
"params": [
""#.to_owned() + &format!("0x{:x}", account) + r#"",
"0x0cc175b9c0f1b6a831c399e26977266192eb5ffee6ae2fec3ad71c777531578f"
],
"id": 1
}"#;
let res = r#"{"jsonrpc":"2.0","result":"0xa2870db1d0c26ef93c7b72d2a0830fa6b841e0593f7186bc6c7cc317af8cf3a42fda03bd589a49949aa05db83300cdb553116274518dbe9d90c65d0213f4af491b","id":1}"#;
assert_eq!(tester.io.handle_request_sync(&req), Some(res.into()));
}
#[test]
fn should_add_sign_to_queue() {
// given

View File

@@ -0,0 +1,237 @@
// 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 <http://www.gnu.org/licenses/>.
use std::str::FromStr;
use std::sync::Arc;
use accounts::AccountProvider;
use ethcore::client::TestBlockChainClient;
use ethereum_types::{U256, Address};
use parity_runtime::Runtime;
use parking_lot::Mutex;
use rlp;
use rustc_hex::ToHex;
use types::transaction::{Transaction, Action};
use jsonrpc_core::IoHandler;
use v1::{EthClientOptions, EthSigning, SigningUnsafeClient};
use v1::helpers::nonce;
use v1::helpers::dispatch::{self, FullDispatcher};
use v1::tests::helpers::{TestMinerService};
use v1::metadata::Metadata;
fn blockchain_client() -> Arc<TestBlockChainClient> {
let client = TestBlockChainClient::new();
Arc::new(client)
}
fn accounts_provider() -> Arc<AccountProvider> {
Arc::new(AccountProvider::transient_provider())
}
fn miner_service() -> Arc<TestMinerService> {
Arc::new(TestMinerService::default())
}
struct EthTester {
pub runtime: Runtime,
pub client: Arc<TestBlockChainClient>,
pub accounts_provider: Arc<AccountProvider>,
pub miner: Arc<TestMinerService>,
pub io: IoHandler<Metadata>,
}
impl Default for EthTester {
fn default() -> Self {
Self::new_with_options(Default::default())
}
}
impl EthTester {
pub fn new_with_options(options: EthClientOptions) -> Self {
let runtime = Runtime::with_thread_count(1);
let client = blockchain_client();
let accounts_provider = accounts_provider();
let ap = Arc::new(dispatch::Signer::new(accounts_provider.clone())) as _;
let miner = miner_service();
let gas_price_percentile = options.gas_price_percentile;
let reservations = Arc::new(Mutex::new(nonce::Reservations::new(runtime.executor())));
let dispatcher = FullDispatcher::new(client.clone(), miner.clone(), reservations, gas_price_percentile);
let sign = SigningUnsafeClient::new(&ap, dispatcher).to_delegate();
let mut io: IoHandler<Metadata> = IoHandler::default();
io.extend_with(sign);
EthTester {
runtime,
client,
miner,
io,
accounts_provider,
}
}
}
#[test]
fn rpc_eth_send_transaction() {
let tester = EthTester::default();
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
tester.accounts_provider.unlock_account_permanently(address, "".into()).unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_sendTransaction",
"params": [{
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a"
}],
"id": 1
}"#;
let t = Transaction {
nonce: U256::zero(),
gas_price: U256::from(0x9184e72a000u64),
gas: U256::from(0x76c0),
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
value: U256::from(0x9184e72au64),
data: vec![]
};
let signature = tester.accounts_provider.sign(address, None, t.hash(None)).unwrap();
let t = t.with_signature(signature, None);
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:x}", t.hash()).as_ref() + r#"","id":1}"#;
assert_eq!(tester.io.handle_request_sync(&request), Some(response));
tester.miner.increment_nonce(&address);
let t = Transaction {
nonce: U256::one(),
gas_price: U256::from(0x9184e72a000u64),
gas: U256::from(0x76c0),
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
value: U256::from(0x9184e72au64),
data: vec![]
};
let signature = tester.accounts_provider.sign(address, None, t.hash(None)).unwrap();
let t = t.with_signature(signature, None);
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:x}", t.hash()).as_ref() + r#"","id":1}"#;
assert_eq!(tester.io.handle_request_sync(&request), Some(response));
}
#[test]
fn rpc_eth_sign_transaction() {
let tester = EthTester::default();
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
tester.accounts_provider.unlock_account_permanently(address, "".into()).unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_signTransaction",
"params": [{
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a"
}],
"id": 1
}"#;
let t = Transaction {
nonce: U256::one(),
gas_price: U256::from(0x9184e72a000u64),
gas: U256::from(0x76c0),
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
value: U256::from(0x9184e72au64),
data: vec![]
};
let signature = tester.accounts_provider.sign(address, None, t.hash(None)).unwrap();
let t = t.with_signature(signature, None);
let signature = t.signature();
let rlp = rlp::encode(&t);
let response = r#"{"jsonrpc":"2.0","result":{"#.to_owned() +
r#""raw":"0x"# + &rlp.to_hex() + r#"","# +
r#""tx":{"# +
r#""blockHash":null,"blockNumber":null,"# +
&format!("\"chainId\":{},", t.chain_id().map_or("null".to_owned(), |n| format!("{}", n))) +
r#""condition":null,"creates":null,"# +
&format!("\"from\":\"0x{:x}\",", &address) +
r#""gas":"0x76c0","gasPrice":"0x9184e72a000","# +
&format!("\"hash\":\"0x{:x}\",", t.hash()) +
r#""input":"0x","# +
r#""nonce":"0x1","# +
&format!("\"publicKey\":\"0x{:x}\",", t.recover_public().unwrap()) +
&format!("\"r\":\"0x{:x}\",", U256::from(signature.r())) +
&format!("\"raw\":\"0x{}\",", rlp.to_hex()) +
&format!("\"s\":\"0x{:x}\",", U256::from(signature.s())) +
&format!("\"standardV\":\"0x{:x}\",", U256::from(t.standard_v())) +
r#""to":"0xd46e8dd67c5d32be8058bb8eb970870f07244567","transactionIndex":null,"# +
&format!("\"v\":\"0x{:x}\",", U256::from(t.original_v())) +
r#""value":"0x9184e72a""# +
r#"}},"id":1}"#;
tester.miner.increment_nonce(&address);
assert_eq!(tester.io.handle_request_sync(&request), Some(response));
}
#[test]
fn rpc_eth_send_transaction_with_bad_to() {
let tester = EthTester::default();
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_sendTransaction",
"params": [{
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
"to": "",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a"
}],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params: expected a hex-encoded hash with 0x prefix."},"id":1}"#;
assert_eq!(tester.io.handle_request_sync(&request), Some(response.into()));
}
#[test]
fn rpc_eth_send_transaction_error() {
let tester = EthTester::default();
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_sendTransaction",
"params": [{
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a"
}],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","error":{"code":-32020,"message":"Your account is locked. Unlock the account via CLI, personal_unlockAccount or use Trusted Signer.","data":"NotUnlocked"},"id":1}"#;
assert_eq!(tester.io.handle_request_sync(&request), Some(response.into()));
}

View File

@@ -40,8 +40,8 @@ pub use self::eth_pubsub::EthPubSub;
pub use self::eth_signing::EthSigning;
pub use self::net::Net;
pub use self::parity::Parity;
pub use self::parity_accounts::ParityAccounts;
pub use self::parity_set::ParitySet;
pub use self::parity_accounts::{ParityAccounts, ParityAccountsInfo};
pub use self::parity_set::{ParitySet, ParitySetAccounts};
pub use self::parity_signing::ParitySigning;
pub use self::personal::Personal;
pub use self::private::Private;

View File

@@ -26,7 +26,7 @@ use v1::types::{
TransactionStats, LocalTransactionStatus,
BlockNumber, ConsensusCapability, VersionInfo,
OperationsInfo, ChainStatus, Log, Filter,
AccountInfo, HwAccountInfo, RichHeader, Receipt,
RichHeader, Receipt,
};
/// Parity-specific rpc interface.
@@ -35,22 +35,6 @@ pub trait Parity {
/// RPC Metadata
type Metadata;
/// Returns accounts information.
#[rpc(name = "parity_accountsInfo")]
fn accounts_info(&self) -> Result<BTreeMap<H160, AccountInfo>>;
/// Returns hardware accounts information.
#[rpc(name = "parity_hardwareAccountsInfo")]
fn hardware_accounts_info(&self) -> Result<BTreeMap<H160, HwAccountInfo>>;
/// Get a list of paths to locked hardware wallets
#[rpc(name = "parity_lockedHardwareAccountsInfo")]
fn locked_hardware_accounts_info(&self) -> Result<Vec<String>>;
/// Returns default account for dapp.
#[rpc(name = "parity_defaultAccount")]
fn default_account(&self) -> Result<H160>;
/// Returns current transactions limit.
#[rpc(name = "parity_transactionsLimit")]
fn transactions_limit(&self) -> Result<usize>;

View File

@@ -22,6 +22,27 @@ use jsonrpc_derive::rpc;
use ethkey::Password;
use ethstore::KeyFile;
use v1::types::{H160, H256, H520, DeriveHash, DeriveHierarchical, ExtAccountInfo};
use v1::types::{AccountInfo, HwAccountInfo};
/// Parity-specific read-only accounts rpc interface.
#[rpc]
pub trait ParityAccountsInfo {
/// Returns accounts information.
#[rpc(name = "parity_accountsInfo")]
fn accounts_info(&self) -> Result<BTreeMap<H160, AccountInfo>>;
/// Returns hardware accounts information.
#[rpc(name = "parity_hardwareAccountsInfo")]
fn hardware_accounts_info(&self) -> Result<BTreeMap<H160, HwAccountInfo>>;
/// Get a list of paths to locked hardware wallets
#[rpc(name = "parity_lockedHardwareAccountsInfo")]
fn locked_hardware_accounts_info(&self) -> Result<Vec<String>>;
/// Returns default account for dapp.
#[rpc(name = "parity_defaultAccount")]
fn default_account(&self) -> Result<H160>;
}
/// Personal Parity rpc interface.
#[rpc]

View File

@@ -21,6 +21,14 @@ use jsonrpc_derive::rpc;
use v1::types::{Bytes, H160, H256, U256, ReleaseInfo, Transaction};
/// Parity-specific rpc interface for operations altering the account-related settings.
#[rpc]
pub trait ParitySetAccounts {
/// Sets account for signing consensus messages.
#[rpc(name = "parity_setEngineSigner")]
fn set_engine_signer(&self, H160, String) -> Result<bool>;
}
/// Parity-specific rpc interface for operations altering the settings.
#[rpc]
pub trait ParitySet {
@@ -44,9 +52,9 @@ pub trait ParitySet {
#[rpc(name = "parity_setAuthor")]
fn set_author(&self, H160) -> Result<bool>;
/// Sets account for signing consensus messages.
#[rpc(name = "parity_setEngineSigner")]
fn set_engine_signer(&self, H160, String) -> Result<bool>;
/// Sets the secret of engine signer account.
#[rpc(name = "parity_setEngineSignerSecret")]
fn set_engine_signer_secret(&self, H256) -> Result<bool>;
/// Sets the limits for transaction queue.
#[rpc(name = "parity_setTransactionsLimit")]

View File

@@ -51,10 +51,6 @@ pub trait Signer {
#[rpc(name = "signer_generateAuthorizationToken")]
fn generate_token(&self) -> Result<String>;
/// Generates new web proxy access token for particular domain.
#[rpc(name = "signer_generateWebProxyAccessToken")]
fn generate_web_proxy_token(&self, String) -> Result<String>;
/// Subscribe to new pending requests on signer interface.
#[pubsub(subscription = "signer_pending", subscribe, name = "signer_subscribePending")]
fn subscribe_pending(&self, Self::Metadata, Subscriber<Vec<ConfirmationRequest>>);