      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
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425

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

    use std::mem;
    use std::cell::RefCell;
    use std::sync::{mpsc, Arc};
    use std::collections::BTreeMap;
    use jsonrpc_core;
    use util::{Mutex, RwLock, U256, Address};
    use ethcore::account_provider::DappId;
    use v1::helpers::{ConfirmationRequest, ConfirmationPayload};
    use v1::metadata::Metadata;
    use v1::types::{ConfirmationResponse, H160 as RpcH160};

    /// Result that can be returned from JSON RPC.
    pub type RpcResult = Result<ConfirmationResponse, jsonrpc_core::Error>;

    /// Type of default account
    pub enum DefaultAccount {
    	/// Default account is known
    	Provided(Address),
    	/// Should use default account for dapp
    	ForDapp(DappId),
    }

    impl From<Metadata> for DefaultAccount {
    	fn from(meta: Metadata) -> Self {
    		DefaultAccount::ForDapp(meta.dapp_id.unwrap_or_default().into())
    	}
    }

    impl From<RpcH160> for DefaultAccount {
    	fn from(address: RpcH160) -> Self {
    		DefaultAccount::Provided(address.into())
    	}
    }

    /// Possible events happening in the queue that can be listened to.
    #[derive(Debug, PartialEq)]
    pub enum QueueEvent {
    	/// Receiver should stop work upon receiving `Finish` message.
    	Finish,
    	/// Informs about new request.
    	NewRequest(U256),
    	/// Request rejected.
    	RequestRejected(U256),
    	/// Request resolved.
    	RequestConfirmed(U256),
    }

    /// Defines possible errors returned from queue receiving method.
    #[derive(Debug, PartialEq)]
    pub enum QueueError {
    	/// Returned when method has been already used (no receiver available).
    	AlreadyUsed,
    	/// Returned when receiver encounters an error.
    	ReceiverError(mpsc::RecvError),
    }

    /// Defines possible errors when inserting to queue
    #[derive(Debug, PartialEq)]
    pub enum QueueAddError {
    	LimitReached,
    }

    // TODO [todr] to consider: timeout instead of limit?
    const QUEUE_LIMIT: usize = 50;

    /// A queue of transactions awaiting to be confirmed and signed.
    pub trait SigningQueue: Send + Sync {
    	/// Add new request to the queue.
    	/// Returns a `ConfirmationPromise` that can be used to await for resolution of given request.
    	fn add_request(&self, request: ConfirmationPayload) -> Result<ConfirmationPromise, QueueAddError>;

    	/// Removes a request from the queue.
    	/// Notifies possible token holders that request was rejected.
    	fn request_rejected(&self, id: U256) -> Option<ConfirmationRequest>;

    	/// Removes a request from the queue.
    	/// Notifies possible token holders that request was confirmed and given hash was assigned.
    	fn request_confirmed(&self, id: U256, result: RpcResult) -> Option<ConfirmationRequest>;

    	/// Returns a request if it is contained in the queue.
    	fn peek(&self, id: &U256) -> Option<ConfirmationRequest>;

    	/// Return copy of all the requests in the queue.
    	fn requests(&self) -> Vec<ConfirmationRequest>;

    	/// Returns number of requests awaiting confirmation.
    	fn len(&self) -> usize;

    	/// Returns true if there are no requests awaiting confirmation.
    	fn is_empty(&self) -> bool;
    }

    #[derive(Debug, Clone, PartialEq)]
    /// Result of a pending confirmation request.
    pub enum ConfirmationResult {
    	/// The request has not yet been confirmed nor rejected.
    	Waiting,
    	/// The request has been rejected.
    	Rejected,
    	/// The request has been confirmed.
    	Confirmed(RpcResult),
    }

    type Listener = Box<FnMut(Option<RpcResult>) + Send>;

    /// A handle to submitted request.
    /// Allows to block and wait for a resolution of that request.
    pub struct ConfirmationToken {
    	result: Arc<Mutex<ConfirmationResult>>,
    	listeners: Arc<Mutex<Vec<Listener>>>,
    	request: ConfirmationRequest,
    }

    pub struct ConfirmationPromise {
    	id: U256,
    	result: Arc<Mutex<ConfirmationResult>>,
    	listeners: Arc<Mutex<Vec<Listener>>>,
    }

    impl ConfirmationToken {
    	/// Submit solution to all listeners
    	fn resolve(&self, result: Option<RpcResult>) {
    		let wrapped = result.clone().map_or(ConfirmationResult::Rejected, |h| ConfirmationResult::Confirmed(h));
    		{
    			let mut res = self.result.lock();
    			*res = wrapped.clone();
    		}
    		// Notify listener
    		let listeners = {
    			let mut listeners = self.listeners.lock();
    			mem::replace(&mut *listeners, Vec::new())
    		};
    		for mut listener in listeners {
    			listener(result.clone());
    		}
    	}

    	fn as_promise(&self) -> ConfirmationPromise {
    		ConfirmationPromise {
    			id: self.request.id,
    			result: self.result.clone(),
    			listeners: self.listeners.clone(),
    		}
    	}
    }

    impl ConfirmationPromise {
    	/// Get the ID for this request.
    	pub fn id(&self) -> U256 { self.id }

    	/// Just get the result, assuming it exists.
    	pub fn result(&self) -> ConfirmationResult {
    		self.result.lock().clone()
    	}

    	pub fn wait_for_result<F>(self, callback: F) where F: FnOnce(Option<RpcResult>) + Send + 'static {
    		trace!(target: "own_tx", "Signer: Awaiting confirmation... ({:?}).", self.id);
    		let _result = self.result.lock();
    		let mut listeners = self.listeners.lock();
    		// TODO [todr] Overcoming FnBox unstability
    		let callback = RefCell::new(Some(callback));
    		listeners.push(Box::new(move |result| {
    			let ref mut f = *callback.borrow_mut();
    			f.take().expect("Callbacks are called only once.")(result)
    		}));
    	}
    }

    /// Queue for all unconfirmed requests.
    pub struct ConfirmationsQueue {
    	id: Mutex<U256>,
    	queue: RwLock<BTreeMap<U256, ConfirmationToken>>,
    	sender: Mutex<mpsc::Sender<QueueEvent>>,
    	receiver: Mutex<Option<mpsc::Receiver<QueueEvent>>>,
    }

    impl Default for ConfirmationsQueue {
    	fn default() -> Self {
    		let (send, recv) = mpsc::channel();

    		ConfirmationsQueue {
    			id: Mutex::new(U256::from(0)),
    			queue: RwLock::new(BTreeMap::new()),
    			sender: Mutex::new(send),
    			receiver: Mutex::new(Some(recv)),
    		}
    	}
    }

    impl ConfirmationsQueue {

    	/// Blocks the thread and starts listening for notifications regarding all actions in the queue.
    	/// For each event, `listener` callback will be invoked.
    	/// This method can be used only once (only single consumer of events can exist).
    	pub fn start_listening<F>(&self, listener: F) -> Result<(), QueueError>
    		where F: Fn(QueueEvent) -> () {
    		let recv = self.receiver.lock().take();
    		if let None = recv {
    			return Err(QueueError::AlreadyUsed);
    		}
    		let recv = recv.expect("Check for none is done earlier.");

    		loop {
    			let message = recv.recv().map_err(|e| QueueError::ReceiverError(e))?;
    			if let QueueEvent::Finish = message {
    				return Ok(());
    			}

    			listener(message);
    		}
    	}

    	/// Notifies consumer that the communcation is over.
    	/// No more events will be sent after this function is invoked.
    	pub fn finish(&self) {
    		self.notify(QueueEvent::Finish);
    	}

    	/// Notifies receiver about the event happening in this queue.
    	fn notify(&self, message: QueueEvent) {
    		// We don't really care about the result
    		let _ = self.sender.lock().send(message);
    	}

    	/// Removes requests from this queue and notifies `ConfirmationPromise` holders about the result.
    	/// Notifies also a receiver about that event.
    	fn remove(&self, id: U256, result: Option<RpcResult>) -> Option<ConfirmationRequest> {
    		let token = self.queue.write().remove(&id);

    		if let Some(token) = token {
    			// notify receiver about the event
    			self.notify(result.clone().map_or_else(
    				|| QueueEvent::RequestRejected(id),
    				|_| QueueEvent::RequestConfirmed(id)
    			));
    			// notify token holders about resolution
    			token.resolve(result);
    			// return a result
    			return Some(token.request.clone());
    		}
    		None
    	}
    }

    impl Drop for ConfirmationsQueue {
    	fn drop(&mut self) {
    		self.finish();
    	}
    }

    impl SigningQueue for ConfirmationsQueue {
    	fn add_request(&self, request: ConfirmationPayload) -> Result<ConfirmationPromise, QueueAddError> {
    		if self.len() > QUEUE_LIMIT {
    			return Err(QueueAddError::LimitReached);
    		}

    		// Increment id
    		let id = {
    			let mut last_id = self.id.lock();
    			*last_id = *last_id + U256::from(1);
    			*last_id
    		};
    		// Add request to queue
    		let res = {
    			debug!(target: "own_tx", "Signer: New entry ({:?}) in confirmation queue.", id);
    			trace!(target: "own_tx", "Signer: ({:?}) : {:?}", id, request);

    			let mut queue = self.queue.write();
    			queue.insert(id, ConfirmationToken {
    				result: Arc::new(Mutex::new(ConfirmationResult::Waiting)),
    				listeners: Default::default(),
    				request: ConfirmationRequest {
    					id: id,
    					payload: request,
    				},
    			});
    			queue.get(&id).map(|token| token.as_promise()).expect("Token was just inserted.")
    		};
    		// Notify listeners
    		self.notify(QueueEvent::NewRequest(id));
    		Ok(res)
    	}

    	fn peek(&self, id: &U256) -> Option<ConfirmationRequest> {
    		self.queue.read().get(id).map(|token| token.request.clone())
    	}

    	fn request_rejected(&self, id: U256) -> Option<ConfirmationRequest> {
    		debug!(target: "own_tx", "Signer: Request rejected ({:?}).", id);
    		self.remove(id, None)
    	}

    	fn request_confirmed(&self, id: U256, result: RpcResult) -> Option<ConfirmationRequest> {
    		debug!(target: "own_tx", "Signer: Transaction confirmed ({:?}).", id);
    		self.remove(id, Some(result))
    	}

    	fn requests(&self) -> Vec<ConfirmationRequest> {
    		let queue = self.queue.read();
    		queue.values().map(|token| token.request.clone()).collect()
    	}

    	fn len(&self) -> usize {
    		let queue = self.queue.read();
    		queue.len()
    	}

    	fn is_empty(&self) -> bool {
    		let queue = self.queue.read();
    		queue.is_empty()
    	}
    }

    #[cfg(test)]
    mod test {
    	use std::time::Duration;
    	use std::thread;
    	use std::sync::{mpsc, Arc};
    	use util::{Address, U256, Mutex};
    	use v1::helpers::{SigningQueue, ConfirmationsQueue, QueueEvent, FilledTransactionRequest, ConfirmationPayload};
    	use v1::types::ConfirmationResponse;

    	fn request() -> ConfirmationPayload {
    		ConfirmationPayload::SendTransaction(FilledTransactionRequest {
    			from: Address::from(1),
    			used_default_from: false,
    			to: Some(Address::from(2)),
    			gas_price: 0.into(),
    			gas: 10_000.into(),
    			value: 10_000_000.into(),
    			data: vec![],
    			nonce: None,
    			min_block: None,
    		})
    	}

    	#[test]
    	fn should_wait_for_hash() {
    		// given
    		let queue = Arc::new(ConfirmationsQueue::default());
    		let request = request();

    		// when
    		let q = queue.clone();
    		let handle = thread::spawn(move || {
    			let v = q.add_request(request).unwrap();
    			let (tx, rx) = mpsc::channel();
    			v.wait_for_result(move |res| {
    				tx.send(res).unwrap();
    			});
    			rx.recv().unwrap().expect("Should return hash")
    		});

    		let id = U256::from(1);
    		while queue.peek(&id).is_none() {
    			// Just wait for the other thread to start
    			thread::sleep(Duration::from_millis(100));
    		}
    		queue.request_confirmed(id, Ok(ConfirmationResponse::SendTransaction(1.into())));

    		// then
    		assert_eq!(handle.join().expect("Thread should finish nicely"), Ok(ConfirmationResponse::SendTransaction(1.into())));
    	}

    	#[test]
    	fn should_receive_notification() {
    		// given
    		let received = Arc::new(Mutex::new(None));
    		let queue = Arc::new(ConfirmationsQueue::default());
    		let request = request();

    		// when
    		let q = queue.clone();
    		let r = received.clone();
    		let handle = thread::spawn(move || {
    			q.start_listening(move |notification| {
    				let mut v = r.lock();
    				*v = Some(notification);
    			}).expect("Should be closed nicely.")
    		});
    		queue.add_request(request).unwrap();
    		queue.finish();

    		// then
    		handle.join().expect("Thread should finish nicely");
    		let r = received.lock().take();
    		assert_eq!(r, Some(QueueEvent::NewRequest(U256::from(1))));
    	}

    	#[test]
    	fn should_add_transactions() {
    		// given
    		let queue = ConfirmationsQueue::default();
    		let request = request();

    		// when
    		queue.add_request(request.clone()).unwrap();
    		let all = queue.requests();

    		// then
    		assert_eq!(all.len(), 1);
    		let el = all.get(0).unwrap();
    		assert_eq!(el.id, U256::from(1));
    		assert_eq!(el.payload, request);
    	}
    }

# 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`)