openethereum/rpc/src/v1/impls/parity.rs

438 lines
12 KiB
Rust
Raw Normal View History

// Copyright 2015-2017 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/>.
//! Parity-specific rpc implementation.
use std::sync::Arc;
use std::str::FromStr;
use std::collections::{BTreeMap, HashSet};
use util::Address;
use version::version_data;
use crypto::{DEFAULT_MAC, ecies};
use ethkey::{Brain, Generator};
use ethstore::random_phrase;
use ethsync::{SyncProvider, ManageNetwork};
use ethcore::account_provider::AccountProvider;
use ethcore::client::{MiningBlockChainClient};
use ethcore::ids::BlockId;
use ethcore::miner::MinerService;
use ethcore::mode::Mode;
use ethcore_logger::RotatingLogger;
use node_health::{NodeHealth, Health};
2016-12-11 23:15:52 +01:00
use updater::{Service as UpdateService};
2017-11-14 11:38:17 +01:00
use jsonrpc_core::{BoxFuture, Result};
use jsonrpc_core::futures::{future, Future};
2016-12-13 14:27:27 +01:00
use jsonrpc_macros::Trailing;
use v1::helpers::{self, errors, fake_sign, ipfs, SigningQueue, SignerService, NetworkSettings};
2017-03-29 17:07:58 +02:00
use v1::helpers::accounts::unwrap_provider;
use v1::metadata::Metadata;
use v1::traits::Parity;
2016-11-16 17:54:54 +01:00
use v1::types::{
Bytes, U256, U64, H160, H256, H512, CallRequest,
2016-11-16 17:54:54 +01:00
Peers, Transaction, RpcSettings, Histogram,
TransactionStats, LocalTransactionStatus,
2016-12-12 02:57:19 +01:00
BlockNumber, ConsensusCapability, VersionInfo,
OperationsInfo, DappId, ChainStatus,
AccountInfo, HwAccountInfo, RichHeader
2016-11-16 17:54:54 +01:00
};
2017-09-21 14:52:44 +02:00
use Host;
/// Parity implementation.
pub struct ParityClient<C, M, U> {
client: Arc<C>,
miner: Arc<M>,
updater: Arc<U>,
sync: Arc<SyncProvider>,
net: Arc<ManageNetwork>,
health: NodeHealth,
accounts: Option<Arc<AccountProvider>>,
2016-04-19 09:58:26 +02:00
logger: Arc<RotatingLogger>,
2016-04-21 19:19:42 +02:00
settings: Arc<NetworkSettings>,
signer: Option<Arc<SignerService>>,
2017-09-21 14:52:44 +02:00
dapps_address: Option<Host>,
ws_address: Option<Host>,
eip86_transition: u64,
}
impl<C, M, U> ParityClient<C, M, U> where
C: MiningBlockChainClient,
{
/// Creates new `ParityClient`.
pub fn new(
client: Arc<C>,
miner: Arc<M>,
sync: Arc<SyncProvider>,
updater: Arc<U>,
net: Arc<ManageNetwork>,
health: NodeHealth,
accounts: Option<Arc<AccountProvider>>,
logger: Arc<RotatingLogger>,
settings: Arc<NetworkSettings>,
2016-10-24 12:21:15 +02:00
signer: Option<Arc<SignerService>>,
2017-09-21 14:52:44 +02:00
dapps_address: Option<Host>,
ws_address: Option<Host>,
) -> Self {
let eip86_transition = client.eip86_transition();
ParityClient {
client,
miner,
sync,
updater,
net,
health,
accounts,
logger,
settings,
signer,
dapps_address,
ws_address,
eip86_transition,
}
}
2017-03-29 17:07:58 +02:00
/// Attempt to get the `Arc<AccountProvider>`, errors if provider was not
/// set.
2017-11-14 11:38:17 +01:00
fn account_provider(&self) -> Result<Arc<AccountProvider>> {
2017-03-29 17:07:58 +02:00
unwrap_provider(&self.accounts)
}
}
impl<C, M, U> Parity for ParityClient<C, M, U> where
C: MiningBlockChainClient + 'static,
M: MinerService + 'static,
U: UpdateService + 'static,
{
type Metadata = Metadata;
2017-11-14 11:38:17 +01:00
fn accounts_info(&self, dapp: Trailing<DappId>) -> Result<BTreeMap<H160, AccountInfo>> {
let dapp = dapp.unwrap_or_default();
2017-03-29 17:07:58 +02:00
let store = self.account_provider()?;
let dapp_accounts = store
.note_dapp_used(dapp.clone().into())
.and_then(|_| store.dapp_addresses(dapp.into()))
.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()
)
}
2017-11-14 11:38:17 +01:00
fn hardware_accounts_info(&self) -> Result<BTreeMap<H160, HwAccountInfo>> {
2017-03-29 17:07:58 +02:00
let store = self.account_provider()?;
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()
)
}
2017-11-14 11:38:17 +01:00
fn locked_hardware_accounts_info(&self) -> Result<Vec<String>> {
Trezor Support (#6403) * Copy modal from keepkey branch and generalize The keepkey PinMatrix modal needs to be the same for Trezor, but we should probably try to keep it general since it can be used for both. * Add trezor communication code This is a result of much trial-and-error and a couple of dead-ends in how to communicate and wire everything up. Code here is still a bit WIP with lots of debug prints and stuff. The test works though, it is possible to sign a transaction. * Extend the basic lib to allow Trezor This is kind of ugly and needs some cleanup and generalization. I’ve just copy-pasted some things to bring in the trezor wallets. I’ve also had to add a lock to the USB API so that only one thing talks to the USB at once. * Add RPC plumbing needed We need to be able to get “locked” devices from the frontend to figure out if we’re going to display the PinMatrix or not. Then we need to be able to send a pin to a device. * Add logic to query backend for Trezor and display PinMatrix There’s a bug somewhere here because signing a transaction fails if you take too long to press the confirm button on the device. * Change back to paritytech branch As my fork has been merged in. * Converting spaces to tabs, as it should be * Incorporate correct handling of EIP-155 Turns out the Trezor was adjusting the v part of the signature, and we’re already doing that so it was done twice. * Some circular logic here that was incorrect BE-encoded U256 is almost the same as RLP encoded without the size-byte, except for <u8 sized values. What’s really done is BE-encoded U256 and then left-trimmed to the smallest size. Kind of obvious in hindsight. * Resolve issue where not clicking fast enough fails The device will not repeat a ButtonRequest when you read from it, so you need to have a blocking `read` for whatever amount of time that you want to give the user to click. You could also have a shorter timeout but keep retrying for some amount of time, but it would amount to the same thing. * Scan after pin entry to make accepting it faster * Remove ability to cancel pin request * Some slight cleanup * Probe for the correct HID Version to determine padding * Move the PinMatrix from Accounts to Application * Removing unused dependencies * Mistake in copying over stuff from keepkey branch * Simplify FormattedMessage * Move generated code to external crate * Remove ethcore-util dependency * Fix broken import in test This test is useless without a connected Trezor, not sure how to make it useful without one. * Merge branch 'master' into fh-4500-trezor-support # Conflicts: # rpc/src/v1/helpers/dispatch.rs * Ignore test that can't be run without trezor device * Fixing grumbles * Avoiding owning data in RPC method * Checking for overflow in v part of signature * s/network_id/chain_id * Propagating an error from the HID Api * Condensing code a little bit * Fixing UI. * Debugging trezor. * Minor styling tweak * Make message type into an actual type This makes the message type that the RPC message accepts into an actual type as opposed to just a string, based on feedback. Although I’m not 100% sure this has actually improved the situation. Overall I think the hardware wallet interface needs some refactoring love. * Split the trezor RPC endpoint It’s split into two more generic endpoints that should be suitable for any hardware wallets with the same behavior to sit behind. * Reflect RPC method split in javascript * Fix bug with pin entry * Fix deadlock for Ledger * Avoid having a USB lock in just listing locked wallets * Fix javascript issue (see #6509) * Replace Mutex with RwLock * Update Ledger test * Fix typo causing faulty signatures (sometimes) * *Actually* fix tests * Update git submodule Needed to make tests pass * Swap line orders to prevent possible deadlock * Make setPinMatrixRequest an @action
2017-09-14 19:28:43 +02:00
let store = self.account_provider()?;
Ok(store.locked_hardware_accounts().map_err(|e| errors::account("Error communicating with hardware wallet.", e))?)
}
2017-11-14 11:38:17 +01:00
fn default_account(&self, meta: Self::Metadata) -> Result<H160> {
let dapp_id = meta.dapp_id();
Ok(self.account_provider()?
.dapp_default_address(dapp_id.into())
.map(Into::into)
.ok()
.unwrap_or_default())
}
2017-11-14 11:38:17 +01:00
fn transactions_limit(&self) -> Result<usize> {
Ok(self.miner.transactions_limit())
2016-04-18 23:13:38 +02:00
}
2017-11-14 11:38:17 +01:00
fn min_gas_price(&self) -> Result<U256> {
Ok(U256::from(self.miner.minimal_gas_price()))
}
2017-11-14 11:38:17 +01:00
fn extra_data(&self) -> Result<Bytes> {
Ok(Bytes::new(self.miner.extra_data()))
}
2017-11-14 11:38:17 +01:00
fn gas_floor_target(&self) -> Result<U256> {
Ok(U256::from(self.miner.gas_floor_target()))
}
2016-04-19 09:58:26 +02:00
2017-11-14 11:38:17 +01:00
fn gas_ceil_target(&self) -> Result<U256> {
Ok(U256::from(self.miner.gas_ceil_target()))
2016-06-23 14:29:16 +02:00
}
2017-11-14 11:38:17 +01:00
fn dev_logs(&self) -> Result<Vec<String>> {
2016-04-19 09:58:26 +02:00
let logs = self.logger.logs();
Ok(logs.as_slice().to_owned())
2016-04-19 09:58:26 +02:00
}
2017-11-14 11:38:17 +01:00
fn dev_logs_levels(&self) -> Result<String> {
Ok(self.logger.levels().to_owned())
2016-04-19 09:58:26 +02:00
}
2017-11-14 11:38:17 +01:00
fn net_chain(&self) -> Result<String> {
Ok(self.settings.chain.clone())
2016-04-21 19:19:42 +02:00
}
2017-11-14 11:38:17 +01:00
fn chain_id(&self) -> Result<Option<U64>> {
Ok(self.client.signing_chain_id().map(U64::from))
}
2017-11-14 11:38:17 +01:00
fn chain(&self) -> Result<String> {
Ok(self.client.spec_name())
}
2017-11-14 11:38:17 +01:00
fn net_peers(&self) -> Result<Peers> {
let sync_status = self.sync.status();
let net_config = self.net.network_config();
let peers = self.sync.peers().into_iter().map(Into::into).collect();
Ok(Peers {
active: sync_status.num_active_peers,
connected: sync_status.num_peers,
max: sync_status.current_max_peers(net_config.min_peers, net_config.max_peers),
peers: peers
})
2016-04-21 19:19:42 +02:00
}
2017-11-14 11:38:17 +01:00
fn net_port(&self) -> Result<u16> {
Ok(self.settings.network_port)
2016-04-21 19:19:42 +02:00
}
2017-11-14 11:38:17 +01:00
fn node_name(&self) -> Result<String> {
Ok(self.settings.name.clone())
2016-04-21 19:19:42 +02:00
}
2017-11-14 11:38:17 +01:00
fn registry_address(&self) -> Result<Option<H160>> {
Ok(
self.client
.additional_params()
.get("registrar")
.and_then(|s| Address::from_str(s).ok())
.map(|s| H160::from(s))
)
}
2017-11-14 11:38:17 +01:00
fn rpc_settings(&self) -> Result<RpcSettings> {
Ok(RpcSettings {
enabled: self.settings.rpc_enabled,
interface: self.settings.rpc_interface.clone(),
port: self.settings.rpc_port as u64,
})
2016-04-21 19:19:42 +02:00
}
2016-05-02 16:12:01 +02:00
2017-11-14 11:38:17 +01:00
fn default_extra_data(&self) -> Result<Bytes> {
Ok(Bytes::new(version_data()))
}
2017-11-14 11:38:17 +01:00
fn gas_price_histogram(&self) -> BoxFuture<Histogram> {
Box::new(future::done(self.client
2017-02-17 21:38:43 +01:00
.gas_price_corpus(100)
.histogram(10)
.ok_or_else(errors::not_enough_data)
.map(Into::into)
))
2016-05-02 16:12:01 +02:00
}
2017-11-14 11:38:17 +01:00
fn unsigned_transactions_count(&self) -> Result<usize> {
match self.signer {
None => Err(errors::signer_disabled()),
Some(ref signer) => Ok(signer.len()),
}
}
2017-11-14 11:38:17 +01:00
fn generate_secret_phrase(&self) -> Result<String> {
Ok(random_phrase(12))
}
2017-11-14 11:38:17 +01:00
fn phrase_to_address(&self, phrase: String) -> Result<H160> {
Ok(Brain::new(phrase).generate().unwrap().address().into())
}
2017-11-14 11:38:17 +01:00
fn list_accounts(&self, count: u64, after: Option<H160>, block_number: Trailing<BlockNumber>) -> Result<Option<Vec<H160>>> {
Ok(self.client
.list_accounts(block_number.unwrap_or_default().into(), after.map(Into::into).as_ref(), count)
.map(|a| a.into_iter().map(Into::into).collect()))
}
2017-11-14 11:38:17 +01:00
fn list_storage_keys(&self, address: H160, count: u64, after: Option<H256>, block_number: Trailing<BlockNumber>) -> Result<Option<Vec<H256>>> {
Ok(self.client
.list_storage(block_number.unwrap_or_default().into(), &address.into(), after.map(Into::into).as_ref(), count)
2016-11-27 11:11:56 +01:00
.map(|a| a.into_iter().map(Into::into).collect()))
}
2017-11-14 11:38:17 +01:00
fn encrypt_message(&self, key: H512, phrase: Bytes) -> Result<Bytes> {
ecies::encrypt(&key.into(), &DEFAULT_MAC, &phrase.0)
.map_err(errors::encryption)
.map(Into::into)
}
2017-11-14 11:38:17 +01:00
fn pending_transactions(&self) -> Result<Vec<Transaction>> {
let block_number = self.client.chain_info().best_block_number;
Ok(self.miner.pending_transactions().into_iter().map(|t| Transaction::from_pending(t, block_number, self.eip86_transition)).collect::<Vec<_>>())
}
2017-11-14 11:38:17 +01:00
fn future_transactions(&self) -> Result<Vec<Transaction>> {
let block_number = self.client.chain_info().best_block_number;
Ok(self.miner.future_transactions().into_iter().map(|t| Transaction::from_pending(t, block_number, self.eip86_transition)).collect::<Vec<_>>())
2016-12-15 18:19:19 +01:00
}
2017-11-14 11:38:17 +01:00
fn pending_transactions_stats(&self) -> Result<BTreeMap<H256, TransactionStats>> {
let stats = self.sync.transactions_stats();
2016-11-16 13:37:21 +01:00
Ok(stats.into_iter()
.map(|(hash, stats)| (hash.into(), stats.into()))
.collect()
)
}
2017-11-14 11:38:17 +01:00
fn local_transactions(&self) -> Result<BTreeMap<H256, LocalTransactionStatus>> {
// Return nothing if accounts are disabled (running as public node)
if self.accounts.is_none() {
return Ok(BTreeMap::new());
}
let transactions = self.miner.local_transactions();
let block_number = self.client.chain_info().best_block_number;
2016-11-16 17:54:54 +01:00
Ok(transactions
.into_iter()
.map(|(hash, status)| (hash.into(), LocalTransactionStatus::from(status, block_number, self.eip86_transition)))
2016-11-16 17:54:54 +01:00
.collect()
)
}
2017-11-14 11:38:17 +01:00
fn dapps_url(&self) -> Result<String> {
helpers::to_url(&self.dapps_address)
2016-10-24 12:21:15 +02:00
.ok_or_else(|| errors::dapps_disabled())
}
2016-10-27 19:29:55 +02:00
2017-11-14 11:38:17 +01:00
fn ws_url(&self) -> Result<String> {
helpers::to_url(&self.ws_address)
.ok_or_else(|| errors::ws_disabled())
}
2017-11-14 11:38:17 +01:00
fn next_nonce(&self, address: H160) -> BoxFuture<U256> {
2016-10-27 19:29:55 +02:00
let address: Address = address.into();
Box::new(future::ok(self.miner.last_nonce(&address)
2016-10-27 19:29:55 +02:00
.map(|n| n + 1.into())
.unwrap_or_else(|| self.client.latest_nonce(&address))
2016-10-27 19:29:55 +02:00
.into()
))
2016-10-27 19:29:55 +02:00
}
2017-11-14 11:38:17 +01:00
fn mode(&self) -> Result<String> {
Ok(match self.client.mode() {
Mode::Off => "offline",
Mode::Dark(..) => "dark",
Mode::Passive(..) => "passive",
Mode::Active => "active",
}.into())
}
2017-11-14 11:38:17 +01:00
fn enode(&self) -> Result<String> {
self.sync.enode().ok_or_else(errors::network_disabled)
}
2017-11-14 11:38:17 +01:00
fn consensus_capability(&self) -> Result<ConsensusCapability> {
Ok(self.updater.capability().into())
2016-12-11 23:36:38 +01:00
}
2016-12-12 02:57:19 +01:00
2017-11-14 11:38:17 +01:00
fn version_info(&self) -> Result<VersionInfo> {
Ok(self.updater.version_info().into())
2016-12-12 02:57:19 +01:00
}
2017-11-14 11:38:17 +01:00
fn releases_info(&self) -> Result<Option<OperationsInfo>> {
Ok(self.updater.info().map(Into::into))
2016-12-12 02:57:19 +01:00
}
2017-11-14 11:38:17 +01:00
fn chain_status(&self) -> Result<ChainStatus> {
let chain_info = self.client.chain_info();
let gap = chain_info.ancient_block_number.map(|x| U256::from(x + 1))
.and_then(|first| chain_info.first_block_number.map(|last| (first, U256::from(last))));
Ok(ChainStatus {
block_gap: gap.map(|(x, y)| (x.into(), y.into())),
})
}
2017-11-14 11:38:17 +01:00
fn node_kind(&self) -> Result<::v1::types::NodeKind> {
use ::v1::types::{NodeKind, Availability, Capability};
2017-03-29 17:07:58 +02:00
let availability = match self.accounts {
Some(_) => Availability::Personal,
None => Availability::Public
};
Ok(NodeKind {
2017-03-29 17:07:58 +02:00
availability: availability,
capability: Capability::Full,
})
}
2017-11-14 11:38:17 +01:00
fn block_header(&self, number: Trailing<BlockNumber>) -> BoxFuture<RichHeader> {
const EXTRA_INFO_PROOF: &'static str = "Object exists in in blockchain (fetched earlier), extra_info is always available if object exists; qed";
let id: BlockId = number.unwrap_or_default().into();
let encoded = match self.client.block_header(id.clone()) {
Some(encoded) => encoded,
None => return Box::new(future::err(errors::unknown_block())),
};
Box::new(future::ok(RichHeader {
inner: encoded.into(),
extra_info: self.client.block_extra_info(id).expect(EXTRA_INFO_PROOF),
}))
}
2017-11-14 11:38:17 +01:00
fn ipfs_cid(&self, content: Bytes) -> Result<String> {
ipfs::cid(content)
}
2017-11-14 11:38:17 +01:00
fn call(&self, meta: Self::Metadata, requests: Vec<CallRequest>, block: Trailing<BlockNumber>) -> Result<Vec<Bytes>> {
let requests = requests
.into_iter()
.map(|request| Ok((
fake_sign::sign_call(request.into(), meta.is_dapp())?,
Default::default()
)))
2017-11-14 11:38:17 +01:00
.collect::<Result<Vec<_>>>()?;
let block = block.unwrap_or_default();
self.client.call_many(&requests, block.into())
.map(|res| res.into_iter().map(|res| res.output.into()).collect())
.map_err(errors::call)
}
2017-11-14 11:38:17 +01:00
fn node_health(&self) -> BoxFuture<Health> {
Box::new(self.health.health()
.map_err(|err| errors::internal("Health API failure.", err)))
}
}