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
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
// This file is part of Substrate.

// Copyright (C) 2018-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

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

// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.

//! A basic version of the dependency graph.
//!
//! For a more full-featured pool, have a look at the `pool` module.

use std::{
	collections::HashSet,
	fmt,
	hash,
	sync::Arc,
};

use log::{trace, debug, warn};
use serde::Serialize;
use sp_core::hexdisplay::HexDisplay;
use sp_runtime::traits::Member;
use sp_runtime::transaction_validity::{
	TransactionTag as Tag,
	TransactionLongevity as Longevity,
	TransactionPriority as Priority,
	TransactionSource as Source,
};
use sp_transaction_pool::{error, PoolStatus, InPoolTransaction};

use crate::future::{FutureTransactions, WaitingTransaction};
use crate::ready::ReadyTransactions;

/// Successful import result.
#[derive(Debug, PartialEq, Eq)]
pub enum Imported<Hash, Ex> {
	/// Transaction was successfully imported to Ready queue.
	Ready {
		/// Hash of transaction that was successfully imported.
		hash: Hash,
		/// Transactions that got promoted from the Future queue.
		promoted: Vec<Hash>,
		/// Transactions that failed to be promoted from the Future queue and are now discarded.
		failed: Vec<Hash>,
		/// Transactions removed from the Ready pool (replaced).
		removed: Vec<Arc<Transaction<Hash, Ex>>>,
	},
	/// Transaction was successfully imported to Future queue.
	Future {
		/// Hash of transaction that was successfully imported.
		hash: Hash,
	}
}

impl<Hash, Ex> Imported<Hash, Ex> {
	/// Returns the hash of imported transaction.
	pub fn hash(&self) -> &Hash {
		use self::Imported::*;
		match *self {
			Ready { ref hash, .. } => hash,
			Future { ref hash, .. } => hash,
		}
	}
}

/// Status of pruning the queue.
#[derive(Debug)]
pub struct PruneStatus<Hash, Ex> {
	/// A list of imports that satisfying the tag triggered.
	pub promoted: Vec<Imported<Hash, Ex>>,
	/// A list of transactions that failed to be promoted and now are discarded.
	pub failed: Vec<Hash>,
	/// A list of transactions that got pruned from the ready queue.
	pub pruned: Vec<Arc<Transaction<Hash, Ex>>>,
}

/// Immutable transaction
#[cfg_attr(test, derive(Clone))]
#[derive(PartialEq, Eq, parity_util_mem::MallocSizeOf)]
pub struct Transaction<Hash, Extrinsic> {
	/// Raw extrinsic representing that transaction.
	pub data: Extrinsic,
	/// Number of bytes encoding of the transaction requires.
	pub bytes: usize,
	/// Transaction hash (unique)
	pub hash: Hash,
	/// Transaction priority (higher = better)
	pub priority: Priority,
	/// At which block the transaction becomes invalid?
	pub valid_till: Longevity,
	/// Tags required by the transaction.
	pub requires: Vec<Tag>,
	/// Tags that this transaction provides.
	pub provides: Vec<Tag>,
	/// Should that transaction be propagated.
	pub propagate: bool,
	/// Source of that transaction.
	pub source: Source,
}

impl<Hash, Extrinsic> AsRef<Extrinsic> for Transaction<Hash, Extrinsic> {
	fn as_ref(&self) -> &Extrinsic {
		&self.data
	}
}

impl<Hash, Extrinsic> InPoolTransaction for Transaction<Hash, Extrinsic> {
	type Transaction = Extrinsic;
	type Hash = Hash;

	fn data(&self) -> &Extrinsic {
		&self.data
	}

	fn hash(&self) -> &Hash {
		&self.hash
	}

	fn priority(&self) -> &Priority {
		&self.priority
	}

	fn longevity(&self) ->&Longevity {
		&self.valid_till
	}

	fn requires(&self) -> &[Tag] {
		&self.requires
	}

	fn provides(&self) -> &[Tag] {
		&self.provides
	}

