zebrad/components/mempool/queue_checker.rs
1//! Zebra Mempool queue checker.
2//!
3//! The queue checker sends a request to the mempool when a transaction is verified, and
4//! periodically as a backstop, so that newly verified transactions are added to the mempool,
5//! and gossiped to peers.
6//!
7//! The mempool performs these actions on every request,
8//! but we can't guarantee that requests will arrive from peers
9//! on a regular basis.
10//!
11//! Crawler queue requests are also too infrequent,
12//! and they only happen if peers respond within the timeout.
13
14use std::{sync::Arc, time::Duration};
15
16use tokio::{sync::Notify, task::JoinHandle, time::sleep};
17use tower::{BoxError, Service, ServiceExt};
18use tracing::Instrument;
19
20use crate::components::mempool;
21
22/// The longest the queue checker waits between queue check events.
23///
24/// The backstop also handles other mempool work, such as chain tip changes and transactions that
25/// fail to download or verify.
26///
27/// This interval is chosen so that there are a significant number of
28/// queue checks in each target block interval.
29///
30/// This allows transactions to propagate across the network for each block,
31/// even if some peers are poorly connected.
32pub(crate) const RATE_LIMIT_DELAY: Duration = Duration::from_secs(5);
33
34/// The mempool queue checker.
35///
36/// The queue checker relies on the mempool to ignore requests when the mempool is inactive.
37pub struct QueueChecker<Mempool> {
38 /// The mempool service that receives crawled transaction IDs.
39 mempool: Mempool,
40
41 /// Notified when a transaction is verified.
42 transaction_verified: Arc<Notify>,
43}
44
45impl<Mempool> QueueChecker<Mempool>
46where
47 Mempool:
48 Service<mempool::Request, Response = mempool::Response, Error = BoxError> + Send + 'static,
49 Mempool::Future: Send,
50{
51 /// Spawn an asynchronous task to run the mempool queue checker.
52 ///
53 /// The downloader signals `transaction_verified` after queuing each verified transaction.
54 pub fn spawn(
55 mempool: Mempool,
56 transaction_verified: Arc<Notify>,
57 ) -> JoinHandle<Result<(), BoxError>> {
58 let queue_checker = QueueChecker {
59 mempool,
60 transaction_verified,
61 };
62
63 tokio::spawn(queue_checker.run().in_current_span())
64 }
65
66 /// Check if the mempool has newly verified transactions, when a transaction is verified and at
67 /// least every [`RATE_LIMIT_DELAY`].
68 ///
69 /// Runs until the mempool returns an error,
70 /// which happens when Zebra is shutting down.
71 pub async fn run(mut self) -> Result<(), BoxError> {
72 info!("initializing mempool queue checker task");
73
74 loop {
75 // A notification that arrives while the mempool is being checked is stored, so the
76 // next wait returns immediately and the transaction isn't left until the backstop.
77 tokio::select! {
78 () = self.transaction_verified.notified() => {}
79 () = sleep(RATE_LIMIT_DELAY) => {}
80 }
81
82 self.check_queue().await?;
83 }
84 }
85
86 /// Check if the mempool has newly verified transactions.
87 async fn check_queue(&mut self) -> Result<(), BoxError> {
88 debug!("checking for newly verified mempool transactions");
89
90 // Since this is an internal request, we don't expect any errors.
91 // So we propagate any unexpected errors to the task that spawned us.
92 let response = self
93 .mempool
94 .ready()
95 .await?
96 .call(mempool::Request::CheckForVerifiedTransactions)
97 .await?;
98
99 match response {
100 mempool::Response::CheckedForVerifiedTransactions => {}
101 _ => {
102 unreachable!("mempool did not respond with checked queue to mempool queue checker")
103 }
104 };
105
106 Ok(())
107 }
108}