referrerpolicy=no-referrer-when-downgrade

sc_transaction_pool/single_state_txpool/
single_state_txpool.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! Substrate transaction pool implementation.
20
21use super::{metrics::MetricsLink as PrometheusMetrics, revalidation};
22pub use crate::{
23	api::FullChainApi,
24	graph::{ChainApi, ValidatedTransaction},
25};
26use crate::{
27	common::{
28		enactment_state::{EnactmentAction, EnactmentState},
29		error,
30		tracing_log_xt::log_xt_trace,
31	},
32	graph::{
33		self, base_pool::TimedTransactionSource, EventHandler, ExtrinsicHash, IsValidator,
34		RawExtrinsicFor,
35	},
36	ReadyIteratorFor, ValidateTransactionPriority, LOG_TARGET,
37};
38use async_trait::async_trait;
39use futures::{channel::oneshot, future, prelude::*, Future, FutureExt};
40use parking_lot::Mutex;
41use prometheus_endpoint::Registry as PrometheusRegistry;
42use sc_transaction_pool_api::{
43	error::Error as TxPoolError, ChainEvent, ImportNotificationStream, MaintainedTransactionPool,
44	PoolStatus, TransactionFor, TransactionPool, TransactionSource, TransactionStatusStreamFor,
45	TxHash, TxInvalidityReportMap,
46};
47use sp_blockchain::{HashAndNumber, TreeRoute};
48use sp_core::traits::SpawnEssentialNamed;
49use sp_runtime::{
50	generic::BlockId,
51	traits::{
52		AtLeast32Bit, Block as BlockT, Header as HeaderT, NumberFor, SaturatedConversion, Zero,
53	},
54	transaction_validity::{TransactionTag as Tag, TransactionValidityError},
55};
56use std::{
57	collections::{HashMap, HashSet},
58	pin::Pin,
59	sync::Arc,
60	time::Instant,
61};
62use tokio::select;
63use tracing::{trace, warn};
64
65/// Basic implementation of transaction pool that can be customized by providing PoolApi.
66pub struct BasicPool<PoolApi, Block>
67where
68	Block: BlockT,
69	PoolApi: graph::ChainApi<Block = Block>,
70{
71	pool: Arc<graph::Pool<PoolApi, ()>>,
72	api: Arc<PoolApi>,
73	revalidation_strategy: Arc<Mutex<RevalidationStrategy<NumberFor<Block>>>>,
74	revalidation_queue: Arc<revalidation::RevalidationQueue<PoolApi>>,
75	ready_poll: Arc<Mutex<ReadyPoll<ReadyIteratorFor<PoolApi>, Block>>>,
76	metrics: PrometheusMetrics,
77	enactment_state: Arc<Mutex<EnactmentState<Block>>>,
78}
79
80struct ReadyPoll<T, Block: BlockT> {
81	updated_at: NumberFor<Block>,
82	pollers: Vec<(NumberFor<Block>, oneshot::Sender<T>)>,
83}
84
85impl<T, Block: BlockT> Default for ReadyPoll<T, Block> {
86	fn default() -> Self {
87		Self { updated_at: NumberFor::<Block>::zero(), pollers: Default::default() }
88	}
89}
90
91impl<T, Block: BlockT> ReadyPoll<T, Block> {
92	fn new(best_block_number: NumberFor<Block>) -> Self {
93		Self { updated_at: best_block_number, pollers: Default::default() }
94	}
95
96	fn trigger(&mut self, number: NumberFor<Block>, iterator_factory: impl Fn() -> T) {
97		self.updated_at = number;
98
99		let mut idx = 0;
100		while idx < self.pollers.len() {
101			if self.pollers[idx].0 <= number {
102				let poller_sender = self.pollers.swap_remove(idx);
103				trace!(
104					target: LOG_TARGET,
105					?number,
106					"Sending ready signal."
107				);
108				let _ = poller_sender.1.send(iterator_factory());
109			} else {
110				idx += 1;
111			}
112		}
113	}
114
115	fn add(&mut self, number: NumberFor<Block>) -> oneshot::Receiver<T> {
116		let (sender, receiver) = oneshot::channel();
117		self.pollers.push((number, sender));
118		receiver
119	}
120
121	fn updated_at(&self) -> NumberFor<Block> {
122		self.updated_at
123	}
124}
125
126/// Type of revalidation.
127pub enum RevalidationType {
128	/// Light revalidation type.
129	///
130	/// During maintenance, transaction pool makes periodic revalidation
131	/// of all transactions depending on number of blocks or time passed.
132	/// Also this kind of revalidation does not resubmit transactions from
133	/// retracted blocks, since it is too expensive.
134	Light,
135
136	/// Full revalidation type.
137	///
138	/// During maintenance, transaction pool revalidates some fixed amount of
139	/// transactions from the pool of valid transactions.
140	Full,
141}
142
143impl<PoolApi, Block> BasicPool<PoolApi, Block>
144where
145	Block: BlockT,
146	PoolApi: graph::ChainApi<Block = Block> + 'static,
147{
148	/// Create new basic transaction pool with provided api, for tests.
149	pub fn new_test(
150		pool_api: Arc<PoolApi>,
151		best_block_hash: Block::Hash,
152		finalized_hash: Block::Hash,
153		options: graph::Options,
154	) -> (Self, Pin<Box<dyn Future<Output = ()> + Send>>) {
155		let pool = Arc::new(graph::Pool::new_with_staticly_sized_rotator(
156			options,
157			true.into(),
158			pool_api.clone(),
159		));
160		let (revalidation_queue, background_task) = revalidation::RevalidationQueue::new_background(
161			pool_api.clone(),
162			pool.clone(),
163			finalized_hash,
164		);
165		(
166			Self {
167				api: pool_api,
168				pool,
169				revalidation_queue: Arc::new(revalidation_queue),
170				revalidation_strategy: Arc::new(Mutex::new(RevalidationStrategy::Always)),
171				ready_poll: Default::default(),
172				metrics: Default::default(),
173				enactment_state: Arc::new(Mutex::new(EnactmentState::new(
174					best_block_hash,
175					finalized_hash,
176				))),
177			},
178			background_task,
179		)
180	}
181
182	/// Create new basic transaction pool with provided api and custom
183	/// revalidation type.
184	pub fn with_revalidation_type(
185		options: graph::Options,
186		is_validator: IsValidator,
187		pool_api: Arc<PoolApi>,
188		prometheus: Option<&PrometheusRegistry>,
189		revalidation_type: RevalidationType,
190		spawner: impl SpawnEssentialNamed,
191		best_block_number: NumberFor<Block>,
192		best_block_hash: Block::Hash,
193		finalized_hash: Block::Hash,
194	) -> Self {
195		let pool = Arc::new(graph::Pool::new_with_staticly_sized_rotator(
196			options,
197			is_validator,
198			pool_api.clone(),
199		));
200		let (revalidation_queue, background_task) = match revalidation_type {
201			RevalidationType::Light => {
202				(revalidation::RevalidationQueue::new(pool_api.clone(), pool.clone()), None)
203			},
204			RevalidationType::Full => {
205				let (queue, background) = revalidation::RevalidationQueue::new_background(
206					pool_api.clone(),
207					pool.clone(),
208					finalized_hash,
209				);
210				(queue, Some(background))
211			},
212		};
213
214		if let Some(background_task) = background_task {
215			spawner.spawn_essential("txpool-background", Some("transaction-pool"), background_task);
216		}
217
218		Self {
219			api: pool_api,
220			pool,
221			revalidation_queue: Arc::new(revalidation_queue),
222			revalidation_strategy: Arc::new(Mutex::new(match revalidation_type {
223				RevalidationType::Light => {
224					RevalidationStrategy::Light(RevalidationStatus::NotScheduled)
225				},
226				RevalidationType::Full => RevalidationStrategy::Always,
227			})),
228			ready_poll: Arc::new(Mutex::new(ReadyPoll::new(best_block_number))),
229			metrics: PrometheusMetrics::new(prometheus),
230			enactment_state: Arc::new(Mutex::new(EnactmentState::new(
231				best_block_hash,
232				finalized_hash,
233			))),
234		}
235	}
236
237	/// Gets shared reference to the underlying pool.
238	pub fn pool(&self) -> &Arc<graph::Pool<PoolApi, ()>> {
239		&self.pool
240	}
241
242	/// Get access to the underlying api
243	pub fn api(&self) -> &PoolApi {
244		&self.api
245	}
246
247	async fn ready_at_with_timeout_internal(
248		&self,
249		at: Block::Hash,
250		timeout: std::time::Duration,
251	) -> ReadyIteratorFor<PoolApi> {
252		select! {
253			ready = self.ready_at(at)=> ready,
254			_ = futures_timer::Delay::new(timeout)=> self.ready()
255		}
256	}
257}
258
259#[async_trait]
260impl<PoolApi, Block> TransactionPool for BasicPool<PoolApi, Block>
261where
262	Block: BlockT,
263	PoolApi: 'static + graph::ChainApi<Block = Block>,
264{
265	type Block = PoolApi::Block;
266	type Hash = graph::ExtrinsicHash<PoolApi>;
267	type InPoolTransaction =
268		graph::base_pool::Transaction<graph::ExtrinsicHash<PoolApi>, graph::ExtrinsicFor<PoolApi>>;
269	type Error = PoolApi::Error;
270
271	async fn submit_at(
272		&self,
273		at: <Self::Block as BlockT>::Hash,
274		source: TransactionSource,
275		xts: Vec<TransactionFor<Self>>,
276	) -> Result<Vec<Result<TxHash<Self>, Self::Error>>, Self::Error> {
277		let pool = self.pool.clone();
278		let xts = xts
279			.into_iter()
280			.map(|xt| {
281				(TimedTransactionSource::from_transaction_source(source, false), Arc::from(xt))
282			})
283			.collect::<Vec<_>>();
284
285		self.metrics
286			.report(|metrics| metrics.submitted_transactions.inc_by(xts.len() as u64));
287
288		let number = self.api.resolve_block_number(at);
289		let at = HashAndNumber { hash: at, number: number? };
290		Ok(pool
291			.submit_at(&at, xts, ValidateTransactionPriority::Submitted)
292			.await
293			.into_iter()
294			.map(|result| result.map(|outcome| outcome.hash()))
295			.collect())
296	}
297
298	async fn submit_one(
299		&self,
300		at: <Self::Block as BlockT>::Hash,
301		source: TransactionSource,
302		xt: TransactionFor<Self>,
303	) -> Result<TxHash<Self>, Self::Error> {
304		let pool = self.pool.clone();
305		let xt = Arc::from(xt);
306
307		self.metrics.report(|metrics| metrics.submitted_transactions.inc());
308
309		let number = self.api.resolve_block_number(at);
310		let at = HashAndNumber { hash: at, number: number? };
311		pool.submit_one(&at, TimedTransactionSource::from_transaction_source(source, false), xt)
312			.await
313			.map(|outcome| outcome.hash())
314	}
315
316	async fn submit_and_watch(
317		&self,
318		at: <Self::Block as BlockT>::Hash,
319		source: TransactionSource,
320		xt: TransactionFor<Self>,
321	) -> Result<Pin<Box<TransactionStatusStreamFor<Self>>>, Self::Error> {
322		let pool = self.pool.clone();
323		let xt = Arc::from(xt);
324
325		self.metrics.report(|metrics| metrics.submitted_transactions.inc());
326
327		let number = self.api.resolve_block_number(at);
328
329		let at = HashAndNumber { hash: at, number: number? };
330		pool.submit_and_watch(
331			&at,
332			TimedTransactionSource::from_transaction_source(source, false),
333			xt,
334		)
335		.await
336		.map(|mut outcome| outcome.expect_watcher().into_stream().boxed())
337	}
338
339	async fn report_invalid(
340		&self,
341		_at: Option<<Self::Block as BlockT>::Hash>,
342		invalid_tx_errors: TxInvalidityReportMap<TxHash<Self>>,
343	) -> Vec<Arc<Self::InPoolTransaction>> {
344		let hashes = invalid_tx_errors.keys().map(|h| *h).collect::<Vec<_>>();
345		let removed = self.pool.validated_pool().remove_invalid(&hashes);
346		self.metrics
347			.report(|metrics| metrics.validations_invalid.inc_by(removed.len() as u64));
348		removed
349	}
350
351	fn status(&self) -> PoolStatus {
352		self.pool.validated_pool().status()
353	}
354
355	fn import_notification_stream(&self) -> ImportNotificationStream<TxHash<Self>> {
356		self.pool.validated_pool().import_notification_stream()
357	}
358
359	fn hash_of(&self, xt: &TransactionFor<Self>) -> TxHash<Self> {
360		self.pool.hash_of(xt)
361	}
362
363	fn on_broadcasted(&self, propagations: HashMap<TxHash<Self>, Vec<String>>) {
364		self.pool.validated_pool().on_broadcasted(propagations)
365	}
366
367	fn ready_transaction(&self, hash: &TxHash<Self>) -> Option<Arc<Self::InPoolTransaction>> {
368		self.pool.validated_pool().ready_by_hash(hash)
369	}
370
371	async fn ready_at(&self, at: <Self::Block as BlockT>::Hash) -> ReadyIteratorFor<PoolApi> {
372		let Ok(at) = self.api.resolve_block_number(at) else {
373			return Box::new(std::iter::empty()) as Box<_>;
374		};
375
376		let status = self.status();
377		// If there are no transactions in the pool, it is fine to return early.
378		//
379		// There could be transaction being added because of some re-org happening at the relevant
380		// block, but this is relative unlikely.
381		if status.ready == 0 && status.future == 0 {
382			return Box::new(std::iter::empty()) as Box<_>;
383		}
384
385		if self.ready_poll.lock().updated_at() >= at {
386			trace!(
387				target: LOG_TARGET,
388				?at,
389				"Transaction pool already processed block."
390			);
391			let iterator: ReadyIteratorFor<PoolApi> = Box::new(self.pool.validated_pool().ready());
392			return iterator;
393		}
394
395		let result = self.ready_poll.lock().add(at).map(|received| {
396			received.unwrap_or_else(|error| {
397				warn!(target: LOG_TARGET,  ?error, "Error receiving pending set.");
398				Box::new(std::iter::empty())
399			})
400		});
401
402		result.await
403	}
404
405	fn ready(&self) -> ReadyIteratorFor<PoolApi> {
406		Box::new(self.pool.validated_pool().ready())
407	}
408
409	fn futures(&self) -> Vec<Self::InPoolTransaction> {
410		let pool = self.pool.validated_pool().pool.read();
411		pool.futures().cloned().collect::<Vec<_>>()
412	}
413
414	async fn ready_at_with_timeout(
415		&self,
416		at: <Self::Block as BlockT>::Hash,
417		timeout: std::time::Duration,
418	) -> ReadyIteratorFor<PoolApi> {
419		self.ready_at_with_timeout_internal(at, timeout).await
420	}
421}
422
423impl<Block, Client> BasicPool<FullChainApi<Client, Block>, Block>
424where
425	Block: BlockT,
426	Client: crate::ClientForTransactionPool<Block>
427		+ sc_client_api::ExecutorProvider<Block>
428		+ sc_client_api::UsageProvider<Block>,
429{
430	/// Create new basic transaction pool for a full node with the provided api.
431	pub fn new_full(
432		options: graph::Options,
433		is_validator: IsValidator,
434		prometheus: Option<&PrometheusRegistry>,
435		spawner: impl SpawnEssentialNamed,
436		client: Arc<Client>,
437	) -> Self {
438		let pool_api = Arc::new(FullChainApi::new(client.clone(), prometheus, &spawner));
439		let pool = Self::with_revalidation_type(
440			options,
441			is_validator,
442			pool_api,
443			prometheus,
444			RevalidationType::Full,
445			spawner,
446			client.usage_info().chain.best_number,
447			client.usage_info().chain.best_hash,
448			client.usage_info().chain.finalized_hash,
449		);
450
451		pool
452	}
453}
454
455impl<Block, Client> sc_transaction_pool_api::LocalTransactionPool
456	for BasicPool<FullChainApi<Client, Block>, Block>
457where
458	Block: BlockT,
459	Client: crate::ClientForTransactionPool<Block>,
460{
461	type Block = Block;
462	type Hash = graph::ExtrinsicHash<FullChainApi<Client, Block>>;
463	type Error = <FullChainApi<Client, Block> as graph::ChainApi>::Error;
464
465	fn submit_local(
466		&self,
467		at: Block::Hash,
468		xt: sc_transaction_pool_api::LocalTransactionFor<Self>,
469	) -> Result<Self::Hash, Self::Error> {
470		let validity = self
471			.api
472			.validate_transaction_blocking(at, TransactionSource::Local, Arc::from(xt.clone()))?
473			.map_err(|e| {
474				Self::Error::Pool(match e {
475					TransactionValidityError::Invalid(i) => TxPoolError::InvalidTransaction(i),
476					TransactionValidityError::Unknown(u) => TxPoolError::UnknownTransaction(u),
477				})
478			})?;
479
480		let (hash, bytes) = self.pool.validated_pool().api().hash_and_length(&xt);
481		let block_number = self
482			.api
483			.block_id_to_number(&BlockId::hash(at))?
484			.ok_or_else(|| error::Error::BlockIdConversion(format!("{:?}", at)))?;
485
486		let validated = ValidatedTransaction::valid_at(
487			block_number.saturated_into::<u64>(),
488			hash,
489			TimedTransactionSource::new_local(false),
490			Arc::from(xt),
491			bytes,
492			validity,
493		);
494
495		self.pool
496			.validated_pool()
497			.submit(vec![validated])
498			.remove(0)
499			.map(|outcome| outcome.hash())
500	}
501}
502
503#[cfg_attr(test, derive(Debug))]
504enum RevalidationStatus<N> {
505	/// The revalidation has never been completed.
506	NotScheduled,
507	/// The revalidation is scheduled.
508	Scheduled(Option<Instant>, Option<N>),
509	/// The revalidation is in progress.
510	InProgress,
511}
512
513enum RevalidationStrategy<N> {
514	Always,
515	Light(RevalidationStatus<N>),
516}
517
518struct RevalidationAction {
519	revalidate: bool,
520	resubmit: bool,
521}
522
523impl<N: Clone + Copy + AtLeast32Bit> RevalidationStrategy<N> {
524	pub fn clear(&mut self) {
525		if let Self::Light(status) = self {
526			status.clear()
527		}
528	}
529
530	pub fn next(
531		&mut self,
532		block: N,
533		revalidate_time_period: Option<std::time::Duration>,
534		revalidate_block_period: Option<N>,
535	) -> RevalidationAction {
536		match self {
537			Self::Light(status) => RevalidationAction {
538				revalidate: status.next_required(
539					block,
540					revalidate_time_period,
541					revalidate_block_period,
542				),
543				resubmit: false,
544			},
545			Self::Always => RevalidationAction { revalidate: true, resubmit: true },
546		}
547	}
548}
549
550impl<N: Clone + Copy + AtLeast32Bit> RevalidationStatus<N> {
551	/// Called when revalidation is completed.
552	pub fn clear(&mut self) {
553		*self = Self::NotScheduled;
554	}
555
556	/// Returns true if revalidation is required.
557	pub fn next_required(
558		&mut self,
559		block: N,
560		revalidate_time_period: Option<std::time::Duration>,
561		revalidate_block_period: Option<N>,
562	) -> bool {
563		match *self {
564			Self::NotScheduled => {
565				*self = Self::Scheduled(
566					revalidate_time_period.map(|period| Instant::now() + period),
567					revalidate_block_period.map(|period| block + period),
568				);
569				false
570			},
571			Self::Scheduled(revalidate_at_time, revalidate_at_block) => {
572				let is_required =
573					revalidate_at_time.map(|at| Instant::now() >= at).unwrap_or(false) ||
574						revalidate_at_block.map(|at| block >= at).unwrap_or(false);
575				if is_required {
576					*self = Self::InProgress;
577				}
578				is_required
579			},
580			Self::InProgress => false,
581		}
582	}
583}
584
585/// Prune the known txs from the given pool for the given block.
586///
587/// Returns the hashes of all transactions included in given block.
588pub async fn prune_known_txs_for_block<
589	Block: BlockT,
590	Api: graph::ChainApi<Block = Block>,
591	L: EventHandler<Api>,
592>(
593	at: &HashAndNumber<Block>,
594	api: &Api,
595	pool: &graph::Pool<Api, L>,
596	extrinsics: Option<Vec<RawExtrinsicFor<Api>>>,
597	known_provides_tags: Option<Arc<HashMap<ExtrinsicHash<Api>, Vec<Tag>>>>,
598) -> Vec<ExtrinsicHash<Api>> {
599	let extrinsics = match extrinsics {
600		Some(xts) => xts,
601		None => api
602			.block_body(at.hash)
603			.await
604			.unwrap_or_else(|error| {
605				warn!(target: LOG_TARGET, ?error, "Prune known transactions: error request.");
606				None
607			})
608			.unwrap_or_default(),
609	};
610
611	let hashes = extrinsics.iter().map(|tx| pool.hash_of(tx)).collect::<Vec<_>>();
612
613	let header = match api.block_header(at.hash) {
614		Ok(Some(h)) => h,
615		Ok(None) => {
616			trace!(target: LOG_TARGET, hash = ?at.hash, "Could not find header.");
617			return hashes;
618		},
619		Err(error) => {
620			trace!(target: LOG_TARGET, hash = ?at.hash,  ?error, "Error retrieving header.");
621			return hashes;
622		},
623	};
624
625	log_xt_trace!(target: LOG_TARGET, &hashes, "Pruning transaction.");
626
627	pool.prune(at, *header.parent_hash(), &extrinsics, known_provides_tags).await;
628	hashes
629}
630
631impl<PoolApi, Block> BasicPool<PoolApi, Block>
632where
633	Block: BlockT,
634	PoolApi: 'static + graph::ChainApi<Block = Block>,
635{
636	/// Handles enactment and retraction of blocks, prunes stale transactions
637	/// (that have already been enacted) and resubmits transactions that were
638	/// retracted.
639	async fn handle_enactment(&self, tree_route: TreeRoute<Block>) {
640		trace!(target: LOG_TARGET, ?tree_route, "handle_enactment tree_route.");
641		let pool = self.pool.clone();
642		let api = self.api.clone();
643
644		let hash_and_number = match tree_route.last() {
645			Some(hash_and_number) => hash_and_number,
646			None => {
647				warn!(target: LOG_TARGET, ?tree_route, "Skipping ChainEvent - no last block in tree route.");
648				return;
649			},
650		};
651
652		let next_action = self.revalidation_strategy.lock().next(
653			hash_and_number.number,
654			Some(std::time::Duration::from_secs(60)),
655			Some(20u32.into()),
656		);
657
658		// We keep track of everything we prune so that later we won't add
659		// transactions with those hashes from the retracted blocks.
660		let mut pruned_log = HashSet::<ExtrinsicHash<PoolApi>>::new();
661
662		// If there is a tree route, we use this to prune known tx based on the enacted
663		// blocks. Before pruning enacted transactions, we inform the listeners about
664		// retracted blocks and their transactions. This order is important, because
665		// if we enact and retract the same transaction at the same time, we want to
666		// send first the retract and then the prune event.
667		for retracted in tree_route.retracted() {
668			// notify txs awaiting finality that it has been retracted
669			pool.validated_pool().on_block_retracted(retracted.hash);
670		}
671
672		future::join_all(
673			tree_route
674				.enacted()
675				.iter()
676				.map(|h| prune_known_txs_for_block(h, &*api, &*pool, None, None)),
677		)
678		.await
679		.into_iter()
680		.for_each(|enacted_log| {
681			pruned_log.extend(enacted_log);
682		});
683
684		self.metrics
685			.report(|metrics| metrics.block_transactions_pruned.inc_by(pruned_log.len() as u64));
686
687		if next_action.resubmit {
688			let mut resubmit_transactions = Vec::new();
689
690			for retracted in tree_route.retracted() {
691				let hash = retracted.hash;
692
693				let block_transactions = api
694					.block_body(hash)
695					.await
696					.unwrap_or_else(|error| {
697						warn!(target: LOG_TARGET, ?error, "Failed to fetch block body.");
698						None
699					})
700					.unwrap_or_default()
701					.into_iter();
702
703				let mut resubmitted_to_report = 0;
704
705				resubmit_transactions.extend(
706					// todo: arctx - we need to get ref from somewhere
707					block_transactions.into_iter().map(Arc::from).filter_map(|tx| {
708						let tx_hash = pool.hash_of(&tx);
709						let contains = pruned_log.contains(&tx_hash);
710
711						// need to count all transactions, not just filtered, here
712						resubmitted_to_report += 1;
713
714						if !contains {
715							trace!(target: LOG_TARGET, ?tx_hash, ?hash, "Resubmitting from retracted block.");
716							Some((
717								// These transactions are coming from retracted blocks, we should
718								// simply consider them external.
719								TimedTransactionSource::new_external(false),
720								tx,
721							))
722						} else {
723							None
724						}
725					}),
726				);
727
728				self.metrics.report(|metrics| {
729					metrics.block_transactions_resubmitted.inc_by(resubmitted_to_report)
730				});
731			}
732
733			pool.resubmit_at(
734				&hash_and_number,
735				resubmit_transactions,
736				ValidateTransactionPriority::Submitted,
737			)
738			.await;
739		}
740
741		let extra_pool = pool.clone();
742		// After #5200 lands, this arguably might be moved to the
743		// handler of "all blocks notification".
744		self.ready_poll
745			.lock()
746			.trigger(hash_and_number.number, move || Box::new(extra_pool.validated_pool().ready()));
747
748		if next_action.revalidate {
749			let hashes = pool.validated_pool().ready().map(|tx| tx.hash).collect();
750			self.revalidation_queue.revalidate_later(hash_and_number.hash, hashes).await;
751
752			self.revalidation_strategy.lock().clear();
753		}
754	}
755}
756
757#[async_trait]
758impl<PoolApi, Block> MaintainedTransactionPool for BasicPool<PoolApi, Block>
759where
760	Block: BlockT,
761	PoolApi: 'static + graph::ChainApi<Block = Block>,
762{
763	async fn maintain(&self, event: ChainEvent<Self::Block>) {
764		let prev_finalized_block = self.enactment_state.lock().recent_finalized_block();
765		let compute_tree_route = |from, to| -> Result<TreeRoute<Block>, String> {
766			match self.api.tree_route(from, to) {
767				Ok(tree_route) => Ok(tree_route),
768				Err(e) => {
769					return Err(format!(
770						"Error occurred while computing tree_route from {from:?} to {to:?}: {e}"
771					))
772				},
773			}
774		};
775		let block_id_to_number =
776			|hash| self.api.block_id_to_number(&BlockId::Hash(hash)).map_err(|e| format!("{}", e));
777
778		let result =
779			self.enactment_state
780				.lock()
781				.update(&event, &compute_tree_route, &block_id_to_number);
782
783		match result {
784			Err(error) => {
785				trace!(target: LOG_TARGET, %error, "enactment state update");
786				self.enactment_state.lock().force_update(&event);
787			},
788			Ok(EnactmentAction::Skip) => return,
789			Ok(EnactmentAction::HandleFinalization) => {},
790			Ok(EnactmentAction::HandleEnactment(tree_route)) => {
791				self.handle_enactment(tree_route).await;
792			},
793		};
794
795		if let ChainEvent::Finalized { hash, tree_route } = event {
796			trace!(
797				target: LOG_TARGET,
798				?tree_route,
799				?prev_finalized_block,
800				"on-finalized enacted"
801			);
802
803			for hash in tree_route.iter().chain(std::iter::once(&hash)) {
804				if let Err(error) = self.pool.validated_pool().on_block_finalized(*hash).await {
805					warn!(
806						target: LOG_TARGET,
807						?hash,
808						?error,
809						"Error occurred while attempting to notify watchers about finalization"
810					);
811				}
812			}
813		}
814	}
815}