	fn is_propagable(&self) -> bool {
		self.propagate
	}
}

impl<Hash: Clone, Extrinsic: Clone> Transaction<Hash, Extrinsic> {
	/// Explicit transaction clone.
	///
	/// Transaction should be cloned only if absolutely necessary && we want
	/// every reason to be commented. That's why we `Transaction` is not `Clone`,
	/// but there's explicit `duplicate` method.
	pub fn duplicate(&self) -> Self {
		Transaction {
			data: self.data.clone(),
			bytes: self.bytes.clone(),
			hash: self.hash.clone(),
			priority: self.priority.clone(),
			source: self.source,
			valid_till: self.valid_till.clone(),
			requires: self.requires.clone(),
			provides: self.provides.clone(),
			propagate: self.propagate,
		}
	}
}

impl<Hash, Extrinsic> fmt::Debug for Transaction<Hash, Extrinsic> where
	Hash: fmt::Debug,
	Extrinsic: fmt::Debug,
{
	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
		fn print_tags(fmt: &mut fmt::Formatter, tags: &[Tag]) -> fmt::Result {
			let mut it = tags.iter();
			if let Some(t) = it.next() {
				write!(fmt, "{}", HexDisplay::from(t))?;
			}
			for t in it {
				write!(fmt, ",{}", HexDisplay::from(t))?;
			}
			Ok(())
		}

		write!(fmt, "Transaction {{ ")?;
		write!(fmt, "hash: {:?}, ", &self.hash)?;
		write!(fmt, "priority: {:?}, ", &self.priority)?;
		write!(fmt, "valid_till: {:?}, ", &self.valid_till)?;
		write!(fmt, "bytes: {:?}, ", &self.bytes)?;
		write!(fmt, "propagate: {:?}, ", &self.propagate)?;
		write!(fmt, "source: {:?}, ", &self.source)?;
		write!(fmt, "requires: [")?;
		print_tags(fmt, &self.requires)?;
		write!(fmt, "], provides: [")?;
		print_tags(fmt, &self.provides)?;
		write!(fmt, "], ")?;
		write!(fmt, "data: {:?}", &self.data)?;
		write!(fmt, "}}")?;
		Ok(())
	}
}

/// Store last pruned tags for given number of invocations.
const RECENTLY_PRUNED_TAGS: usize = 2;

/// Transaction pool.
///
/// Builds a dependency graph for all transactions in the pool and returns
/// the ones that are currently ready to be executed.
///
/// General note:
/// If function returns some transactions it usually means that importing them
/// as-is for the second time will fail or produce unwanted results.
/// Most likely it is required to revalidate them and recompute set of
/// required tags.
#[derive(Debug)]
#[cfg_attr(not(target_os = "unknown"), derive(parity_util_mem::MallocSizeOf))]
pub struct BasePool<Hash: hash::Hash + Eq, Ex> {
	reject_future_transactions: bool,
	future: FutureTransactions<Hash, Ex>,
	ready: ReadyTransactions<Hash, Ex>,
	/// Store recently pruned tags (for last two invocations).
	///
	/// This is used to make sure we don't accidentally put
	/// transactions to future in case they were just stuck in verification.
	recently_pruned: [HashSet<Tag>; RECENTLY_PRUNED_TAGS],
	recently_pruned_index: usize,
}

impl<Hash: hash::Hash + Member + Serialize, Ex: std::fmt::Debug> Default for BasePool<Hash, Ex> {
	fn default() -> Self {
		Self::new(false)
	}
}

impl<Hash: hash::Hash + Member + Serialize, Ex: std::fmt::Debug> BasePool<Hash, Ex> {
	/// Create new pool given reject_future_transactions flag.
	pub fn new(reject_future_transactions: bool) -> Self {
		BasePool {
			reject_future_transactions,
			future: Default::default(),
			ready: Default::default(),
			recently_pruned: Default::default(),
			recently_pruned_index: 0,
		}
	}

