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

413 lines
11 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, Weak};
use std::str::FromStr;
use std::collections::{BTreeMap, HashSet};
use util::{RotatingLogger, Address};
use util::misc::version_data;
use crypto::ecies;
use ethkey::{Brain, Generator};
use ethstore::random_phrase;
use ethsync::{SyncProvider, ManageNetwork};
use ethcore::miner::MinerService;
use ethcore::client::{MiningBlockChainClient};
use ethcore::mode::Mode;
use ethcore::account_provider::AccountProvider;
2016-12-11 23:15:52 +01:00
use updater::{Service as UpdateService};
use jsonrpc_core::Error;
2016-12-13 14:27:27 +01:00
use jsonrpc_macros::Trailing;
use v1::traits::Parity;
2016-11-16 17:54:54 +01:00
use v1::types::{
Bytes, U256, H160, H256, H512,
Peers, Transaction, RpcSettings, Histogram,
TransactionStats, LocalTransactionStatus,
2016-12-12 02:57:19 +01:00
BlockNumber, ConsensusCapability, VersionInfo,
OperationsInfo, DappId, ChainStatus,
2016-11-16 17:54:54 +01:00
};
use v1::helpers::{errors, SigningQueue, SignerService, NetworkSettings};
use v1::helpers::dispatch::DEFAULT_MAC;
/// Parity implementation.
2016-12-11 23:15:52 +01:00
pub struct ParityClient<C, M, S: ?Sized, U> where
C: MiningBlockChainClient,
M: MinerService,
S: SyncProvider,
2016-12-11 23:15:52 +01:00
U: UpdateService,
{
client: Weak<C>,
miner: Weak<M>,
sync: Weak<S>,
2016-12-11 23:15:52 +01:00
updater: Weak<U>,
net: Weak<ManageNetwork>,
accounts: Weak<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>>,
dapps_interface: Option<String>,
2016-10-24 12:21:15 +02:00
dapps_port: Option<u16>,
}
2016-12-11 23:15:52 +01:00
impl<C, M, S: ?Sized, U> ParityClient<C, M, S, U> where
C: MiningBlockChainClient,
M: MinerService,
S: SyncProvider,
2016-12-11 23:15:52 +01:00
U: UpdateService,
{
/// Creates new `ParityClient`.
pub fn new(
client: &Arc<C>,
miner: &Arc<M>,
sync: &Arc<S>,
2016-12-11 23:15:52 +01:00
updater: &Arc<U>,
net: &Arc<ManageNetwork>,
store: &Arc<AccountProvider>,
logger: Arc<RotatingLogger>,
settings: Arc<NetworkSettings>,
2016-10-24 12:21:15 +02:00
signer: Option<Arc<SignerService>>,
dapps_interface: Option<String>,
2016-10-24 12:21:15 +02:00
dapps_port: Option<u16>,
) -> Self {
ParityClient {
client: Arc::downgrade(client),
2016-04-19 09:58:26 +02:00
miner: Arc::downgrade(miner),
sync: Arc::downgrade(sync),
2016-12-11 23:15:52 +01:00
updater: Arc::downgrade(updater),
net: Arc::downgrade(net),
accounts: Arc::downgrade(store),
2016-04-19 09:58:26 +02:00
logger: logger,
2016-04-21 19:19:42 +02:00
settings: settings,
signer: signer,
dapps_interface: dapps_interface,
2016-10-24 12:21:15 +02:00
dapps_port: dapps_port,
}
}
fn active(&self) -> Result<(), Error> {
// TODO: only call every 30s at most.
take_weak!(self.client).keep_alive();
Ok(())
}
}
2016-12-11 23:15:52 +01:00
impl<C, M, S: ?Sized, U> Parity for ParityClient<C, M, S, U> where
M: MinerService + 'static,
C: MiningBlockChainClient + 'static,
2016-12-11 23:15:52 +01:00
S: SyncProvider + 'static,
U: UpdateService + 'static,
{
fn accounts_info(&self, dapp: Trailing<DappId>) -> Result<BTreeMap<String, BTreeMap<String, String>>, Error> {
self.active()?;
let dapp = dapp.0;
let store = take_weak!(self.accounts);
let dapp_accounts = store
.note_dapp_used(dapp.clone().into())
.and_then(|_| store.dapps_addresses(dapp.into()))
.map_err(|e| errors::internal("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().expect("addresses_info always returns Ok; qed");
Ok(info
.into_iter()
.chain(other.into_iter())
.filter(|&(ref a, _)| dapp_accounts.contains(a))
.map(|(a, v)| {
let m = map![
"name".to_owned() => v.name
];
(format!("0x{}", a.hex()), m)
})
.collect()
)
}
fn transactions_limit(&self) -> Result<usize, Error> {
self.active()?;
Ok(take_weak!(self.miner).transactions_limit())
2016-04-18 23:13:38 +02:00
}
fn min_gas_price(&self) -> Result<U256, Error> {
self.active()?;
Ok(U256::from(take_weak!(self.miner).minimal_gas_price()))
}
fn extra_data(&self) -> Result<Bytes, Error> {
self.active()?;
Ok(Bytes::new(take_weak!(self.miner).extra_data()))
}
fn gas_floor_target(&self) -> Result<U256, Error> {
self.active()?;
Ok(U256::from(take_weak!(self.miner).gas_floor_target()))
}
2016-04-19 09:58:26 +02:00
fn gas_ceil_target(&self) -> Result<U256, Error> {
self.active()?;
Ok(U256::from(take_weak!(self.miner).gas_ceil_target()))
2016-06-23 14:29:16 +02:00
}
fn dev_logs(&self) -> Result<Vec<String>, Error> {
self.active()?;
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
}
fn dev_logs_levels(&self) -> Result<String, Error> {
self.active()?;
Ok(self.logger.levels().to_owned())
2016-04-19 09:58:26 +02:00
}
fn net_chain(&self) -> Result<String, Error> {
self.active()?;
Ok(self.settings.chain.clone())
2016-04-21 19:19:42 +02:00
}
fn net_peers(&self) -> Result<Peers, Error> {
self.active()?;
let sync = take_weak!(self.sync);
let sync_status = sync.status();
let net_config = take_weak!(self.net).network_config();
let peers = 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
}
fn net_port(&self) -> Result<u16, Error> {
self.active()?;
Ok(self.settings.network_port)
2016-04-21 19:19:42 +02:00
}
fn node_name(&self) -> Result<String, Error> {
self.active()?;
Ok(self.settings.name.clone())
2016-04-21 19:19:42 +02:00
}
fn registry_address(&self) -> Result<Option<H160>, Error> {
self.active()?;
Ok(
take_weak!(self.client)
.additional_params()
.get("registrar")
.and_then(|s| Address::from_str(s).ok())
.map(|s| H160::from(s))
)
}
fn rpc_settings(&self) -> Result<RpcSettings, Error> {
self.active()?;
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
fn default_extra_data(&self) -> Result<Bytes, Error> {
self.active()?;
Ok(Bytes::new(version_data()))
}
fn gas_price_histogram(&self) -> Result<Histogram, Error> {
self.active()?;
take_weak!(self.client).gas_price_histogram(100, 10).ok_or_else(errors::not_enough_data).map(Into::into)
2016-05-02 16:12:01 +02:00
}
fn unsigned_transactions_count(&self) -> Result<usize, Error> {
self.active()?;
match self.signer {
None => Err(errors::signer_disabled()),
Some(ref signer) => Ok(signer.len()),
}
}
fn generate_secret_phrase(&self) -> Result<String, Error> {
self.active()?;
Ok(random_phrase(12))
}
fn phrase_to_address(&self, phrase: String) -> Result<H160, Error> {
self.active()?;
Ok(Brain::new(phrase).generate().unwrap().address().into())
}
2016-11-28 01:32:40 +01:00
fn list_accounts(&self, count: u64, after: Option<H160>, block_number: Trailing<BlockNumber>) -> Result<Option<Vec<H160>>, Error> {
self.active()?;
Ok(take_weak!(self.client)
2016-11-28 01:32:40 +01:00
.list_accounts(block_number.0.into(), after.map(Into::into).as_ref(), count)
.map(|a| a.into_iter().map(Into::into).collect()))
}
2016-11-28 01:32:40 +01:00
fn list_storage_keys(&self, address: H160, count: u64, after: Option<H256>, block_number: Trailing<BlockNumber>) -> Result<Option<Vec<H256>>, Error> {
self.active()?;
2016-11-27 11:11:56 +01:00
Ok(take_weak!(self.client)
2016-11-28 01:32:40 +01:00
.list_storage(block_number.0.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()))
}
fn encrypt_message(&self, key: H512, phrase: Bytes) -> Result<Bytes, Error> {
self.active()?;
ecies::encrypt(&key.into(), &DEFAULT_MAC, &phrase.0)
.map_err(errors::encryption_error)
.map(Into::into)
}
fn pending_transactions(&self) -> Result<Vec<Transaction>, Error> {
self.active()?;
2016-12-16 14:54:26 +01:00
Ok(take_weak!(self.miner).pending_transactions().into_iter().map(Into::into).collect::<Vec<_>>())
}
2016-12-15 18:19:19 +01:00
fn future_transactions(&self) -> Result<Vec<Transaction>, Error> {
self.active()?;
2016-12-15 18:19:19 +01:00
Ok(take_weak!(self.miner).future_transactions().into_iter().map(Into::into).collect::<Vec<_>>())
}
2016-11-16 13:37:21 +01:00
fn pending_transactions_stats(&self) -> Result<BTreeMap<H256, TransactionStats>, Error> {
self.active()?;
2016-11-16 13:37:21 +01:00
let stats = take_weak!(self.sync).transactions_stats();
Ok(stats.into_iter()
.map(|(hash, stats)| (hash.into(), stats.into()))
.collect()
)
}
2016-11-16 17:54:54 +01:00
fn local_transactions(&self) -> Result<BTreeMap<H256, LocalTransactionStatus>, Error> {
self.active()?;
2016-11-16 17:54:54 +01:00
let transactions = take_weak!(self.miner).local_transactions();
Ok(transactions
.into_iter()
.map(|(hash, status)| (hash.into(), status.into()))
.collect()
)
}
2016-10-24 12:21:15 +02:00
fn signer_port(&self) -> Result<u16, Error> {
self.active()?;
2016-10-24 12:21:15 +02:00
self.signer
.clone()
.and_then(|signer| signer.address())
.map(|address| address.1)
2016-10-24 12:21:15 +02:00
.ok_or_else(|| errors::signer_disabled())
}
fn dapps_port(&self) -> Result<u16, Error> {
self.active()?;
2016-10-24 12:21:15 +02:00
self.dapps_port
.ok_or_else(|| errors::dapps_disabled())
}
2016-10-27 19:29:55 +02:00
fn dapps_interface(&self) -> Result<String, Error> {
self.active()?;
self.dapps_interface.clone()
.ok_or_else(|| errors::dapps_disabled())
}
2016-10-27 19:29:55 +02:00
fn next_nonce(&self, address: H160) -> Result<U256, Error> {
self.active()?;
2016-10-27 19:29:55 +02:00
let address: Address = address.into();
let miner = take_weak!(self.miner);
let client = take_weak!(self.client);
Ok(miner.last_nonce(&address)
.map(|n| n + 1.into())
.unwrap_or_else(|| client.latest_nonce(&address))
.into()
)
}
fn mode(&self) -> Result<String, Error> {
Ok(match take_weak!(self.client).mode() {
Mode::Off => "offline",
Mode::Dark(..) => "dark",
Mode::Passive(..) => "passive",
Mode::Active => "active",
}.into())
}
fn enode(&self) -> Result<String, Error> {
take_weak!(self.sync).enode().ok_or_else(errors::network_disabled)
}
2016-12-11 23:36:38 +01:00
fn consensus_capability(&self) -> Result<ConsensusCapability, Error> {
self.active()?;
2016-12-11 23:36:38 +01:00
let updater = take_weak!(self.updater);
Ok(updater.capability().into())
}
2016-12-12 02:57:19 +01:00
fn version_info(&self) -> Result<VersionInfo, Error> {
self.active()?;
2016-12-12 02:57:19 +01:00
let updater = take_weak!(self.updater);
Ok(updater.version_info().into())
}
fn releases_info(&self) -> Result<Option<OperationsInfo>, Error> {
self.active()?;
2016-12-12 02:57:19 +01:00
let updater = take_weak!(self.updater);
Ok(updater.info().map(Into::into))
}
fn chain_status(&self) -> Result<ChainStatus, Error> {
self.active()?;
let chain_info = take_weak!(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())),
})
}
}