      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248

    // 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/>.

    //! Signing RPC implementation.

    use std::sync::{Arc, Weak};
    use transient_hashmap::TransientHashMap;
    use util::{U256, Mutex};

    use ethcore::account_provider::AccountProvider;
    use ethcore::miner::MinerService;
    use ethcore::client::MiningBlockChainClient;

    use futures::{self, BoxFuture, Future};
    use jsonrpc_core::Error;
    use v1::helpers::{
    	errors, dispatch,
    	DefaultAccount,
    	SigningQueue, ConfirmationPromise, ConfirmationResult, ConfirmationPayload, SignerService
    };
    use v1::metadata::Metadata;
    use v1::traits::{EthSigning, ParitySigning};
    use v1::types::{
    	H160 as RpcH160, H256 as RpcH256, U256 as RpcU256, Bytes as RpcBytes, H520 as RpcH520,
    	Either as RpcEither,
    	RichRawTransaction as RpcRichRawTransaction,
    	TransactionRequest as RpcTransactionRequest,
    	ConfirmationPayload as RpcConfirmationPayload,
    	ConfirmationResponse as RpcConfirmationResponse
    };

    const MAX_PENDING_DURATION: u64 = 60 * 60;

    enum DispatchResult {
    	Promise(ConfirmationPromise),
    	Value(RpcConfirmationResponse),
    }

    /// Implementation of functions that require signing when no trusted signer is used.
    pub struct SigningQueueClient<C, M> where C: MiningBlockChainClient, M: MinerService {
    	signer: Weak<SignerService>,
    	accounts: Weak<AccountProvider>,
    	client: Weak<C>,
    	miner: Weak<M>,

    	pending: Mutex<TransientHashMap<U256, ConfirmationPromise>>,
    }

    impl<C, M> SigningQueueClient<C, M> where
    	C: MiningBlockChainClient,
    	M: MinerService,
    {
    	/// Creates a new signing queue client given shared signing queue.
    	pub fn new(signer: &Arc<SignerService>, client: &Arc<C>, miner: &Arc<M>, accounts: &Arc<AccountProvider>) -> Self {
    		SigningQueueClient {
    			signer: Arc::downgrade(signer),
    			accounts: Arc::downgrade(accounts),
    			client: Arc::downgrade(client),
    			miner: Arc::downgrade(miner),
    			pending: Mutex::new(TransientHashMap::new(MAX_PENDING_DURATION)),
    		}
    	}

    	fn active(&self) -> Result<(), Error> {
    		// TODO: only call every 30s at most.
    		take_weak!(self.client).keep_alive();
    		Ok(())
    	}

    	fn handle_dispatch<OnResponse>(&self, res: Result<DispatchResult, Error>, on_response: OnResponse)
    		where OnResponse: FnOnce(Result<RpcConfirmationResponse, Error>) + Send + 'static
    	{
    		match res {
    			Ok(DispatchResult::Value(result)) => on_response(Ok(result)),
    			Ok(DispatchResult::Promise(promise)) => {
    				promise.wait_for_result(move |result| {
    					on_response(result.unwrap_or_else(|| Err(errors::request_rejected())))
    				})
    			},
    			Err(e) => on_response(Err(e)),
    		}
    	}

    	fn add_to_queue(&self, payload: ConfirmationPayload) -> Result<DispatchResult, Error> {
    		let client = take_weak!(self.client);
    		let miner = take_weak!(self.miner);
    		let accounts = take_weak!(self.accounts);

    		let sender = payload.sender();
    		if accounts.is_unlocked(sender) {
    			return dispatch::execute(&*client, &*miner, &*accounts, payload, dispatch::SignWith::Nothing)
    				.map(|v| v.into_value())
    				.map(DispatchResult::Value);
    		}

    		take_weak!(self.signer).add_request(payload)
    			.map(DispatchResult::Promise)
    			.map_err(|_| errors::request_rejected_limit())
    	}

    	fn dispatch(&self, payload: RpcConfirmationPayload, default_account: DefaultAccount) -> Result<DispatchResult, Error> {
    		let client = take_weak!(self.client);
    		let miner = take_weak!(self.miner);

    		let default_account = match default_account {
    			DefaultAccount::Provided(acc) => acc,
    			DefaultAccount::ForDapp(dapp) => take_weak!(self.accounts).default_address(dapp).ok().unwrap_or_default(),
    		};
    		let payload = dispatch::from_rpc(payload, default_account, &*client, &*miner);
    		self.add_to_queue(payload)
    	}
    }

    impl<C: 'static, M: 'static> ParitySigning for SigningQueueClient<C, M> where
    	C: MiningBlockChainClient,
    	M: MinerService,
    {
    	type Metadata = Metadata;

    	fn post_sign(&self, address: RpcH160, data: RpcBytes) -> Result<RpcEither<RpcU256, RpcConfirmationResponse>, Error> {
    		self.active()?;
    		self.dispatch(RpcConfirmationPayload::Signature((address.clone(), data).into()), DefaultAccount::Provided(address.into()))
    			.map(|result| match result {
    				DispatchResult::Value(v) => RpcEither::Or(v),
    				DispatchResult::Promise(promise) => {
    					let id = promise.id();
    					self.pending.lock().insert(id, promise);
    					RpcEither::Either(id.into())
    				},
    			})
    	}

    	fn post_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcEither<RpcU256, RpcConfirmationResponse>, Error> {
    		let post_transaction = move || {
    			self.active()?;
    			self.dispatch(RpcConfirmationPayload::SendTransaction(request), meta.into())
    				.map(|result| match result {
    					DispatchResult::Value(v) => RpcEither::Or(v),
    					DispatchResult::Promise(promise) => {
    						let id = promise.id();
    						self.pending.lock().insert(id, promise);
    						RpcEither::Either(id.into())
    					},
    				})
    		};
    		futures::done(post_transaction()).boxed()
    	}

    	fn check_request(&self, id: RpcU256) -> Result<Option<RpcConfirmationResponse>, Error> {
    		self.active()?;
    		let mut pending = self.pending.lock();
    		let id: U256 = id.into();
    		let res = match pending.get(&id) {
    			Some(ref promise) => match promise.result() {
    				ConfirmationResult::Waiting => { return Ok(None); }
    				ConfirmationResult::Rejected => Err(errors::request_rejected()),
    				ConfirmationResult::Confirmed(rpc_response) => rpc_response.map(Some),
    			},
    			_ => { return Err(errors::request_not_found()); }
    		};
    		pending.remove(&id);
    		res
    	}

    	fn decrypt_message(&self, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcBytes, Error> {
    		let res = self.active()
    			.and_then(|_| self.dispatch(RpcConfirmationPayload::Decrypt((address.clone(), data).into()), address.into()));

    		let (ready, p) = futures::oneshot();
    		// TODO [todr] typed handle_dispatch
    		self.handle_dispatch(res, |response| {
    			match response {
    				Ok(RpcConfirmationResponse::Decrypt(data)) => ready.complete(Ok(data)),
    				Err(e) => ready.complete(Err(e)),
    				e => ready.complete(Err(errors::internal("Unexpected result.", e))),
    			}
    		});

    		p.then(|result| futures::done(result.expect("Ready is never dropped nor canceled."))).boxed()
    	}
    }

    impl<C: 'static, M: 'static> EthSigning for SigningQueueClient<C, M> where
    	C: MiningBlockChainClient,
    	M: MinerService,
    {
    	type Metadata = Metadata;

    	fn sign(&self, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcH520, Error> {
    		let res = self.active()
    			.and_then(|_| self.dispatch(RpcConfirmationPayload::Signature((address.clone(), data).into()), address.into()));

    		let (ready, p) = futures::oneshot();
    		self.handle_dispatch(res, |response| {
    			match response {
    				Ok(RpcConfirmationResponse::Signature(signature)) => ready.complete(Ok(signature)),
    				Err(e) => ready.complete(Err(e)),
    				e => ready.complete(Err(errors::internal("Unexpected result.", e))),
    			}
    		});

    		p.then(|result| futures::done(result.expect("Ready is never dropped nor canceled."))).boxed()
    	}

    	fn send_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcH256, Error> {
    		let res = self.active()
    			.and_then(|_| self.dispatch(RpcConfirmationPayload::SendTransaction(request), meta.into()));

    		let (ready, p) = futures::oneshot();
    		self.handle_dispatch(res, |response| {
    			match response {
    				Ok(RpcConfirmationResponse::SendTransaction(hash)) => ready.complete(Ok(hash)),
    				Err(e) => ready.complete(Err(e)),
    				e => ready.complete(Err(errors::internal("Unexpected result.", e))),
    			}
    		});

    		p.then(|result| futures::done(result.expect("Ready is never dropped nor canceled."))).boxed()
    	}

    	fn sign_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcRichRawTransaction, Error> {
    		let res = self.active().and_then(|_| self.dispatch(RpcConfirmationPayload::SignTransaction(request), meta.into()));

    		let (ready, p) = futures::oneshot();
    		self.handle_dispatch(res, |response| {
    			match response {
    				Ok(RpcConfirmationResponse::SignTransaction(tx)) => ready.complete(Ok(tx)),
    				Err(e) => ready.complete(Err(e)),
    				e => ready.complete(Err(errors::internal("Unexpected result.", e))),
    			}
    		});

    		p.then(|result| futures::done(result.expect("Ready is never dropped nor canceled."))).boxed()
    	}
    }

# Help

## Keyboard Shortcuts

?
  Show this help dialog
S
  Focus the search field
⇤
  Move up in search results
⇥
  Move down in search results
⏎
  Go to active search result
+
  Collapse/expand all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)