	/// Temporary enables future transactions, runs closure and then restores
	/// `reject_future_transactions` flag back to previous value.
	///
	/// The closure accepts the mutable reference to the pool and original value
	/// of the `reject_future_transactions` flag.
	pub(crate) fn with_futures_enabled<T>(&mut self, closure: impl FnOnce(&mut Self, bool) -> T) -> T {
		let previous = self.reject_future_transactions;
		self.reject_future_transactions = false;
		let return_value = closure(self, previous);
		self.reject_future_transactions = previous;
		return_value
	}

	/// Returns if the transaction for the given hash is already imported.
	pub fn is_imported(&self, tx_hash: &Hash) -> bool {
		self.future.contains(tx_hash) || self.ready.contains(tx_hash)
	}

	/// Imports transaction to the pool.
	///
	/// The pool consists of two parts: Future and Ready.
	/// The former contains transactions that require some tags that are not yet provided by
	/// other transactions in the pool.
	/// The latter contains transactions that have all the requirements satisfied and are
	/// ready to be included in the block.
	pub fn import(
		&mut self,
		tx: Transaction<Hash, Ex>,
	) -> error::Result<Imported<Hash, Ex>> {
		if self.is_imported(&tx.hash) {
			return Err(error::Error::AlreadyImported(Box::new(tx.hash)))
		}

		let tx = WaitingTransaction::new(
			tx,
			self.ready.provided_tags(),
			&self.recently_pruned,
		);
		trace!(target: "txpool", "[{:?}] {:?}", tx.transaction.hash, tx);
		debug!(
			target: "txpool",
			"[{:?}] Importing to {}",
			tx.transaction.hash,
			if tx.is_ready() { "ready" } else { "future" }
		);

		// If all tags are not satisfied import to future.
		if !tx.is_ready() {
			if self.reject_future_transactions {
				return Err(error::Error::RejectedFutureTransaction);
			}

			let hash = tx.transaction.hash.clone();
			self.future.import(tx);
			return Ok(Imported::Future { hash });
		}

		self.import_to_ready(tx)
	}

	/// Imports transaction to ready queue.
	///
	/// NOTE the transaction has to have all requirements satisfied.
	fn import_to_ready(&mut self, tx: WaitingTransaction<Hash, Ex>) -> error::Result<Imported<Hash, Ex>> {
		let hash = tx.transaction.hash.clone();
		let mut promoted = vec![];
		let mut failed = vec![];
		let mut removed = vec![];

		let mut first = true;
		let mut to_import = vec![tx];

		loop {
			// take first transaction from the list
			let tx = match to_import.pop() {
				Some(tx) => tx,
				None => break,
			};

			// find transactions in Future that it unlocks
			to_import.append(&mut self.future.satisfy_tags(&tx.transaction.provides));

			// import this transaction
			let current_hash = tx.transaction.hash.clone();
			match self.ready.import(tx) {
				Ok(mut replaced) => {
					if !first {
						promoted.push(current_hash);
					}
					// The transactions were removed from the ready pool. We might attempt to re-import them.
					removed.append(&mut replaced);
				},
				// transaction failed to be imported.
				Err(e) => if first {
					debug!(target: "txpool", "[{:?}] Error importing: {:?}", current_hash, e);
					return Err(e)
				} else {
					failed.push(current_hash);
				},
			}
			first = false;
		}

		// An edge case when importing transaction caused
		// some future transactions to be imported and that
		// future transactions pushed out current transaction.
		// This means that there is a cycle and the transactions should
		// be moved back to future, since we can't resolve it.
		if removed.iter().any(|tx| tx.hash == hash) {
			// We still need to remove all transactions that we promoted
			// since they depend on each other and will never get to the best iterator.
			self.ready.remove_subtree(&promoted);

			debug!(target: "txpool", "[{:?}] Cycle detected, bailing.", hash);
			return Err(error::Error::CycleDetected)
		}

		Ok(Imported::Ready {
			hash,
			promoted,
			failed,
			removed,
		})
	}

