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
// Copyright 2015-2018 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/>.

//! Local Transactions List.

use std::sync::Arc;

use ethereum_types::H256;
use linked_hash_map::LinkedHashMap;
use pool::VerifiedTransaction as Transaction;
use txpool::{self, VerifiedTransaction};

/// Status of local transaction.
/// Can indicate that the transaction is currently part of the queue (`Pending/Future`)
/// or gives a reason why the transaction was removed.
#[derive(Debug, PartialEq, Clone)]
pub enum Status {
	/// The transaction is currently in the transaction queue.
	Pending(Arc<Transaction>),
	/// Transaction is already mined.
	Mined(Arc<Transaction>),
	/// Transaction is dropped because of limit
	Dropped(Arc<Transaction>),
	/// Replaced because of higher gas price of another transaction.
	Replaced {
		/// Replaced transaction
		old: Arc<Transaction>,
		/// Transaction that replaced this one.
		new: Arc<Transaction>,
	},
	/// Transaction was never accepted to the queue.
	/// It means that it was too cheap to replace any transaction already in the pool.
	Rejected(Arc<Transaction>, String),
	/// Transaction is invalid.
	Invalid(Arc<Transaction>),
	/// Transaction was canceled.
	Canceled(Arc<Transaction>),
}

impl Status {
	fn is_pending(&self) -> bool {
		match *self {
			Status::Pending(_) => true,
			_ => false,
		}
	}
}

/// Keeps track of local transactions that are in the queue or were mined/dropped recently.
#[derive(Debug)]
pub struct LocalTransactionsList {
	max_old: usize,
	transactions: LinkedHashMap<H256, Status>,
	pending: usize,
}

impl Default for LocalTransactionsList {
	fn default() -> Self {
		Self::new(10)
	}
}

impl LocalTransactionsList {
	/// Create a new list of local transactions.
	pub fn new(max_old: usize) -> Self {
		LocalTransactionsList {
			max_old,
			transactions: Default::default(),
			pending: 0,
		}
	}

	/// Returns true if the transaction is already in local transactions.
	pub fn contains(&self, hash: &H256) -> bool {
		self.transactions.contains_key(hash)
	}

	/// Return a map of all currently stored transactions.
	pub fn all_transactions(&self) -> &LinkedHashMap<H256, Status> {
		&self.transactions
	}

	/// Returns true if there are pending local transactions.
	pub fn has_pending(&self) -> bool {
		self.pending > 0
	}

	fn clear_old(&mut self) {
		let number_of_old = self.transactions.len() - self.pending;
		if self.max_old >= number_of_old {
			return;
		}

		let to_remove: Vec<_> = self.transactions
			.iter()
			.filter(|&(_, status)| !status.is_pending())
			.map(|(hash, _)| *hash)
			.take(number_of_old - self.max_old)
			.collect();

		for hash in to_remove {
			self.transactions.remove(&hash);
		}
	}

	fn insert(&mut self, hash: H256, status: Status) {
		let result = self.transactions.insert(hash, status);
		if let Some(old) = result {
			if old.is_pending() {
				self.pending -= 1;
			}
		}
	}
}

impl txpool::Listener<Transaction> for LocalTransactionsList {
	fn added(&mut self, tx: &Arc<Transaction>, old: Option<&Arc<Transaction>>) {
		if !tx.priority().is_local() {
			return;
		}

		debug!(target: "own_tx", "Imported to the pool (hash {:?})", tx.hash());
		self.clear_old();
		self.insert(*tx.hash(), Status::Pending(tx.clone()));
		self.pending += 1;

		if let Some(old) = old {
			if self.transactions.contains_key(old.hash()) {
				self.insert(*old.hash(), Status::Replaced {
					old: old.clone(),
					new: tx.clone(),
				});
			}
		}
	}

	fn rejected(&mut self, tx: &Arc<Transaction>, reason: &txpool::ErrorKind) {
		if !tx.priority().is_local() {
			return;
		}

		debug!(target: "own_tx", "Transaction rejected (hash {:?}). {}", tx.hash(), reason);
		self.insert(*tx.hash(), Status::Rejected(tx.clone(), format!("{}", reason)));
		self.clear_old();
	}

	fn dropped(&mut self, tx: &Arc<Transaction>, new: Option<&Transaction>) {
		if !tx.priority().is_local() {
			return;
		}

		match new {
			Some(new) => warn!(target: "own_tx", "Transaction pushed out because of limit (hash {:?}, replacement: {:?})", tx.hash(), new.hash()),
			None => warn!(target: "own_tx", "Transaction dropped because of limit (hash: {:?})", tx.hash()),
		}
		self.insert(*tx.hash(), Status::Dropped(tx.clone()));
		self.clear_old();
	}

	fn invalid(&mut self, tx: &Arc<Transaction>) {
		if !tx.priority().is_local() {
			return;
		}

		warn!(target: "own_tx", "Transaction marked invalid (hash {:?})", tx.hash());
		self.insert(*tx.hash(), Status::Invalid(tx.clone()));
		self.clear_old();
	}

	fn canceled(&mut self, tx: &Arc<Transaction>) {
		if !tx.priority().is_local() {
			return;
		}

		warn!(target: "own_tx", "Transaction canceled (hash {:?})", tx.hash());
		self.insert(*tx.hash(), Status::Canceled(tx.clone()));
		self.clear_old();
	}

	/// The transaction has been mined.
	fn mined(&mut self, tx: &Arc<Transaction>) {
		if !tx.priority().is_local() {
			return;
		}

		info!(target: "own_tx", "Transaction mined (hash {:?})", tx.hash());
		self.insert(*tx.hash(), Status::Mined(tx.clone()));
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use ethereum_types::U256;
	use ethkey::{Random, Generator};
	use transaction;
	use txpool::Listener;

	use pool;

	#[test]
	fn should_add_transaction_as_pending() {
		// given
		let mut list = LocalTransactionsList::default();
		let tx1 = new_tx(10);
		let tx2 = new_tx(20);

		// when
		list.added(&tx1, None);
		list.added(&tx2, None);

		// then
		assert!(list.contains(tx1.hash()));
		assert!(list.contains(tx2.hash()));
		let statuses = list.all_transactions().values().cloned().collect::<Vec<Status>>();
		assert_eq!(statuses, vec![Status::Pending(tx1), Status::Pending(tx2)]);
	}

	#[test]
	fn should_clear_old_transactions() {
		// given
		let mut list = LocalTransactionsList::new(1);
		let tx1 = new_tx(10);
		let tx2 = new_tx(50);
		let tx3 = new_tx(51);

		list.added(&tx1, None);
		list.invalid(&tx1);
		list.dropped(&tx2, None);
		assert!(!list.contains(tx1.hash()));
		assert!(list.contains(tx2.hash()));
		assert!(!list.contains(tx3.hash()));

		// when
		list.added(&tx3, Some(&tx1));

		// then
		assert!(!list.contains(tx1.hash()));
		assert!(list.contains(tx2.hash()));
		assert!(list.contains(tx3.hash()));
	}

	fn new_tx<T: Into<U256>>(nonce: T) -> Arc<Transaction> {
		let keypair = Random.generate().unwrap();
		let signed = transaction::Transaction {
			action: transaction::Action::Create,
			value: U256::from(100),
			data: Default::default(),
			gas: U256::from(10),
			gas_price: U256::from(1245),
			nonce: nonce.into(),
		}.sign(keypair.secret(), None);

		let mut tx = Transaction::from_pending_block_transaction(signed);
		tx.priority = pool::Priority::Local;

		Arc::new(tx)
	}
}