rpc -> weak to arc (#5688)

* helpers-1

* helpers2-impls1

* small adjustments1

* cleanup-2

* small changes

* helper-impl-cleanup-finished

* test-update

* merge fix

* merge fix

* merge fix2

* fix tests

* fix tests2

* fix tests3
This commit is contained in:
Craig O'Connor 2017-05-28 08:40:36 -04:00 committed by Gav Wood
parent a246278727
commit 3991178b8d
21 changed files with 205 additions and 270 deletions

View File

@ -226,7 +226,7 @@ impl FullDependencies {
($namespace:ident, $handler:expr, $deps:expr) => {
{
let deps = &$deps;
let dispatcher = FullDispatcher::new(Arc::downgrade(&deps.client), Arc::downgrade(&deps.miner));
let dispatcher = FullDispatcher::new(deps.client.clone(), deps.miner.clone());
if deps.signer_service.is_enabled() {
$handler.extend_with($namespace::to_delegate(SigningQueueClient::new(&deps.signer_service, dispatcher, &deps.secret_store)))
} else {
@ -236,7 +236,7 @@ impl FullDependencies {
}
}
let dispatcher = FullDispatcher::new(Arc::downgrade(&self.client), Arc::downgrade(&self.miner));
let dispatcher = FullDispatcher::new(self.client.clone(), self.miner.clone());
for api in apis {
match *api {
Api::Web3 => {

View File

@ -14,14 +14,14 @@
// 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, Weak};
use std::sync::Arc;
use ethcore::account_provider::AccountProvider;
use jsonrpc_core::Error;
use v1::helpers::errors;
pub fn unwrap_provider(provider: &Option<Weak<AccountProvider>>) -> Result<Arc<AccountProvider>, Error> {
pub fn unwrap_provider(provider: &Option<Arc<AccountProvider>>) -> Result<Arc<AccountProvider>, Error> {
match *provider {
Some(ref weak) => weak.upgrade().ok_or_else(Error::internal_error),
Some(ref arc) => Ok(arc.clone()),
None => Err(errors::public_unsupported(None)),
}
}

View File

@ -18,7 +18,7 @@
use std::fmt::Debug;
use std::ops::Deref;
use std::sync::{Arc, Weak};
use std::sync::Arc;
use futures::{future, Future, BoxFuture};
use light::cache::Cache as LightDataCache;
@ -74,16 +74,16 @@ pub trait Dispatcher: Send + Sync + Clone {
/// requests locally.
#[derive(Debug)]
pub struct FullDispatcher<C, M> {
client: Weak<C>,
miner: Weak<M>,
client: Arc<C>,
miner: Arc<M>,
}
impl<C, M> FullDispatcher<C, M> {
/// Create a `FullDispatcher` from weak references to a client and miner.
pub fn new(client: Weak<C>, miner: Weak<M>) -> Self {
/// Create a `FullDispatcher` from Arc references to a client and miner.
pub fn new(client: Arc<C>, miner: Arc<M>) -> Self {
FullDispatcher {
client: client,
miner: miner,
client,
miner,
}
}
}
@ -109,7 +109,7 @@ impl<C: MiningBlockChainClient, M: MinerService> Dispatcher for FullDispatcher<C
fn fill_optional_fields(&self, request: TransactionRequest, default_sender: Address, force_nonce: bool)
-> BoxFuture<FilledTransactionRequest, Error>
{
let (client, miner) = (take_weakf!(self.client), take_weakf!(self.miner));
let (client, miner) = (self.client.clone(), self.miner.clone());
let request = request;
let from = request.from.unwrap_or(default_sender);
let nonce = match force_nonce {
@ -132,7 +132,7 @@ impl<C: MiningBlockChainClient, M: MinerService> Dispatcher for FullDispatcher<C
fn sign(&self, accounts: Arc<AccountProvider>, filled: FilledTransactionRequest, password: SignWith)
-> BoxFuture<WithToken<SignedTransaction>, Error>
{
let (client, miner) = (take_weakf!(self.client), take_weakf!(self.miner));
let (client, miner) = (self.client.clone(), self.miner.clone());
let network_id = client.signing_network_id();
let address = filled.from;
future::done({
@ -161,7 +161,7 @@ impl<C: MiningBlockChainClient, M: MinerService> Dispatcher for FullDispatcher<C
fn dispatch_transaction(&self, signed_transaction: PendingTransaction) -> Result<H256, Error> {
let hash = signed_transaction.transaction.hash();
take_weak!(self.miner).import_own_transaction(&*take_weak!(self.client), signed_transaction)
self.miner.import_own_transaction(&*self.client, signed_transaction)
.map_err(errors::from_transaction_error)
.map(|_| hash)
}

View File

@ -14,7 +14,7 @@
// 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::Weak;
use std::sync::Arc;
use ethcore::client::MiningBlockChainClient;
use ethcore::miner::MinerService;
use ethcore::transaction::{Transaction, SignedTransaction, Action};
@ -24,19 +24,17 @@ use v1::helpers::CallRequest;
use v1::helpers::dispatch::default_gas_price;
pub fn sign_call<B: MiningBlockChainClient, M: MinerService>(
client: &Weak<B>,
miner: &Weak<M>,
client: &Arc<B>,
miner: &Arc<M>,
request: CallRequest,
) -> Result<SignedTransaction, Error> {
let client = take_weak!(client);
let miner = take_weak!(miner);
let from = request.from.unwrap_or(0.into());
Ok(Transaction {
nonce: request.nonce.unwrap_or_else(|| client.latest_nonce(&from)),
action: request.to.map_or(Action::Create, Action::Call),
gas: request.gas.unwrap_or(50_000_000.into()),
gas_price: request.gas_price.unwrap_or_else(|| default_gas_price(&*client, &*miner)),
gas_price: request.gas_price.unwrap_or_else(|| default_gas_price(&**client, &**miner)),
value: request.value.unwrap_or(0.into()),
data: request.data.map_or_else(Vec::new, |d| d.to_vec())
}.fake_sign(from))

View File

@ -18,7 +18,7 @@
use std::thread;
use std::time::{Instant, Duration};
use std::sync::{Arc, Weak};
use std::sync::Arc;
use futures::{self, future, BoxFuture, Future};
use rlp::{self, UntrustedRlp};
@ -95,11 +95,11 @@ pub struct EthClient<C, SN: ?Sized, S: ?Sized, M, EM> where
M: MinerService,
EM: ExternalMinerService {
client: Weak<C>,
snapshot: Weak<SN>,
sync: Weak<S>,
accounts: Option<Weak<AccountProvider>>,
miner: Weak<M>,
client: Arc<C>,
snapshot: Arc<SN>,
sync: Arc<S>,
accounts: Option<Arc<AccountProvider>>,
miner: Arc<M>,
external_miner: Arc<EM>,
seed_compute: Mutex<SeedHashCompute>,
options: EthClientOptions,
@ -124,11 +124,11 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> EthClient<C, SN, S, M, EM> where
options: EthClientOptions
) -> Self {
EthClient {
client: Arc::downgrade(client),
snapshot: Arc::downgrade(snapshot),
sync: Arc::downgrade(sync),
miner: Arc::downgrade(miner),
accounts: accounts.as_ref().map(Arc::downgrade),
client: client.clone(),
snapshot: snapshot.clone(),
sync: sync.clone(),
miner: miner.clone(),
accounts: accounts.clone(),
external_miner: em.clone(),
seed_compute: Mutex::new(SeedHashCompute::new()),
options: options,
@ -137,13 +137,13 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> EthClient<C, SN, S, M, EM> where
}
/// Attempt to get the `Arc<AccountProvider>`, errors if provider was not
/// set, or if upgrading the weak reference failed.
/// set.
fn account_provider(&self) -> Result<Arc<AccountProvider>, Error> {
unwrap_provider(&self.accounts)
}
fn block(&self, id: BlockId, include_txs: bool) -> Result<Option<RichBlock>, Error> {
let client = take_weak!(self.client);
let client = &self.client;
match (client.block(id.clone()), client.block_total_difficulty(id)) {
(Some(block), Some(total_difficulty)) => {
let view = block.header_view();
@ -181,14 +181,14 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> EthClient<C, SN, S, M, EM> where
}
fn transaction(&self, id: TransactionId) -> Result<Option<Transaction>, Error> {
match take_weak!(self.client).transaction(id) {
match self.client.transaction(id) {
Some(t) => Ok(Some(Transaction::from_localized(t, self.eip86_transition))),
None => Ok(None),
}
}
fn uncle(&self, id: UncleId) -> Result<Option<RichBlock>, Error> {
let client = take_weak!(self.client);
let client = &self.client;
let uncle: BlockHeader = match client.uncle(id) {
Some(hdr) => hdr.decode(),
None => { return Ok(None); }
@ -280,16 +280,16 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
type Metadata = Metadata;
fn protocol_version(&self) -> Result<String, Error> {
let version = take_weak!(self.sync).status().protocol_version.to_owned();
let version = self.sync.status().protocol_version.to_owned();
Ok(format!("{}", version))
}
fn syncing(&self) -> Result<SyncStatus, Error> {
use ethcore::snapshot::RestorationStatus;
let status = take_weak!(self.sync).status();
let client = take_weak!(self.client);
let snapshot_status = take_weak!(self.snapshot).status();
let status = self.sync.status();
let client = &self.client;
let snapshot_status = self.snapshot.status();
let (warping, warp_chunks_amount, warp_chunks_processed) = match snapshot_status {
RestorationStatus::Ongoing { state_chunks, block_chunks, state_chunks_done, block_chunks_done } =>
@ -320,7 +320,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
let dapp = meta.dapp_id();
let author = move || {
let mut miner = take_weak!(self.miner).author();
let mut miner = self.miner.author();
if miner == 0.into() {
miner = self.dapp_accounts(dapp.into())?.get(0).cloned().unwrap_or_default();
}
@ -332,7 +332,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
}
fn is_mining(&self) -> Result<bool, Error> {
Ok(take_weak!(self.miner).is_sealing())
Ok(self.miner.is_sealing())
}
fn hashrate(&self) -> Result<RpcU256, Error> {
@ -340,8 +340,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
}
fn gas_price(&self) -> Result<RpcU256, Error> {
let (client, miner) = (take_weak!(self.client), take_weak!(self.miner));
Ok(RpcU256::from(default_gas_price(&*client, &*miner)))
Ok(RpcU256::from(default_gas_price(&*self.client, &*self.miner)))
}
fn accounts(&self, meta: Metadata) -> BoxFuture<Vec<RpcH160>, Error> {
@ -356,23 +355,22 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
}
fn block_number(&self) -> Result<RpcU256, Error> {
Ok(RpcU256::from(take_weak!(self.client).chain_info().best_block_number))
Ok(RpcU256::from(self.client.chain_info().best_block_number))
}
fn balance(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256, Error> {
let address = address.into();
let client = take_weakf!(self.client);
let res = match num.0.clone() {
BlockNumber::Pending => {
match take_weakf!(self.miner).balance(&*client, &address) {
match self.miner.balance(&*self.client, &address) {
Some(balance) => Ok(balance.into()),
None => Err(errors::database_error("latest balance missing"))
}
}
id => {
try_bf!(check_known(&*client, id.clone()));
match client.balance(&address, id.into()) {
try_bf!(check_known(&*self.client, id.clone()));
match self.client.balance(&address, id.into()) {
Some(balance) => Ok(balance.into()),
None => Err(errors::state_pruned()),
}
@ -388,17 +386,14 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
let res = match num.0.clone() {
BlockNumber::Pending => {
let client = take_weakf!(self.client);
match take_weakf!(self.miner).storage_at(&*client, &address, &H256::from(position)) {
match self.miner.storage_at(&*self.client, &address, &H256::from(position)) {
Some(s) => Ok(s.into()),
None => Err(errors::database_error("latest storage missing"))
}
}
id => {
let client = take_weakf!(self.client);
try_bf!(check_known(&*client, id.clone()));
match client.storage_at(&address, &H256::from(position), id.into()) {
try_bf!(check_known(&*self.client, id.clone()));
match self.client.storage_at(&address, &H256::from(position), id.into()) {
Some(s) => Ok(s.into()),
None => Err(errors::state_pruned()),
}
@ -410,28 +405,26 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
fn transaction_count(&self, address: RpcH160, num: Trailing<BlockNumber>) -> BoxFuture<RpcU256, Error> {
let address: Address = RpcH160::into(address);
let client = take_weakf!(self.client);
let miner = take_weakf!(self.miner);
let res = match num.0.clone() {
BlockNumber::Pending if self.options.pending_nonce_from_queue => {
let nonce = miner.last_nonce(&address)
let nonce = self.miner.last_nonce(&address)
.map(|n| n + 1.into())
.or_else(|| miner.nonce(&*client, &address));
.or_else(|| self.miner.nonce(&*self.client, &address));
match nonce {
Some(nonce) => Ok(nonce.into()),
None => Err(errors::database_error("latest nonce missing"))
}
}
BlockNumber::Pending => {
match miner.nonce(&*client, &address) {
match self.miner.nonce(&*self.client, &address) {
Some(nonce) => Ok(nonce.into()),
None => Err(errors::database_error("latest nonce missing"))
}
}
id => {
try_bf!(check_known(&*client, id.clone()));
match client.nonce(&address, id.into()) {
try_bf!(check_known(&*self.client, id.clone()));
match self.client.nonce(&address, id.into()) {
Some(nonce) => Ok(nonce.into()),
None => Err(errors::state_pruned()),
}
@ -442,23 +435,23 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
}
fn block_transaction_count_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<RpcU256>, Error> {
future::ok(take_weakf!(self.client).block(BlockId::Hash(hash.into()))
future::ok(self.client.block(BlockId::Hash(hash.into()))
.map(|block| block.transactions_count().into())).boxed()
}
fn block_transaction_count_by_number(&self, num: BlockNumber) -> BoxFuture<Option<RpcU256>, Error> {
future::ok(match num {
BlockNumber::Pending => Some(
take_weakf!(self.miner).status().transactions_in_pending_block.into()
self.miner.status().transactions_in_pending_block.into()
),
_ =>
take_weakf!(self.client).block(num.into())
self.client.block(num.into())
.map(|block| block.transactions_count().into())
}).boxed()
}
fn block_uncles_count_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<RpcU256>, Error> {
future::ok(take_weakf!(self.client).block(BlockId::Hash(hash.into()))
future::ok(self.client.block(BlockId::Hash(hash.into()))
.map(|block| block.uncles_count().into()))
.boxed()
}
@ -466,7 +459,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
fn block_uncles_count_by_number(&self, num: BlockNumber) -> BoxFuture<Option<RpcU256>, Error> {
future::ok(match num {
BlockNumber::Pending => Some(0.into()),
_ => take_weakf!(self.client).block(num.into())
_ => self.client.block(num.into())
.map(|block| block.uncles_count().into()
),
}).boxed()
@ -477,17 +470,14 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
let res = match num.0.clone() {
BlockNumber::Pending => {
let client = take_weakf!(self.client);
match take_weakf!(self.miner).code(&*client, &address) {
match self.miner.code(&*self.client, &address) {
Some(code) => Ok(code.map_or_else(Bytes::default, Bytes::new)),
None => Err(errors::database_error("latest code missing"))
}
}
id => {
let client = take_weakf!(self.client);
try_bf!(check_known(&*client, id.clone()));
match client.code(&address, id.into()) {
try_bf!(check_known(&*self.client, id.clone()));
match self.client.code(&address, id.into()) {
Some(code) => Ok(code.map_or_else(Bytes::default, Bytes::new)),
None => Err(errors::state_pruned()),
}
@ -507,10 +497,8 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
fn transaction_by_hash(&self, hash: RpcH256) -> Result<Option<Transaction>, Error> {
let hash: H256 = hash.into();
let miner = take_weak!(self.miner);
let client = take_weak!(self.client);
let block_number = client.chain_info().best_block_number;
Ok(self.transaction(TransactionId::Hash(hash))?.or_else(|| miner.transaction(block_number, &hash).map(|t| Transaction::from_pending(t, block_number, self.eip86_transition))))
let block_number = self.client.chain_info().best_block_number;
Ok(self.transaction(TransactionId::Hash(hash))?.or_else(|| self.miner.transaction(block_number, &hash).map(|t| Transaction::from_pending(t, block_number, self.eip86_transition))))
}
fn transaction_by_block_hash_and_index(&self, hash: RpcH256, index: Index) -> Result<Option<Transaction>, Error> {
@ -522,14 +510,12 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
}
fn transaction_receipt(&self, hash: RpcH256) -> Result<Option<Receipt>, Error> {
let miner = take_weak!(self.miner);
let best_block = take_weak!(self.client).chain_info().best_block_number;
let best_block = self.client.chain_info().best_block_number;
let hash: H256 = hash.into();
match (miner.pending_receipt(best_block, &hash), self.options.allow_pending_receipt_query) {
match (self.miner.pending_receipt(best_block, &hash), self.options.allow_pending_receipt_query) {
(Some(receipt), true) => Ok(Some(receipt.into())),
_ => {
let client = take_weak!(self.client);
let receipt = client.transaction_receipt(TransactionId::Hash(hash));
let receipt = self.client.transaction_receipt(TransactionId::Hash(hash));
Ok(receipt.map(Into::into))
}
}
@ -550,14 +536,14 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
fn logs(&self, filter: Filter) -> BoxFuture<Vec<Log>, Error> {
let include_pending = filter.to_block == Some(BlockNumber::Pending);
let filter: EthcoreFilter = filter.into();
let mut logs = take_weakf!(self.client).logs(filter.clone())
let mut logs = self.client.logs(filter.clone())
.into_iter()
.map(From::from)
.collect::<Vec<Log>>();
if include_pending {
let best_block = take_weakf!(self.client).chain_info().best_block_number;
let pending = pending_logs(&*take_weakf!(self.miner), best_block, &filter);
let best_block = self.client.chain_info().best_block_number;
let pending = pending_logs(&*self.miner, best_block, &filter);
logs.extend(pending);
}
@ -569,29 +555,27 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
fn work(&self, no_new_work_timeout: Trailing<u64>) -> Result<Work, Error> {
let no_new_work_timeout = no_new_work_timeout.0;
let client = take_weak!(self.client);
// check if we're still syncing and return empty strings in that case
{
//TODO: check if initial sync is complete here
//let sync = take_weak!(self.sync);
if /*sync.status().state != SyncState::Idle ||*/ client.queue_info().total_queue_size() > MAX_QUEUE_SIZE_TO_MINE_ON {
//let sync = self.sync;
if /*sync.status().state != SyncState::Idle ||*/ self.client.queue_info().total_queue_size() > MAX_QUEUE_SIZE_TO_MINE_ON {
trace!(target: "miner", "Syncing. Cannot give any work.");
return Err(errors::no_work());
}
// Otherwise spin until our submitted block has been included.
let timeout = Instant::now() + Duration::from_millis(1000);
while Instant::now() < timeout && client.queue_info().total_queue_size() > 0 {
while Instant::now() < timeout && self.client.queue_info().total_queue_size() > 0 {
thread::sleep(Duration::from_millis(1));
}
}
let miner = take_weak!(self.miner);
if miner.author().is_zero() {
if self.miner.author().is_zero() {
warn!(target: "miner", "Cannot give work package - no author is configured. Use --author to configure!");
return Err(errors::no_author())
}
miner.map_sealing_work(&*client, |b| {
self.miner.map_sealing_work(&*self.client, |b| {
let pow_hash = b.hash();
let target = Ethash::difficulty_to_boundary(b.block().header().difficulty());
let seed_hash = self.seed_compute.lock().get_seedhash(b.block().header().number());
@ -623,10 +607,8 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
let mix_hash: H256 = mix_hash.into();
trace!(target: "miner", "submit_work: Decoded: nonce={}, pow_hash={}, mix_hash={}", nonce, pow_hash, mix_hash);
let miner = take_weak!(self.miner);
let client = take_weak!(self.client);
let seal = vec![rlp::encode(&mix_hash).to_vec(), rlp::encode(&nonce).to_vec()];
Ok(miner.submit_seal(&*client, pow_hash, seal).is_ok())
Ok(self.miner.submit_seal(&*self.client, pow_hash, seal).is_ok())
}
fn submit_hashrate(&self, rate: RpcU256, id: RpcH256) -> Result<bool, Error> {
@ -657,8 +639,8 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
};
let result = match num.0 {
BlockNumber::Pending => take_weakf!(self.miner).call(&*take_weakf!(self.client), &signed, Default::default()),
num => take_weakf!(self.client).call(&signed, num.into(), Default::default()),
BlockNumber::Pending => self.miner.call(&*self.client, &signed, Default::default()),
num => self.client.call(&signed, num.into(), Default::default()),
};
future::done(result
@ -673,7 +655,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
Ok(signed) => signed,
Err(e) => return future::err(e).boxed(),
};
future::done(take_weakf!(self.client).estimate_gas(&signed, num.0.into())
future::done(self.client.estimate_gas(&signed, num.0.into())
.map(Into::into)
.map_err(errors::from_call_error)
).boxed()

View File

@ -15,32 +15,32 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Net rpc implementation.
use std::sync::{Arc, Weak};
use std::sync::Arc;
use jsonrpc_core::Error;
use ethsync::SyncProvider;
use v1::traits::Net;
/// Net rpc implementation.
pub struct NetClient<S: ?Sized> {
sync: Weak<S>
sync: Arc<S>
}
impl<S: ?Sized> NetClient<S> where S: SyncProvider {
/// Creates new NetClient.
pub fn new(sync: &Arc<S>) -> Self {
NetClient {
sync: Arc::downgrade(sync)
sync: sync.clone(),
}
}
}
impl<S: ?Sized> Net for NetClient<S> where S: SyncProvider + 'static {
fn version(&self) -> Result<String, Error> {
Ok(format!("{}", take_weak!(self.sync).status().network_id).to_owned())
Ok(format!("{}", self.sync.status().network_id).to_owned())
}
fn peer_count(&self) -> Result<String, Error> {
Ok(format!("0x{:x}", take_weak!(self.sync).status().num_peers as u64).to_owned())
Ok(format!("0x{:x}", self.sync.status().num_peers as u64).to_owned())
}
fn is_listening(&self) -> Result<bool, Error> {

View File

@ -15,7 +15,7 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Parity-specific rpc implementation.
use std::sync::{Arc, Weak};
use std::sync::Arc;
use std::str::FromStr;
use std::collections::{BTreeMap, HashSet};
use futures::{future, Future, BoxFuture};
@ -58,12 +58,12 @@ pub struct ParityClient<C, M, S: ?Sized, U> where
S: SyncProvider,
U: UpdateService,
{
client: Weak<C>,
miner: Weak<M>,
sync: Weak<S>,
updater: Weak<U>,
net: Weak<ManageNetwork>,
accounts: Option<Weak<AccountProvider>>,
client: Arc<C>,
miner: Arc<M>,
sync: Arc<S>,
updater: Arc<U>,
net: Arc<ManageNetwork>,
accounts: Option<Arc<AccountProvider>>,
logger: Arc<RotatingLogger>,
settings: Arc<NetworkSettings>,
signer: Option<Arc<SignerService>>,
@ -93,12 +93,12 @@ impl<C, M, S: ?Sized, U> ParityClient<C, M, S, U> where
ws_address: Option<(String, u16)>,
) -> Self {
ParityClient {
client: Arc::downgrade(client),
miner: Arc::downgrade(miner),
sync: Arc::downgrade(sync),
updater: Arc::downgrade(updater),
net: Arc::downgrade(net),
accounts: store.as_ref().map(Arc::downgrade),
client: client.clone(),
miner: miner.clone(),
sync: sync.clone(),
updater: updater.clone(),
net: net.clone(),
accounts: store.clone(),
logger: logger,
settings: settings,
signer: signer,
@ -109,7 +109,7 @@ impl<C, M, S: ?Sized, U> ParityClient<C, M, S, U> where
}
/// Attempt to get the `Arc<AccountProvider>`, errors if provider was not
/// set, or if upgrading the weak reference failed.
/// set.
fn account_provider(&self) -> Result<Arc<AccountProvider>, Error> {
unwrap_provider(&self.accounts)
}
@ -167,23 +167,23 @@ impl<C, M, S: ?Sized, U> Parity for ParityClient<C, M, S, U> where
}
fn transactions_limit(&self) -> Result<usize, Error> {
Ok(take_weak!(self.miner).transactions_limit())
Ok(self.miner.transactions_limit())
}
fn min_gas_price(&self) -> Result<U256, Error> {
Ok(U256::from(take_weak!(self.miner).minimal_gas_price()))
Ok(U256::from(self.miner.minimal_gas_price()))
}
fn extra_data(&self) -> Result<Bytes, Error> {
Ok(Bytes::new(take_weak!(self.miner).extra_data()))
Ok(Bytes::new(self.miner.extra_data()))
}
fn gas_floor_target(&self) -> Result<U256, Error> {
Ok(U256::from(take_weak!(self.miner).gas_floor_target()))
Ok(U256::from(self.miner.gas_floor_target()))
}
fn gas_ceil_target(&self) -> Result<U256, Error> {
Ok(U256::from(take_weak!(self.miner).gas_ceil_target()))
Ok(U256::from(self.miner.gas_ceil_target()))
}
fn dev_logs(&self) -> Result<Vec<String>, Error> {
@ -200,14 +200,13 @@ impl<C, M, S: ?Sized, U> Parity for ParityClient<C, M, S, U> where
}
fn chain(&self) -> Result<String, Error> {
Ok(take_weak!(self.client).spec_name())
Ok(self.client.spec_name())
}
fn net_peers(&self) -> Result<Peers, Error> {
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();
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,
@ -227,7 +226,7 @@ impl<C, M, S: ?Sized, U> Parity for ParityClient<C, M, S, U> where
fn registry_address(&self) -> Result<Option<H160>, Error> {
Ok(
take_weak!(self.client)
self.client
.additional_params()
.get("registrar")
.and_then(|s| Address::from_str(s).ok())
@ -248,7 +247,7 @@ impl<C, M, S: ?Sized, U> Parity for ParityClient<C, M, S, U> where
}
fn gas_price_histogram(&self) -> BoxFuture<Histogram, Error> {
future::done(take_weakf!(self.client)
future::done(self.client
.gas_price_corpus(100)
.histogram(10)
.ok_or_else(errors::not_enough_data)
@ -272,13 +271,13 @@ impl<C, M, S: ?Sized, U> Parity for ParityClient<C, M, S, U> where
}
fn list_accounts(&self, count: u64, after: Option<H160>, block_number: Trailing<BlockNumber>) -> Result<Option<Vec<H160>>, Error> {
Ok(take_weak!(self.client)
Ok(self.client
.list_accounts(block_number.0.into(), after.map(Into::into).as_ref(), count)
.map(|a| a.into_iter().map(Into::into).collect()))
}
fn list_storage_keys(&self, address: H160, count: u64, after: Option<H256>, block_number: Trailing<BlockNumber>) -> Result<Option<Vec<H256>>, Error> {
Ok(take_weak!(self.client)
Ok(self.client
.list_storage(block_number.0.into(), &address.into(), after.map(Into::into).as_ref(), count)
.map(|a| a.into_iter().map(Into::into).collect()))
}
@ -290,17 +289,17 @@ impl<C, M, S: ?Sized, U> Parity for ParityClient<C, M, S, U> where
}
fn pending_transactions(&self) -> Result<Vec<Transaction>, Error> {
let block_number = take_weak!(self.client).chain_info().best_block_number;
Ok(take_weak!(self.miner).pending_transactions().into_iter().map(|t| Transaction::from_pending(t, block_number, self.eip86_transition)).collect::<Vec<_>>())
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<_>>())
}
fn future_transactions(&self) -> Result<Vec<Transaction>, Error> {
let block_number = take_weak!(self.client).chain_info().best_block_number;
Ok(take_weak!(self.miner).future_transactions().into_iter().map(|t| Transaction::from_pending(t, block_number, self.eip86_transition)).collect::<Vec<_>>())
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<_>>())
}
fn pending_transactions_stats(&self) -> Result<BTreeMap<H256, TransactionStats>, Error> {
let stats = take_weak!(self.sync).transactions_stats();
let stats = self.sync.transactions_stats();
Ok(stats.into_iter()
.map(|(hash, stats)| (hash.into(), stats.into()))
.collect()
@ -308,8 +307,8 @@ impl<C, M, S: ?Sized, U> Parity for ParityClient<C, M, S, U> where
}
fn local_transactions(&self) -> Result<BTreeMap<H256, LocalTransactionStatus>, Error> {
let transactions = take_weak!(self.miner).local_transactions();
let block_number = take_weak!(self.client).chain_info().best_block_number;
let transactions = self.miner.local_transactions();
let block_number = self.client.chain_info().best_block_number;
Ok(transactions
.into_iter()
.map(|(hash, status)| (hash.into(), LocalTransactionStatus::from(status, block_number, self.eip86_transition)))
@ -329,18 +328,16 @@ impl<C, M, S: ?Sized, U> Parity for ParityClient<C, M, S, U> where
fn next_nonce(&self, address: H160) -> BoxFuture<U256, Error> {
let address: Address = address.into();
let miner = take_weakf!(self.miner);
let client = take_weakf!(self.client);
future::ok(miner.last_nonce(&address)
future::ok(self.miner.last_nonce(&address)
.map(|n| n + 1.into())
.unwrap_or_else(|| client.latest_nonce(&address))
.unwrap_or_else(|| self.client.latest_nonce(&address))
.into()
).boxed()
}
fn mode(&self) -> Result<String, Error> {
Ok(match take_weak!(self.client).mode() {
Ok(match self.client.mode() {
Mode::Off => "offline",
Mode::Dark(..) => "dark",
Mode::Passive(..) => "passive",
@ -349,26 +346,23 @@ impl<C, M, S: ?Sized, U> Parity for ParityClient<C, M, S, U> where
}
fn enode(&self) -> Result<String, Error> {
take_weak!(self.sync).enode().ok_or_else(errors::network_disabled)
self.sync.enode().ok_or_else(errors::network_disabled)
}
fn consensus_capability(&self) -> Result<ConsensusCapability, Error> {
let updater = take_weak!(self.updater);
Ok(updater.capability().into())
Ok(self.updater.capability().into())
}
fn version_info(&self) -> Result<VersionInfo, Error> {
let updater = take_weak!(self.updater);
Ok(updater.version_info().into())
Ok(self.updater.version_info().into())
}
fn releases_info(&self) -> Result<Option<OperationsInfo>, Error> {
let updater = take_weak!(self.updater);
Ok(updater.info().map(Into::into))
Ok(self.updater.info().map(Into::into))
}
fn chain_status(&self) -> Result<ChainStatus, Error> {
let chain_info = take_weak!(self.client).chain_info();
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))));
@ -395,16 +389,15 @@ impl<C, M, S: ?Sized, U> Parity for ParityClient<C, M, S, U> where
fn block_header(&self, number: Trailing<BlockNumber>) -> BoxFuture<RichHeader, Error> {
const EXTRA_INFO_PROOF: &'static str = "Object exists in in blockchain (fetched earlier), extra_info is always available if object exists; qed";
let client = take_weakf!(self.client);
let id: BlockId = number.0.into();
let encoded = match client.block_header(id.clone()) {
let encoded = match self.client.block_header(id.clone()) {
Some(encoded) => encoded,
None => return future::err(errors::unknown_block()).boxed(),
};
future::ok(RichHeader {
inner: encoded.into(),
extra_info: client.block_extra_info(id).expect(EXTRA_INFO_PROOF),
extra_info: self.client.block_extra_info(id).expect(EXTRA_INFO_PROOF),
}).boxed()
}

View File

@ -15,7 +15,7 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Account management (personal) rpc implementation
use std::sync::{Arc, Weak};
use std::sync::Arc;
use std::collections::BTreeMap;
use util::Address;
@ -31,19 +31,19 @@ use v1::types::{H160 as RpcH160, H256 as RpcH256, H520 as RpcH520, DappId, Deriv
/// Account management (personal) rpc implementation.
pub struct ParityAccountsClient {
accounts: Option<Weak<AccountProvider>>,
accounts: Option<Arc<AccountProvider>>,
}
impl ParityAccountsClient {
/// Creates new PersonalClient
pub fn new(store: &Option<Arc<AccountProvider>>) -> Self {
ParityAccountsClient {
accounts: store.as_ref().map(Arc::downgrade),
accounts: store.clone(),
}
}
/// Attempt to get the `Arc<AccountProvider>`, errors if provider was not
/// set, or if upgrading the weak reference failed.
/// set.
fn account_provider(&self) -> Result<Arc<AccountProvider>, Error> {
unwrap_provider(&self.accounts)
}

View File

@ -16,7 +16,7 @@
/// Parity-specific rpc interface for operations altering the settings.
use std::io;
use std::sync::{Arc, Weak};
use std::sync::Arc;
use ethcore::miner::MinerService;
use ethcore::client::MiningBlockChainClient;
@ -35,10 +35,10 @@ use v1::types::{Bytes, H160, H256, U256, ReleaseInfo, Transaction, LocalDapp};
/// Parity-specific rpc interface for operations altering the settings.
pub struct ParitySetClient<C, M, U, F = fetch::Client> {
client: Weak<C>,
miner: Weak<M>,
updater: Weak<U>,
net: Weak<ManageNetwork>,
client: Arc<C>,
miner: Arc<M>,
updater: Arc<U>,
net: Arc<ManageNetwork>,
dapps: Option<Arc<DappsService>>,
fetch: F,
eip86_transition: u64,
@ -57,10 +57,10 @@ impl<C, M, U, F> ParitySetClient<C, M, U, F>
fetch: F,
) -> Self {
ParitySetClient {
client: Arc::downgrade(client),
miner: Arc::downgrade(miner),
updater: Arc::downgrade(updater),
net: Arc::downgrade(net),
client: client.clone(),
miner: miner.clone(),
updater: updater.clone(),
net: net.clone(),
dapps: dapps,
fetch: fetch,
eip86_transition: client.eip86_transition(),
@ -76,81 +76,81 @@ impl<C, M, U, F> ParitySet for ParitySetClient<C, M, U, F> where
{
fn set_min_gas_price(&self, gas_price: U256) -> Result<bool, Error> {
take_weak!(self.miner).set_minimal_gas_price(gas_price.into());
self.miner.set_minimal_gas_price(gas_price.into());
Ok(true)
}
fn set_gas_floor_target(&self, target: U256) -> Result<bool, Error> {
take_weak!(self.miner).set_gas_floor_target(target.into());
self.miner.set_gas_floor_target(target.into());
Ok(true)
}
fn set_gas_ceil_target(&self, target: U256) -> Result<bool, Error> {
take_weak!(self.miner).set_gas_ceil_target(target.into());
self.miner.set_gas_ceil_target(target.into());
Ok(true)
}
fn set_extra_data(&self, extra_data: Bytes) -> Result<bool, Error> {
take_weak!(self.miner).set_extra_data(extra_data.into_vec());
self.miner.set_extra_data(extra_data.into_vec());
Ok(true)
}
fn set_author(&self, author: H160) -> Result<bool, Error> {
take_weak!(self.miner).set_author(author.into());
self.miner.set_author(author.into());
Ok(true)
}
fn set_engine_signer(&self, address: H160, password: String) -> Result<bool, Error> {
take_weak!(self.miner).set_engine_signer(address.into(), password).map_err(Into::into).map_err(errors::from_password_error)?;
self.miner.set_engine_signer(address.into(), password).map_err(Into::into).map_err(errors::from_password_error)?;
Ok(true)
}
fn set_transactions_limit(&self, limit: usize) -> Result<bool, Error> {
take_weak!(self.miner).set_transactions_limit(limit);
self.miner.set_transactions_limit(limit);
Ok(true)
}
fn set_tx_gas_limit(&self, limit: U256) -> Result<bool, Error> {
take_weak!(self.miner).set_tx_gas_limit(limit.into());
self.miner.set_tx_gas_limit(limit.into());
Ok(true)
}
fn add_reserved_peer(&self, peer: String) -> Result<bool, Error> {
match take_weak!(self.net).add_reserved_peer(peer) {
match self.net.add_reserved_peer(peer) {
Ok(()) => Ok(true),
Err(e) => Err(errors::invalid_params("Peer address", e)),
}
}
fn remove_reserved_peer(&self, peer: String) -> Result<bool, Error> {
match take_weak!(self.net).remove_reserved_peer(peer) {
match self.net.remove_reserved_peer(peer) {
Ok(()) => Ok(true),
Err(e) => Err(errors::invalid_params("Peer address", e)),
}
}
fn drop_non_reserved_peers(&self) -> Result<bool, Error> {
take_weak!(self.net).deny_unreserved_peers();
self.net.deny_unreserved_peers();
Ok(true)
}
fn accept_non_reserved_peers(&self) -> Result<bool, Error> {
take_weak!(self.net).accept_unreserved_peers();
self.net.accept_unreserved_peers();
Ok(true)
}
fn start_network(&self) -> Result<bool, Error> {
take_weak!(self.net).start_network();
self.net.start_network();
Ok(true)
}
fn stop_network(&self) -> Result<bool, Error> {
take_weak!(self.net).stop_network();
self.net.stop_network();
Ok(true)
}
fn set_mode(&self, mode: String) -> Result<bool, Error> {
take_weak!(self.client).set_mode(match mode.as_str() {
self.client.set_mode(match mode.as_str() {
"offline" => Mode::Off,
"dark" => Mode::Dark(300),
"passive" => Mode::Passive(300, 3600),
@ -161,7 +161,7 @@ impl<C, M, U, F> ParitySet for ParitySetClient<C, M, U, F> where
}
fn set_spec_name(&self, spec_name: String) -> Result<bool, Error> {
take_weak!(self.client).set_spec_name(spec_name);
self.client.set_spec_name(spec_name);
Ok(true)
}
@ -181,21 +181,17 @@ impl<C, M, U, F> ParitySet for ParitySetClient<C, M, U, F> where
}
fn upgrade_ready(&self) -> Result<Option<ReleaseInfo>, Error> {
let updater = take_weak!(self.updater);
Ok(updater.upgrade_ready().map(Into::into))
Ok(self.updater.upgrade_ready().map(Into::into))
}
fn execute_upgrade(&self) -> Result<bool, Error> {
let updater = take_weak!(self.updater);
Ok(updater.execute_upgrade())
Ok(self.updater.execute_upgrade())
}
fn remove_transaction(&self, hash: H256) -> Result<Option<Transaction>, Error> {
let miner = take_weak!(self.miner);
let client = take_weak!(self.client);
let block_number = take_weak!(self.client).chain_info().best_block_number;
let block_number = self.client.chain_info().best_block_number;
let hash = hash.into();
Ok(miner.remove_pending_transaction(&*client, &hash).map(|t| Transaction::from_pending(t, block_number, self.eip86_transition)))
Ok(self.miner.remove_pending_transaction(&*self.client, &hash).map(|t| Transaction::from_pending(t, block_number, self.eip86_transition)))
}
}

View File

@ -15,7 +15,7 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Account management (personal) rpc implementation
use std::sync::{Arc, Weak};
use std::sync::Arc;
use ethcore::account_provider::AccountProvider;
use ethcore::transaction::PendingTransaction;
@ -33,7 +33,7 @@ use v1::metadata::Metadata;
/// Account management (personal) rpc implementation.
pub struct PersonalClient<D: Dispatcher> {
accounts: Option<Weak<AccountProvider>>,
accounts: Option<Arc<AccountProvider>>,
dispatcher: D,
allow_perm_unlock: bool,
}
@ -42,7 +42,7 @@ impl<D: Dispatcher> PersonalClient<D> {
/// Creates new PersonalClient
pub fn new(store: &Option<Arc<AccountProvider>>, dispatcher: D, allow_perm_unlock: bool) -> Self {
PersonalClient {
accounts: store.as_ref().map(Arc::downgrade),
accounts: store.clone(),
dispatcher: dispatcher,
allow_perm_unlock: allow_perm_unlock,
}

View File

@ -16,7 +16,7 @@
//! SecretStore-specific rpc implementation.
use std::sync::{Arc, Weak};
use std::sync::Arc;
use crypto::DEFAULT_MAC;
use ethkey::Secret;
@ -31,19 +31,19 @@ use v1::types::{H160, H512, Bytes};
/// Parity implementation.
pub struct SecretStoreClient {
accounts: Option<Weak<AccountProvider>>,
accounts: Option<Arc<AccountProvider>>,
}
impl SecretStoreClient {
/// Creates new SecretStoreClient
pub fn new(store: &Option<Arc<AccountProvider>>) -> Self {
SecretStoreClient {
accounts: store.as_ref().map(Arc::downgrade),
accounts: store.clone(),
}
}
/// Attempt to get the `Arc<AccountProvider>`, errors if provider was not
/// set, or if upgrading the weak reference failed.
/// set.
fn account_provider(&self) -> Result<Arc<AccountProvider>, Error> {
unwrap_provider(&self.accounts)
}

View File

@ -16,7 +16,7 @@
//! Transactions Confirmations rpc implementation
use std::sync::{Arc, Weak};
use std::sync::Arc;
use ethcore::account_provider::AccountProvider;
use ethcore::transaction::{SignedTransaction, PendingTransaction};
@ -38,8 +38,8 @@ use v1::types::{TransactionModification, ConfirmationRequest, ConfirmationRespon
/// Transactions confirmation (personal) rpc implementation.
pub struct SignerClient<D: Dispatcher> {
signer: Weak<SignerService>,
accounts: Option<Weak<AccountProvider>>,
signer: Arc<SignerService>,
accounts: Option<Arc<AccountProvider>>,
dispatcher: D,
subscribers: Arc<Mutex<Subscribers<Sink<Vec<ConfirmationRequest>>>>>,
}
@ -70,8 +70,8 @@ impl<D: Dispatcher + 'static> SignerClient<D> {
});
SignerClient {
signer: Arc::downgrade(signer),
accounts: store.as_ref().map(Arc::downgrade),
signer: signer.clone(),
accounts: store.clone(),
dispatcher: dispatcher,
subscribers: subscribers,
}
@ -90,7 +90,7 @@ impl<D: Dispatcher + 'static> SignerClient<D> {
let dispatcher = self.dispatcher.clone();
let setup = || {
Ok((self.account_provider()?, take_weak!(self.signer)))
Ok((self.account_provider()?, self.signer.clone()))
};
let (accounts, signer) = match setup() {
@ -166,8 +166,7 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
type Metadata = Metadata;
fn requests_to_confirm(&self) -> Result<Vec<ConfirmationRequest>, Error> {
let signer = take_weak!(self.signer);
Ok(signer.requests()
Ok(self.signer.requests()
.into_iter()
.map(Into::into)
.collect()
@ -200,9 +199,8 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
fn confirm_request_raw(&self, id: U256, bytes: Bytes) -> Result<ConfirmationResponse, Error> {
let id = id.into();
let signer = take_weak!(self.signer);
signer.peek(&id).map(|confirmation| {
self.signer.peek(&id).map(|confirmation| {
let result = match confirmation.payload {
ConfirmationPayload::SendTransaction(request) => {
Self::verify_transaction(bytes, request, |pending_transaction| {
@ -231,24 +229,24 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
},
};
if let Ok(ref response) = result {
signer.request_confirmed(id, Ok(response.clone()));
self.signer.request_confirmed(id, Ok(response.clone()));
}
result
}).unwrap_or_else(|| Err(errors::invalid_params("Unknown RequestID", id)))
}
fn reject_request(&self, id: U256) -> Result<bool, Error> {
let res = take_weak!(self.signer).request_rejected(id.into());
let res = self.signer.request_rejected(id.into());
Ok(res.is_some())
}
fn generate_token(&self) -> Result<String, Error> {
take_weak!(self.signer).generate_token()
self.signer.generate_token()
.map_err(|e| errors::token(e))
}
fn generate_web_proxy_token(&self) -> Result<String, Error> {
Ok(take_weak!(self.signer).generate_web_proxy_access_token())
Ok(self.signer.generate_web_proxy_access_token())
}
fn subscribe_pending(&self, _meta: Self::Metadata, sub: Subscriber<Vec<ConfirmationRequest>>) {
@ -260,4 +258,3 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
futures::future::ok(res).boxed()
}
}

View File

@ -16,7 +16,7 @@
//! Signing RPC implementation.
use std::sync::{Arc, Weak};
use std::sync::Arc;
use transient_hashmap::TransientHashMap;
use util::{U256, Mutex};
@ -55,8 +55,8 @@ enum DispatchResult {
/// Implementation of functions that require signing when no trusted signer is used.
pub struct SigningQueueClient<D> {
signer: Weak<SignerService>,
accounts: Option<Weak<AccountProvider>>,
signer: Arc<SignerService>,
accounts: Option<Arc<AccountProvider>>,
dispatcher: D,
pending: Arc<Mutex<TransientHashMap<U256, ConfirmationPromise>>>,
}
@ -94,8 +94,8 @@ impl<D: Dispatcher + 'static> SigningQueueClient<D> {
/// Creates a new signing queue client given shared signing queue.
pub fn new(signer: &Arc<SignerService>, dispatcher: D, accounts: &Option<Arc<AccountProvider>>) -> Self {
SigningQueueClient {
signer: Arc::downgrade(signer),
accounts: accounts.as_ref().map(Arc::downgrade),
signer: signer.clone(),
accounts: accounts.clone(),
dispatcher: dispatcher,
pending: Arc::new(Mutex::new(TransientHashMap::new(MAX_PENDING_DURATION_SEC))),
}
@ -113,7 +113,7 @@ impl<D: Dispatcher + 'static> SigningQueueClient<D> {
};
let dispatcher = self.dispatcher.clone();
let signer = take_weakf!(self.signer);
let signer = self.signer.clone();
dispatch::from_rpc(payload, default_account, &dispatcher)
.and_then(move |payload| {
let sender = payload.sender();

View File

@ -16,7 +16,7 @@
//! Unsafe Signing RPC implementation.
use std::sync::{Arc, Weak};
use std::sync::Arc;
use ethcore::account_provider::AccountProvider;
@ -39,7 +39,7 @@ use v1::types::{
/// Implementation of functions that require signing when no trusted signer is used.
pub struct SigningUnsafeClient<D> {
accounts: Option<Weak<AccountProvider>>,
accounts: Option<Arc<AccountProvider>>,
dispatcher: D,
}
@ -47,7 +47,7 @@ impl<D: Dispatcher + 'static> SigningUnsafeClient<D> {
/// Creates new SigningUnsafeClient.
pub fn new(accounts: &Option<Arc<AccountProvider>>, dispatcher: D) -> Self {
SigningUnsafeClient {
accounts: accounts.as_ref().map(Arc::downgrade),
accounts: accounts.clone(),
dispatcher: dispatcher,
}
}

View File

@ -16,7 +16,7 @@
//! Traces api implementation.
use std::sync::{Weak, Arc};
use std::sync::Arc;
use rlp::UntrustedRlp;
use ethcore::client::{MiningBlockChainClient, CallAnalytics, TransactionId, TraceId};
@ -39,33 +39,33 @@ fn to_call_analytics(flags: Vec<String>) -> CallAnalytics {
/// Traces api implementation.
pub struct TracesClient<C, M> {
client: Weak<C>,
miner: Weak<M>,
client: Arc<C>,
miner: Arc<M>,
}
impl<C, M> TracesClient<C, M> {
/// Creates new Traces client.
pub fn new(client: &Arc<C>, miner: &Arc<M>) -> Self {
TracesClient {
client: Arc::downgrade(client),
miner: Arc::downgrade(miner),
client: client.clone(),
miner: miner.clone(),
}
}
}
impl<C, M> Traces for TracesClient<C, M> where C: MiningBlockChainClient + 'static, M: MinerService + 'static {
fn filter(&self, filter: TraceFilter) -> Result<Option<Vec<LocalizedTrace>>, Error> {
Ok(take_weak!(self.client).filter_traces(filter.into())
Ok(self.client.filter_traces(filter.into())
.map(|traces| traces.into_iter().map(LocalizedTrace::from).collect()))
}
fn block_traces(&self, block_number: BlockNumber) -> Result<Option<Vec<LocalizedTrace>>, Error> {
Ok(take_weak!(self.client).block_traces(block_number.into())
Ok(self.client.block_traces(block_number.into())
.map(|traces| traces.into_iter().map(LocalizedTrace::from).collect()))
}
fn transaction_traces(&self, transaction_hash: H256) -> Result<Option<Vec<LocalizedTrace>>, Error> {
Ok(take_weak!(self.client).transaction_traces(TransactionId::Hash(transaction_hash.into()))
Ok(self.client.transaction_traces(TransactionId::Hash(transaction_hash.into()))
.map(|traces| traces.into_iter().map(LocalizedTrace::from).collect()))
}
@ -75,7 +75,7 @@ impl<C, M> Traces for TracesClient<C, M> where C: MiningBlockChainClient + 'stat
address: address.into_iter().map(|i| i.value()).collect()
};
Ok(take_weak!(self.client).trace(id)
Ok(self.client.trace(id)
.map(LocalizedTrace::from))
}
@ -85,7 +85,7 @@ impl<C, M> Traces for TracesClient<C, M> where C: MiningBlockChainClient + 'stat
let request = CallRequest::into(request);
let signed = fake_sign::sign_call(&self.client, &self.miner, request)?;
take_weak!(self.client).call(&signed, block.into(), to_call_analytics(flags))
self.client.call(&signed, block.into(), to_call_analytics(flags))
.map(TraceResults::from)
.map_err(errors::from_call_error)
}
@ -96,13 +96,13 @@ impl<C, M> Traces for TracesClient<C, M> where C: MiningBlockChainClient + 'stat
let tx = UntrustedRlp::new(&raw_transaction.into_vec()).as_val().map_err(|e| errors::invalid_params("Transaction is not valid RLP", e))?;
let signed = SignedTransaction::new(tx).map_err(errors::from_transaction_error)?;
take_weak!(self.client).call(&signed, block.into(), to_call_analytics(flags))
self.client.call(&signed, block.into(), to_call_analytics(flags))
.map(TraceResults::from)
.map_err(errors::from_call_error)
}
fn replay_transaction(&self, transaction_hash: H256, flags: Vec<String>) -> Result<TraceResults, Error> {
take_weak!(self.client).replay(TransactionId::Hash(transaction_hash.into()), to_call_analytics(flags))
self.client.replay(TransactionId::Hash(transaction_hash.into()), to_call_analytics(flags))
.map(TraceResults::from)
.map_err(errors::from_call_error)
}

View File

@ -18,26 +18,6 @@
//!
//! Compliant with ethereum rpc.
// Upgrade a weak pointer, returning an error on failure.
macro_rules! take_weak {
($weak: expr) => {
match $weak.upgrade() {
Some(arc) => arc,
None => return Err(Error::internal_error()),
}
}
}
// Upgrade a weak pointer, returning an error leaf-future on failure.
macro_rules! take_weakf {
($weak: expr) => {
match $weak.upgrade() {
Some(arc) => arc,
None => return ::futures::future::err(Error::internal_error()).boxed(),
}
}
}
// short for "try_boxfuture"
// unwrap a result, returning a BoxFuture<_, Err> on failure.
macro_rules! try_bf {

View File

@ -141,7 +141,7 @@ impl EthTester {
Default::default(),
);
let dispatcher = FullDispatcher::new(Arc::downgrade(&client), Arc::downgrade(&miner_service));
let dispatcher = FullDispatcher::new(client.clone(), miner_service.clone());
let eth_sign = SigningUnsafeClient::new(
&opt_account_provider,
dispatcher,

View File

@ -92,7 +92,7 @@ impl EthTester {
let eth = EthClient::new(&client, &snapshot, &sync, &opt_ap, &miner, &external_miner, options).to_delegate();
let filter = EthFilterClient::new(client.clone(), miner.clone()).to_delegate();
let dispatcher = FullDispatcher::new(Arc::downgrade(&client), Arc::downgrade(&miner));
let dispatcher = FullDispatcher::new(client.clone(), miner.clone());
let sign = SigningUnsafeClient::new(&opt_ap, dispatcher).to_delegate();
let mut io: IoHandler<Metadata> = IoHandler::default();
io.extend_with(eth);

View File

@ -31,9 +31,6 @@ struct PersonalTester {
accounts: Arc<AccountProvider>,
io: IoHandler<Metadata>,
miner: Arc<TestMinerService>,
// these unused fields are necessary to keep the data alive
// as the handler has only weak pointers.
_client: Arc<TestBlockChainClient>,
}
fn blockchain_client() -> Arc<TestBlockChainClient> {
@ -55,7 +52,7 @@ fn setup() -> PersonalTester {
let client = blockchain_client();
let miner = miner_service();
let dispatcher = FullDispatcher::new(Arc::downgrade(&client), Arc::downgrade(&miner));
let dispatcher = FullDispatcher::new(client, miner.clone());
let personal = PersonalClient::new(&opt_accounts, dispatcher, false);
let mut io = IoHandler::default();
@ -65,7 +62,6 @@ fn setup() -> PersonalTester {
accounts: accounts,
io: io,
miner: miner,
_client: client,
};
tester
@ -220,4 +216,3 @@ fn should_unlock_account_permanently() {
assert_eq!(tester.io.handle_request_sync(&request), Some(response.into()));
assert!(tester.accounts.sign(address, None, Default::default()).is_ok(), "Should unlock account.");
}

View File

@ -38,10 +38,6 @@ struct SignerTester {
accounts: Arc<AccountProvider>,
io: IoHandler<Metadata>,
miner: Arc<TestMinerService>,
// these unused fields are necessary to keep the data alive
// as the handler has only weak pointers.
_client: Arc<TestBlockChainClient>,
_event_loop: EventLoop,
}
fn blockchain_client() -> Arc<TestBlockChainClient> {
@ -65,7 +61,7 @@ fn signer_tester() -> SignerTester {
let miner = miner_service();
let event_loop = EventLoop::spawn();
let dispatcher = FullDispatcher::new(Arc::downgrade(&client), Arc::downgrade(&miner));
let dispatcher = FullDispatcher::new(client, miner.clone());
let mut io = IoHandler::default();
io.extend_with(SignerClient::new(&opt_accounts, dispatcher, &signer, event_loop.remote()).to_delegate());
@ -74,8 +70,6 @@ fn signer_tester() -> SignerTester {
accounts: accounts,
io: io,
miner: miner,
_client: client,
_event_loop: event_loop,
}
}

View File

@ -54,7 +54,7 @@ impl Default for SigningTester {
let opt_accounts = Some(accounts.clone());
let mut io = IoHandler::default();
let dispatcher = FullDispatcher::new(Arc::downgrade(&client), Arc::downgrade(&miner));
let dispatcher = FullDispatcher::new(client.clone(), miner.clone());
let rpc = SigningQueueClient::new(&signer, dispatcher.clone(), &opt_accounts);
io.extend_with(EthSigning::to_delegate(rpc));