	/// Returns an iterator over ready transactions in the pool.
	pub fn ready(&self) -> impl Iterator<Item=Arc<Transaction<Hash, Ex>>> {
		self.ready.get()
	}

	/// Returns an iterator over future transactions in the pool.
	pub fn futures(&self) -> impl Iterator<Item=&Transaction<Hash, Ex>> {
		self.future.all()
	}

	/// Returns pool transactions given list of hashes.
	///
	/// Includes both ready and future pool. For every hash in the `hashes`
	/// iterator an `Option` is produced (so the resulting `Vec` always have the same length).
	pub fn by_hashes(&self, hashes: &[Hash]) -> Vec<Option<Arc<Transaction<Hash, Ex>>>> {
		let ready = self.ready.by_hashes(hashes);
		let future = self.future.by_hashes(hashes);

		ready
			.into_iter()
			.zip(future)
			.map(|(a, b)| a.or(b))
			.collect()
	}

	/// Returns pool transaction by hash.
	pub fn ready_by_hash(&self, hash: &Hash) -> Option<Arc<Transaction<Hash, Ex>>> {
		self.ready.by_hash(hash)
	}

	/// Makes sure that the transactions in the queues stay within provided limits.
	///
	/// Removes and returns worst transactions from the queues and all transactions that depend on them.
	/// Technically the worst transaction should be evaluated by computing the entire pending set.
	/// We use a simplified approach to remove the transaction that occupies the pool for the longest time.
	pub fn enforce_limits(&mut self, ready: &Limit, future: &Limit) -> Vec<Arc<Transaction<Hash, Ex>>> {
		let mut removed = vec![];

		while ready.is_exceeded(self.ready.len(), self.ready.bytes()) {
			// find the worst transaction
			let minimal = self.ready
				.fold(|minimal, current| {
					let transaction = &current.transaction;
					match minimal {
						None => Some(transaction.clone()),
						Some(ref tx) if tx.insertion_id > transaction.insertion_id => {
							Some(transaction.clone())
						},
						other => other,
					}
				});

			if let Some(minimal) = minimal {
				removed.append(&mut self.remove_subtree(&[minimal.transaction.hash.clone()]))
			} else {
				break;
			}
		}

		while future.is_exceeded(self.future.len(), self.future.bytes()) {
			// find the worst transaction
			let minimal = self.future
				.fold(|minimal, current| {
					match minimal {
						None => Some(current.clone()),
						Some(ref tx) if tx.imported_at > current.imported_at => {
							Some(current.clone())
						},
						other => other,
					}
				});

			if let Some(minimal) = minimal {
				removed.append(&mut self.remove_subtree(&[minimal.transaction.hash.clone()]))
			} else {
				break;
			}
		}

		removed
	}

	/// Removes all transactions represented by the hashes and all other transactions
	/// that depend on them.
	///
	/// Returns a list of actually removed transactions.
	/// NOTE some transactions might still be valid, but were just removed because
	/// they were part of a chain, you may attempt to re-import them later.
	/// NOTE If you want to remove ready transactions that were already used
	/// and you don't want them to be stored in the pool use `prune_tags` method.
	pub fn remove_subtree(&mut self, hashes: &[Hash]) -> Vec<Arc<Transaction<Hash, Ex>>> {
		let mut removed = self.ready.remove_subtree(hashes);
		removed.extend(self.future.remove(hashes));
		removed
	}

	/// Removes and returns all transactions from the future queue.
	pub fn clear_future(&mut self) -> Vec<Arc<Transaction<Hash, Ex>>> {
		self.future.clear()
	}

	/// Prunes transactions that provide given list of tags.
	///
	/// This will cause all transactions that provide these tags to be removed from the pool,
	/// but unlike `remove_subtree`, dependent transactions are not touched.
	/// Additional transactions from future queue might be promoted to ready if you satisfy tags
	/// that the pool didn't previously know about.
	pub fn prune_tags(&mut self, tags: impl IntoIterator<Item=Tag>) -> PruneStatus<Hash, Ex> {
		let mut to_import = vec![];
		let mut pruned = vec![];
		let recently_pruned = &mut self.recently_pruned[self.recently_pruned_index];
		self.recently_pruned_index = (self.recently_pruned_index + 1) % RECENTLY_PRUNED_TAGS;
		recently_pruned.clear();

		for tag in tags {
			// make sure to promote any future transactions that could be unlocked
			to_import.append(&mut self.future.satisfy_tags(std::iter::once(&tag)));
			// and actually prune transactions in ready queue
			pruned.append(&mut self.ready.prune_tags(tag.clone()));
			// store the tags for next submission
			recently_pruned.insert(tag);
		}

		let mut promoted = vec![];
		let mut failed = vec![];
		for tx in to_import {
			let hash = tx.transaction.hash.clone();
			match self.import_to_ready(tx) {
				Ok(res) => promoted.push(res),
				Err(e) => {
					warn!(target: "txpool", "[{:?}] Failed to promote during pruning: {:?}", hash, e);
					failed.push(hash)
				},
			}
		}

		PruneStatus {
			pruned,
			failed,
			promoted,
		}
	}

	/// Get pool status.
	pub fn status(&self) -> PoolStatus {
		PoolStatus {
			ready: self.ready.len(),
			ready_bytes: self.ready.bytes(),
			future: self.future.len(),
			future_bytes: self.future.bytes(),
		}
	}
}

/// Queue limits
#[derive(Debug, Clone)]
pub struct Limit {
	/// Maximal number of transactions in the queue.
	pub count: usize,
	/// Maximal size of encodings of all transactions in the queue.
	pub total_bytes: usize,
}

impl Limit {
	/// Returns true if any of the provided values exceeds the limit.
	pub fn is_exceeded(&self, count: usize, bytes: usize) -> bool {
		self.count < count || self.total_bytes < bytes
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	type Hash = u64;

	fn pool() -> BasePool<Hash, Vec<u8>> {
		BasePool::default()
	}

	#[test]
	fn should_import_transaction_to_ready() {
		// given
		let mut pool = pool();

		// when
		pool.import(Transaction {
			data: vec![1u8],
			bytes: 1,
			hash: 1u64,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![],
			provides: vec![vec![1]],
			propagate: true,
			source: Source::External,
		}).unwrap();

		// then
		assert_eq!(pool.ready().count(), 1);
		assert_eq!(pool.ready.len(), 1);
	}

	#[test]
	fn should_not_import_same_transaction_twice() {
		// given
		let mut pool = pool();

		// when
		pool.import(Transaction {
			data: vec![1u8],
			bytes: 1,
			hash: 1,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![],
			provides: vec![vec![1]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		pool.import(Transaction {
			data: vec![1u8],
			bytes: 1,
			hash: 1,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![],
			provides: vec![vec![1]],
			propagate: true,
			source: Source::External,
		}).unwrap_err();

		// then
		assert_eq!(pool.ready().count(), 1);
		assert_eq!(pool.ready.len(), 1);
	}


	#[test]
	fn should_import_transaction_to_future_and_promote_it_later() {
		// given
		let mut pool = pool();

		// when
		pool.import(Transaction {
			data: vec![1u8],
			bytes: 1,
			hash: 1,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![0]],
			provides: vec![vec![1]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		assert_eq!(pool.ready().count(), 0);
		assert_eq!(pool.ready.len(), 0);
		pool.import(Transaction {
			data: vec![2u8],
			bytes: 1,
			hash: 2,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![],
			provides: vec![vec![0]],
			propagate: true,
			source: Source::External,
		}).unwrap();

		// then
		assert_eq!(pool.ready().count(), 2);
		assert_eq!(pool.ready.len(), 2);
	}

	#[test]
	fn should_promote_a_subgraph() {
		// given
		let mut pool = pool();

		// when
		pool.import(Transaction {
			data: vec![1u8],
			bytes: 1,
			hash: 1,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![0]],
			provides: vec![vec![1]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		pool.import(Transaction {
			data: vec![3u8],
			bytes: 1,
			hash: 3,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![2]],
			provides: vec![],
			propagate: true,
			source: Source::External,
		}).unwrap();
		pool.import(Transaction {
			data: vec![2u8],
			bytes: 1,
			hash: 2,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![1]],
			provides: vec![vec![3], vec![2]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		pool.import(Transaction {
			data: vec![4u8],
			bytes: 1,
			hash: 4,
			priority: 1_000u64,
			valid_till: 64u64,
			requires: vec![vec![3], vec![4]],
			provides: vec![],
			propagate: true,
			source: Source::External,
		}).unwrap();
		assert_eq!(pool.ready().count(), 0);
		assert_eq!(pool.ready.len(), 0);

		let res = pool.import(Transaction {
			data: vec![5u8],
			bytes: 1,
			hash: 5,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![],
			provides: vec![vec![0], vec![4]],
			propagate: true,
			source: Source::External,
		}).unwrap();

		// then
		let mut it = pool.ready().into_iter().map(|tx| tx.data[0]);

		assert_eq!(it.next(), Some(5));
		assert_eq!(it.next(), Some(1));
		assert_eq!(it.next(), Some(2));
		assert_eq!(it.next(), Some(4));
		assert_eq!(it.next(), Some(3));
		assert_eq!(it.next(), None);
		assert_eq!(res, Imported::Ready {
			hash: 5,
			promoted: vec![1, 2, 3, 4],
			failed: vec![],
			removed: vec![],
		});
	}

	#[test]
	fn should_handle_a_cycle() {
		// given
		let mut pool = pool();
		pool.import(Transaction {
			data: vec![1u8],
			bytes: 1,
			hash: 1,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![0]],
			provides: vec![vec![1]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		pool.import(Transaction {
			data: vec![3u8],
			bytes: 1,
			hash: 3,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![1]],
			provides: vec![vec![2]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		assert_eq!(pool.ready().count(), 0);
		assert_eq!(pool.ready.len(), 0);

		// when
		pool.import(Transaction {
			data: vec![2u8],
			bytes: 1,
			hash: 2,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![2]],
			provides: vec![vec![0]],
			propagate: true,
			source: Source::External,
		}).unwrap();

		// then
		{
			let mut it = pool.ready().into_iter().map(|tx| tx.data[0]);
			assert_eq!(it.next(), None);
		}
		// all transactions occupy the Future queue - it's fine
		assert_eq!(pool.future.len(), 3);

		// let's close the cycle with one additional transaction
		let res = pool.import(Transaction {
			data: vec![4u8],
			bytes: 1,
			hash: 4,
			priority: 50u64,
			valid_till: 64u64,
			requires: vec![],
			provides: vec![vec![0]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		let mut it = pool.ready().into_iter().map(|tx| tx.data[0]);
		assert_eq!(it.next(), Some(4));
		assert_eq!(it.next(), Some(1));
		assert_eq!(it.next(), Some(3));
		assert_eq!(it.next(), None);
		assert_eq!(res, Imported::Ready {
			hash: 4,
			promoted: vec![1, 3],
			failed: vec![2],
			removed: vec![],
		});
		assert_eq!(pool.future.len(), 0);
	}

	#[test]
	fn should_handle_a_cycle_with_low_priority() {
		// given
		let mut pool = pool();
		pool.import(Transaction {
			data: vec![1u8],
			bytes: 1,
			hash: 1,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![0]],
			provides: vec![vec![1]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		pool.import(Transaction {
			data: vec![3u8],
			bytes: 1,
			hash: 3,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![1]],
			provides: vec![vec![2]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		assert_eq!(pool.ready().count(), 0);
		assert_eq!(pool.ready.len(), 0);

		// when
		pool.import(Transaction {
			data: vec![2u8],
			bytes: 1,
			hash: 2,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![2]],
			provides: vec![vec![0]],
			propagate: true,
			source: Source::External,
		}).unwrap();

		// then
		{
			let mut it = pool.ready().into_iter().map(|tx| tx.data[0]);
			assert_eq!(it.next(), None);
		}
		// all transactions occupy the Future queue - it's fine
		assert_eq!(pool.future.len(), 3);

		// let's close the cycle with one additional transaction
		let err = pool.import(Transaction {
			data: vec![4u8],
			bytes: 1,
			hash: 4,
			priority: 1u64, // lower priority than Tx(2)
			valid_till: 64u64,
			requires: vec![],
			provides: vec![vec![0]],
			propagate: true,
			source: Source::External,
		}).unwrap_err();
		let mut it = pool.ready().into_iter().map(|tx| tx.data[0]);
		assert_eq!(it.next(), None);
		assert_eq!(pool.ready.len(), 0);
		assert_eq!(pool.future.len(), 0);
		if let error::Error::CycleDetected = err {
		} else {
			assert!(false, "Invalid error kind: {:?}", err);
		}
	}

	#[test]
	fn can_track_heap_size() {
		let mut pool = pool();
		pool.import(Transaction {
			data: vec![5u8; 1024],
			bytes: 1,
			hash: 5,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![],
			provides: vec![vec![0], vec![4]],
			propagate: true,
			source: Source::External,
		}).expect("import 1 should be ok");
		pool.import(Transaction {
			data: vec![3u8; 1024],
			bytes: 1,
			hash: 7,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![],
			provides: vec![vec![2], vec![7]],
			propagate: true,
			source: Source::External,
		}).expect("import 2 should be ok");

		assert!(parity_util_mem::malloc_size(&pool) > 5000);
	}

	#[test]
	fn should_remove_invalid_transactions() {
		// given
		let mut pool = pool();
		pool.import(Transaction {
			data: vec![5u8],
			bytes: 1,
			hash: 5,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![],
			provides: vec![vec![0], vec![4]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		pool.import(Transaction {
			data: vec![1u8],
			bytes: 1,
			hash: 1,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![0]],
			provides: vec![vec![1]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		pool.import(Transaction {
			data: vec![3u8],
			bytes: 1,
			hash: 3,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![2]],
			provides: vec![],
			propagate: true,
			source: Source::External,
		}).unwrap();
		pool.import(Transaction {
			data: vec![2u8],
			bytes: 1,
			hash: 2,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![1]],
			provides: vec![vec![3], vec![2]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		pool.import(Transaction {
			data: vec![4u8],
			bytes: 1,
			hash: 4,
			priority: 1_000u64,
			valid_till: 64u64,
			requires: vec![vec![3], vec![4]],
			provides: vec![],
			propagate: true,
			source: Source::External,
		}).unwrap();
		// future
		pool.import(Transaction {
			data: vec![6u8],
			bytes: 1,
			hash: 6,
			priority: 1_000u64,
			valid_till: 64u64,
			requires: vec![vec![11]],
			provides: vec![],
			propagate: true,
			source: Source::External,
		}).unwrap();
		assert_eq!(pool.ready().count(), 5);
		assert_eq!(pool.future.len(), 1);

		// when
		pool.remove_subtree(&[6, 1]);

		// then
		assert_eq!(pool.ready().count(), 1);
		assert_eq!(pool.future.len(), 0);
	}

	#[test]
	fn should_prune_ready_transactions() {
		// given
		let mut pool = pool();
		// future (waiting for 0)
		pool.import(Transaction {
			data: vec![5u8],
			bytes: 1,
			hash: 5,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![0]],
			provides: vec![vec![100]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		// ready
		pool.import(Transaction {
			data: vec![1u8],
			bytes: 1,
			hash: 1,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![],
			provides: vec![vec![1]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		pool.import(Transaction {
			data: vec![2u8],
			bytes: 1,
			hash: 2,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![2]],
			provides: vec![vec![3]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		pool.import(Transaction {
			data: vec![3u8],
			bytes: 1,
			hash: 3,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![1]],
			provides: vec![vec![2]],
			propagate: true,
			source: Source::External,
		}).unwrap();
		pool.import(Transaction {
			data: vec![4u8],
			bytes: 1,
			hash: 4,
			priority: 1_000u64,
			valid_till: 64u64,
			requires: vec![vec![3], vec![2]],
			provides: vec![vec![4]],
			propagate: true,
			source: Source::External,
		}).unwrap();

		assert_eq!(pool.ready().count(), 4);
		assert_eq!(pool.future.len(), 1);

		// when
		let result = pool.prune_tags(vec![vec![0], vec![2]]);

		// then
		assert_eq!(result.pruned.len(), 2);
		assert_eq!(result.failed.len(), 0);
		assert_eq!(result.promoted[0], Imported::Ready {
			hash: 5,
			promoted: vec![],
			failed: vec![],
			removed: vec![],
		});
		assert_eq!(result.promoted.len(), 1);
		assert_eq!(pool.future.len(), 0);
		assert_eq!(pool.ready.len(), 3);
		assert_eq!(pool.ready().count(), 3);
	}

	#[test]
	fn transaction_debug() {
		assert_eq!(
			format!("{:?}", Transaction {
				data: vec![4u8],
				bytes: 1,
				hash: 4,
				priority: 1_000u64,
				valid_till: 64u64,
				requires: vec![vec![3], vec![2]],
				provides: vec![vec![4]],
				propagate: true,
				source: Source::External,
			}),
			"Transaction { \
hash: 4, priority: 1000, valid_till: 64, bytes: 1, propagate: true, \
source: TransactionSource::External, requires: [03,02], provides: [04], data: [4]}".to_owned()
		);
	}

	#[test]
	fn transaction_propagation() {
		assert_eq!(Transaction {
				data: vec![4u8],
				bytes: 1,
				hash: 4,
				priority: 1_000u64,
				valid_till: 64u64,
				requires: vec![vec![3], vec![2]],
				provides: vec![vec![4]],
				propagate: true,
				source: Source::External,
		}.is_propagable(), true);

		assert_eq!(Transaction {
				data: vec![4u8],
				bytes: 1,
				hash: 4,
				priority: 1_000u64,
				valid_till: 64u64,
				requires: vec![vec![3], vec![2]],
				provides: vec![vec![4]],
				propagate: false,
				source: Source::External,
		}.is_propagable(), false);
	}

	#[test]
	fn should_reject_future_transactions() {
		// given
		let mut pool = pool();

		// when
		pool.reject_future_transactions = true;

		// then
		let err = pool.import(Transaction {
			data: vec![5u8],
			bytes: 1,
			hash: 5,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![0]],
			provides: vec![],
			propagate: true,
			source: Source::External,
		});

		if let Err(error::Error::RejectedFutureTransaction) = err {
		} else {
			assert!(false, "Invalid error kind: {:?}", err);
		}
	}

	#[test]
	fn should_clear_future_queue() {
		// given
		let mut pool = pool();

		// when
		pool.import(Transaction {
			data: vec![5u8],
			bytes: 1,
			hash: 5,
			priority: 5u64,
			valid_till: 64u64,
			requires: vec![vec![0]],
			provides: vec![],
			propagate: true,
			source: Source::External,
		}).unwrap();

		// then
		assert_eq!(pool.future.len(), 1);

		// and then when
		assert_eq!(pool.clear_future().len(), 1);

		// then
		assert_eq!(pool.future.len(), 0);
	}

	#[test]
	fn should_accept_future_transactions_when_explicitly_asked_to() {
		// given
		let mut pool = pool();
		pool.reject_future_transactions = true;

		// when
		let flag_value = pool.with_futures_enabled(|pool, flag| {
			pool.import(Transaction {
				data: vec![5u8],
				bytes: 1,
				hash: 5,
				priority: 5u64,
				valid_till: 64u64,
				requires: vec![vec![0]],
				provides: vec![],
				propagate: true,
				source: Source::External,
			}).unwrap();

			flag
		});

		// then
		assert_eq!(flag_value, true);
		assert_eq!(pool.reject_future_transactions, true);
		assert_eq!(pool.future.len(), 1);
	}
}