Skip to main content

zebrad/components/mempool/
downloads.rs

1//! Transaction downloader and verifier.
2//!
3//! The main struct [`Downloads`] allows downloading and verifying transactions.
4//! It is used by the mempool to get transactions into it. It is also able to
5//! just verify transactions that were directly pushed.
6//!
7//! The verification itself is done by the [`zebra_consensus`] crate.
8//!
9//! Verified transactions are returned to the caller in [`Downloads::poll_next`].
10//! This is in contrast to the block downloader and verifiers which don't
11//! return anything and forward the verified blocks to the state themselves.
12//!
13//! # Correctness
14//!
15//! The mempool downloader doesn't send verified transactions to the [`Mempool`]
16//! service. So Zebra must spawn a task that regularly polls the downloader for
17//! ready transactions. (To ensure that transactions propagate across the entire
18//! network in each 75s block interval, the polling interval should be around
19//! 5-10 seconds.)
20//!
21//! Polling the downloader from [`Mempool::poll_ready`] is not sufficient.
22//! [`Service::poll_ready`] is only called when there is a service request.
23//! But we want to download and gossip transactions,
24//! even when there are no other service requests.
25//!
26//! [`Mempool`]: super::Mempool
27//! [`Mempool::poll_ready`]: super::Mempool::poll_ready
28use std::{
29    collections::{HashMap, HashSet},
30    net::{IpAddr, SocketAddr},
31    pin::Pin,
32    sync::Arc,
33    task::{Context, Poll},
34    time::Duration,
35};
36
37use futures::{
38    future::TryFutureExt,
39    ready,
40    stream::{FuturesUnordered, Stream},
41    FutureExt,
42};
43use pin_project::{pin_project, pinned_drop};
44use thiserror::Error;
45use tokio::{
46    sync::{mpsc, oneshot, Notify},
47    task::JoinHandle,
48};
49use tower::{Service, ServiceExt};
50use tracing::Instrument;
51
52use zebra_chain::{
53    block::Height,
54    parameters::NetworkUpgrade,
55    transaction::{self, UnminedTxId, VerifiedUnminedTx},
56    transparent,
57};
58use zebra_consensus::transaction as tx;
59use zebra_network::{self as zn, PeerSocketAddr};
60use zebra_node_services::mempool::Gossip;
61use zebra_state::{self as zs, CloneError};
62
63use crate::components::{
64    mempool::crawler::RATE_LIMIT_DELAY,
65    sync::{BLOCK_DOWNLOAD_TIMEOUT, BLOCK_VERIFY_TIMEOUT},
66};
67
68use super::{
69    config::DEFAULT_MAX_DATACARRIER_BYTES,
70    storage::{check_standard_outputs, NonStandardTransactionError},
71    MempoolError,
72};
73
74type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
75
76/// Controls how long we wait for a transaction download request to complete.
77///
78/// This is currently equal to [`BLOCK_DOWNLOAD_TIMEOUT`] for
79/// consistency, even though parts of the rationale used for defining the value
80/// don't apply here (e.g. we can drop transactions hashes when the queue is full).
81pub(crate) const TRANSACTION_DOWNLOAD_TIMEOUT: Duration = BLOCK_DOWNLOAD_TIMEOUT;
82
83/// Controls how long we wait for a transaction verify request to complete.
84///
85/// This is currently equal to [`BLOCK_VERIFY_TIMEOUT`] for
86/// consistency.
87///
88/// This timeout may lead to denial of service, which will be handled in
89/// [#2694](https://github.com/ZcashFoundation/zebra/issues/2694)
90pub(crate) const TRANSACTION_VERIFY_TIMEOUT: Duration = BLOCK_VERIFY_TIMEOUT;
91
92/// The maximum number of concurrent inbound download and verify tasks.
93///
94/// We expect the mempool crawler to download and verify most mempool transactions, so this bound
95/// can be small. But it should be at least the default `network.peerset_initial_target_size` config,
96/// to avoid disconnecting peers on startup.
97///
98/// ## Security
99///
100/// We use a small concurrency limit, to prevent memory denial-of-service
101/// attacks.
102///
103/// The maximum transaction size is 2 million bytes. A deserialized malicious
104/// transaction with ~225_000 transparent outputs can take up 9MB of RAM.
105/// (See #1880 for more details.)
106///
107/// Malicious transactions will eventually timeout or fail validation.
108/// Once validation fails, the transaction is dropped, and its memory is deallocated.
109///
110/// Since Zebra keeps an `inv` index, inbound downloads for malicious transactions
111/// will be directed to the malicious node that originally gossiped the hash.
112/// Therefore, this attack can be carried out by a single malicious node.
113//
114// TODO: replace with the configured value of network.peerset_initial_target_size
115pub const MAX_INBOUND_CONCURRENCY: usize = 500;
116
117/// The maximum number of concurrent inbound download tasks attributable to a
118/// single advertising peer.
119///
120/// Caps how many slots of [`MAX_INBOUND_CONCURRENCY`] one peer's `Inv`
121/// advertisements can occupy, so a single peer cannot saturate the global
122/// queue with fake txids and deny gossip-path mempool admission for honest
123/// peers. See `GHSA-4fc2-h7jh-287c`. Crawler-driven and locally-pushed
124/// transactions have no source peer and are not counted against the cap.
125pub const MAX_INBOUND_CONCURRENCY_PER_PEER: usize = 5;
126
127/// A marker struct for the oneshot channels which cancel a pending download and verify.
128#[derive(Copy, Clone, Debug, Eq, PartialEq)]
129struct CancelDownloadAndVerify;
130
131/// Errors that can occur while downloading and verifying a transaction.
132#[derive(Error, Debug, Clone)]
133#[allow(dead_code)]
134pub enum TransactionDownloadVerifyError {
135    #[error("transaction is already in state")]
136    InState,
137
138    #[error("error in state service: {0}")]
139    StateError(#[source] CloneError),
140
141    #[error("error downloading transaction: {0}")]
142    DownloadFailed(#[source] CloneError),
143
144    #[error("transaction download / verification was cancelled")]
145    Cancelled,
146
147    #[error("transaction did not pass consensus validation: {error}")]
148    Invalid {
149        error: zebra_consensus::error::TransactionError,
150        advertiser_addr: Option<PeerSocketAddr>,
151        /// The transaction's consensus branch upgrade, if its version contains one.
152        transaction_upgrade: Option<NetworkUpgrade>,
153        /// The candidate block height used for mempool consensus verification.
154        verification_height: Height,
155    },
156
157    #[error("transaction is non-standard: {0}")]
158    NonStandard(NonStandardTransactionError),
159}
160
161impl TransactionDownloadVerifyError {
162    /// Returns a bounded metric label, excluding nested errors and transaction details.
163    pub(super) fn metric_label(&self) -> &'static str {
164        match self {
165            Self::InState => "in_state",
166            Self::StateError(_) => "state_error",
167            Self::DownloadFailed(_) => "download_failed",
168            Self::Cancelled => "cancelled",
169            Self::Invalid { .. } => "invalid",
170            Self::NonStandard(_) => "non_standard",
171        }
172    }
173}
174
175/// A download and verify result queued before notifying the mempool.
176type VerifyResult = Result<
177    Result<
178        (
179            VerifiedUnminedTx,
180            Vec<transparent::OutPoint>,
181            Option<Height>,
182            Option<oneshot::Sender<Result<(), BoxError>>>,
183        ),
184        Box<(TransactionDownloadVerifyError, UnminedTxId)>,
185    >,
186    (UnminedTxId, tokio::time::error::Elapsed),
187>;
188
189/// Represents a [`Stream`] of download and verification tasks.
190#[pin_project(PinnedDrop)]
191#[derive(Debug)]
192pub struct Downloads<ZN, ZV, ZS>
193where
194    ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
195    ZN::Future: Send,
196    ZV: Service<tx::MempoolRequest, Response = tx::MempoolResponse, Error = BoxError>
197        + Send
198        + Clone
199        + 'static,
200    ZV::Future: Send,
201    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
202    ZS::Future: Send,
203{
204    // Services
205    /// A service that forwards requests to connected peers, and returns their
206    /// responses.
207    network: ZN,
208
209    /// A service that verifies downloaded transactions.
210    verifier: ZV,
211
212    /// A service that manages cached blockchain state.
213    state: ZS,
214
215    /// The maximum OP_RETURN script size for the standard output checks.
216    max_datacarrier_bytes: u32,
217
218    // Internal downloads state
219    /// Pending tasks, retained to reap finished tasks and propagate panics.
220    #[pin]
221    pending: FuturesUnordered<JoinHandle<()>>,
222
223    /// The results of finished download and verify tasks.
224    results: mpsc::UnboundedReceiver<VerifyResult>,
225
226    /// The sender each task uses to queue its result.
227    results_sender: mpsc::UnboundedSender<VerifyResult>,
228
229    /// Transactions whose results have not been consumed, including cancelled tasks.
230    in_flight: usize,
231
232    /// A list of channels that can be used to cancel pending transaction
233    /// download and verify tasks. Each entry also stores the corresponding
234    /// gossip request and the announcing peer (when known), so completion can
235    /// release the per-peer slot by `UnminedTxId` lookup.
236    cancel_handles: HashMap<
237        UnminedTxId,
238        (
239            oneshot::Sender<CancelDownloadAndVerify>,
240            Gossip,
241            Option<SocketAddr>,
242        ),
243    >,
244
245    /// The number of currently in-flight download tasks per advertising host,
246    /// keyed on the peer's [`IpAddr`].
247    ///
248    /// Keyed on the host IP rather than the full `SocketAddr` so that all
249    /// connections from one host share a single budget: the `source` is a
250    /// transient `(IP, ephemeral port)`, so per-`SocketAddr` keying would give
251    /// each connection its own bucket. This matches the inbound-block download
252    /// cap (`in_flight_ips`). See #10685.
253    ///
254    /// Invariant: an IP is present here with count `n` iff exactly `n` entries in
255    /// [`Self::cancel_handles`] have a source with that IP. Enforces
256    /// [`MAX_INBOUND_CONCURRENCY_PER_PEER`]. See `GHSA-4fc2-h7jh-287c`.
257    pending_per_peer: HashMap<IpAddr, usize>,
258
259    /// Wakes the queue checker to store and announce verified transactions.
260    transaction_verified: Arc<Notify>,
261}
262
263impl<ZN, ZV, ZS> Stream for Downloads<ZN, ZV, ZS>
264where
265    ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
266    ZN::Future: Send,
267    ZV: Service<tx::MempoolRequest, Response = tx::MempoolResponse, Error = BoxError>
268        + Send
269        + Clone
270        + 'static,
271    ZV::Future: Send,
272    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
273    ZS::Future: Send,
274{
275    type Item = Result<
276        Result<
277            (
278                VerifiedUnminedTx,
279                Vec<transparent::OutPoint>,
280                Option<Height>,
281                Option<oneshot::Sender<Result<(), BoxError>>>,
282            ),
283            Box<(UnminedTxId, TransactionDownloadVerifyError)>,
284        >,
285        (UnminedTxId, tokio::time::error::Elapsed),
286    >;
287
288    fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
289        let mut this = self.project();
290
291        // Results arrive separately; join handles still propagate task panics.
292        while let Poll::Ready(Some(join_result)) = this.pending.as_mut().poll_next(cx) {
293            join_result.expect("transaction download and verify tasks must not panic");
294        }
295
296        let result = this.results.poll_recv(cx);
297        // A cooperative yield must not strand queued results: the mempool returns readiness
298        // on Pending, so only another queue-check request will resume draining them.
299        if result.is_pending() && !this.results.is_empty() {
300            this.transaction_verified.notify_one();
301        }
302        let item = if let Some(result) = ready!(result) {
303            *this.in_flight -= 1;
304            let (result, completed_txid) = match result {
305                Ok(Ok((tx, spent_mempool_outpoints, tip_height, rsp_tx))) => {
306                    let hash = tx.transaction.id;
307                    (
308                        Ok(Ok((tx, spent_mempool_outpoints, tip_height, rsp_tx))),
309                        Some(hash),
310                    )
311                }
312                Ok(Err(boxed_err)) => {
313                    let (e, hash) = *boxed_err;
314                    (Ok(Err(Box::new((hash, e)))), Some(hash))
315                }
316                Err((txid, elapsed)) => {
317                    // Treat a verification timeout as a terminal completion so the
318                    // shared cleanup below removes the `cancel_handles` entry — the
319                    // GHSA-65jj fix, which drops the resident `Gossip` (~2 MB per tx)
320                    // so it can't leak until OOM — and releases the per-peer queue
321                    // slot. A bare handle removal here left the slot pinned, so a
322                    // peer that timed out `MAX_INBOUND_CONCURRENCY_PER_PEER`
323                    // transactions could no longer queue any from that source.
324                    // See #10684.
325                    (Err((txid, elapsed)), Some(txid))
326                }
327            };
328
329            if let Some(hash) = completed_txid {
330                if let Some((_, _gossip, Some(source))) = this.cancel_handles.remove(&hash) {
331                    Self::release_peer_slot(this.pending_per_peer, source);
332                }
333            }
334
335            Some(result)
336        } else {
337            None
338        };
339
340        Poll::Ready(item)
341    }
342}
343
344impl<ZN, ZV, ZS> Downloads<ZN, ZV, ZS>
345where
346    ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
347    ZN::Future: Send,
348    ZV: Service<tx::MempoolRequest, Response = tx::MempoolResponse, Error = BoxError>
349        + Send
350        + Clone
351        + 'static,
352    ZV::Future: Send,
353    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
354    ZS::Future: Send,
355{
356    /// Initialize a new download stream with the provided services.
357    ///
358    /// `network` is used to download transactions.
359    /// `verifier` is used to verify transactions.
360    /// `state` is used to check if transactions are already in the state.
361    ///
362    /// The notification wakes the queue checker after each verified transaction is queued.
363    ///
364    /// The [`Downloads`] stream is agnostic to the network policy, so retry and
365    /// timeout limits should be applied to the `network` service passed into
366    /// this constructor.
367    pub fn new(network: ZN, verifier: ZV, state: ZS, transaction_verified: Arc<Notify>) -> Self {
368        let (results_sender, results) = mpsc::unbounded_channel();
369
370        Self {
371            network,
372            verifier,
373            state,
374            max_datacarrier_bytes: DEFAULT_MAX_DATACARRIER_BYTES,
375            pending: FuturesUnordered::new(),
376            results,
377            results_sender,
378            in_flight: 0,
379            cancel_handles: HashMap::new(),
380            pending_per_peer: HashMap::new(),
381            transaction_verified,
382        }
383    }
384
385    /// Sets the maximum OP_RETURN script size used by the standard output checks.
386    pub fn with_max_datacarrier_bytes(mut self, max_datacarrier_bytes: u32) -> Self {
387        self.max_datacarrier_bytes = max_datacarrier_bytes;
388        self
389    }
390
391    /// Queue a transaction for download (if needed) and verification.
392    ///
393    /// Returns the action taken in response to the queue request.
394    ///
395    /// When `source` is `Some`, the per-peer cap
396    /// [`MAX_INBOUND_CONCURRENCY_PER_PEER`] is enforced; crawler-driven and
397    /// locally-pushed transactions pass `None` and are not capped per peer.
398    #[instrument(skip(self, gossiped_tx), fields(txid = %gossiped_tx.id()))]
399    #[allow(clippy::unwrap_in_result)]
400    pub fn download_if_needed_and_verify(
401        &mut self,
402        gossiped_tx: Gossip,
403        source: Option<SocketAddr>,
404        mut rsp_tx: Option<oneshot::Sender<Result<(), BoxError>>>,
405    ) -> Result<(), MempoolError> {
406        let txid = gossiped_tx.id();
407
408        if self.cancel_handles.contains_key(&txid) {
409            debug!(
410                ?txid,
411                queue_len = self.in_flight,
412                ?MAX_INBOUND_CONCURRENCY,
413                "transaction id already queued for inbound download: ignored transaction"
414            );
415            metrics::gauge!("mempool.currently.queued.transactions",).set(self.in_flight as f64);
416
417            return Err(MempoolError::AlreadyQueued);
418        }
419
420        if self.in_flight >= MAX_INBOUND_CONCURRENCY {
421            debug!(
422                ?txid,
423                queue_len = self.in_flight,
424                ?MAX_INBOUND_CONCURRENCY,
425                "too many transactions queued for inbound download: ignored transaction"
426            );
427            metrics::gauge!("mempool.currently.queued.transactions",).set(self.in_flight as f64);
428
429            return Err(MempoolError::FullQueue);
430        }
431
432        // Per-peer cap: a single advertising host (keyed by IP) cannot saturate
433        // the queue with attacker-supplied fake txids. See `GHSA-4fc2-h7jh-287c`.
434        if let Some(source) = source {
435            let count = self
436                .pending_per_peer
437                .get(&source.ip())
438                .copied()
439                .unwrap_or(0);
440            if count >= MAX_INBOUND_CONCURRENCY_PER_PEER {
441                debug!(
442                    ?txid,
443                    peer_queue_len = count,
444                    ?MAX_INBOUND_CONCURRENCY_PER_PEER,
445                    "too many transactions queued for this peer: ignored transaction"
446                );
447                metrics::counter!("mempool.full_queue.per_peer.total").increment(1);
448                return Err(MempoolError::FullQueue);
449            }
450        }
451
452        // This oneshot is used to signal cancellation to the download task.
453        let (cancel_tx, mut cancel_rx) = oneshot::channel::<CancelDownloadAndVerify>();
454
455        let network = self.network.clone();
456        let verifier = self.verifier.clone();
457        let mut state = self.state.clone();
458        let max_datacarrier_bytes = self.max_datacarrier_bytes;
459        let pushed_advertiser_addr = source.map(PeerSocketAddr::from);
460
461        let gossiped_tx_req = gossiped_tx.clone();
462
463        let fut = async move {
464            // Don't download/verify if the transaction is already in the best chain.
465            Self::transaction_in_best_chain(&mut state, txid).await?;
466
467            trace!(?txid, "transaction is not in best chain");
468
469            let (tip_height, next_height) = match state.oneshot(zs::Request::Tip).await {
470                Ok(zs::Response::Tip(None)) => Ok((None, Height(0))),
471                Ok(zs::Response::Tip(Some((height, _hash)))) => {
472                    let next_height =
473                        (height + 1).expect("valid heights are far below the maximum");
474                    Ok((Some(height), next_height))
475                }
476                Ok(_) => unreachable!("wrong response"),
477                Err(e) => Err(TransactionDownloadVerifyError::StateError(e.into())),
478            }?;
479
480            trace!(?txid, ?next_height, "got next height");
481
482            let (tx, advertiser_addr) = match gossiped_tx {
483                Gossip::Id(txid) => {
484                    let req = zn::Request::TransactionsById(std::iter::once(txid).collect());
485
486                    let tx = match network
487                        .oneshot(req)
488                        .await
489                        .map_err(CloneError::from)
490                        .map_err(TransactionDownloadVerifyError::DownloadFailed)?
491                    {
492                        zn::Response::Transactions(mut txs) => txs.pop().ok_or_else(|| {
493                            TransactionDownloadVerifyError::DownloadFailed(
494                                BoxError::from("no transactions returned").into(),
495                            )
496                        })?,
497                        _ => unreachable!("wrong response to transaction request"),
498                    };
499
500                    let (tx, advertiser_addr) = tx.available().expect(
501                        "unexpected missing tx status: single tx failures should be errors",
502                    );
503
504                    metrics::counter!(
505                        "mempool.downloaded.transactions.total",
506                        "version" => format!("{}",tx.transaction.version()),
507                    ).increment(1);
508                    (tx, advertiser_addr)
509                }
510                Gossip::Tx(tx) => {
511                    metrics::counter!(
512                        "mempool.pushed.transactions.total",
513                        "version" => format!("{}",tx.transaction.version()),
514                    ).increment(1);
515                    (tx, pushed_advertiser_addr)
516                }
517            };
518
519            trace!(?txid, "got tx");
520
521            // Reject non-standard outputs before verifying scripts and proofs, like zcashd.
522            check_standard_outputs(&tx.transaction, max_datacarrier_bytes)
523                .map_err(TransactionDownloadVerifyError::NonStandard)?;
524
525            let transaction_upgrade = tx.transaction.network_upgrade();
526            let result = verifier
527                .oneshot(tx::MempoolRequest {
528                    transaction: tx.clone(),
529                    height: next_height,
530                })
531                .map_ok(|rsp| {
532                    let tx::MempoolResponse { transaction, spent_mempool_outpoints } = rsp;
533
534                    (transaction, spent_mempool_outpoints, tip_height)
535                })
536                .await;
537
538            // Hide the transaction data to avoid filling the logs
539            trace!(?txid, result = ?result.as_ref().map(|_tx| ()), "verified transaction for the mempool");
540
541            result.map_err(|error| TransactionDownloadVerifyError::Invalid {
542                error: error.into(),
543                advertiser_addr,
544                transaction_upgrade,
545                verification_height: next_height,
546            })
547        }
548        .map_ok(|(tx, spent_mempool_outpoints, tip_height)| {
549            metrics::counter!(
550                "mempool.verified.transactions.total",
551                "version" => format!("{}", tx.transaction.transaction.version()),
552            ).increment(1);
553            (tx, spent_mempool_outpoints, tip_height)
554        })
555        // Tack the hash onto the error so we can remove the cancel handle
556        // on failure as well as on success.
557        .map_err(move |e| Box::new((e, txid)))
558        .inspect(move |result| {
559            // Hide the transaction data to avoid filling the logs
560            let result = result.as_ref().map(|_tx| txid);
561            debug!("mempool transaction result: {result:?}");
562        })
563        .in_current_span();
564
565        let transaction_verified = self.transaction_verified.clone();
566        let results_sender = self.results_sender.clone();
567        let task = tokio::spawn(async move {
568            let fut = tokio::time::timeout(RATE_LIMIT_DELAY, fut);
569
570            // Prefer the cancel handle if both are ready.
571            let result = tokio::select! {
572                biased;
573                _ = &mut cancel_rx => {
574                    trace!("task cancelled prior to completion");
575                    metrics::counter!("mempool.cancelled.verify.tasks.total").increment(1);
576                    if let Some(rsp_tx) = rsp_tx.take() {
577                        let _ = rsp_tx.send(Err("verification cancelled".into()));
578                    }
579
580                    Ok(Err(Box::new((TransactionDownloadVerifyError::Cancelled, txid))))
581                }
582                verification = fut => {
583                    verification
584                        .inspect_err(|_elapsed| {
585                            if let Some(rsp_tx) = rsp_tx.take() {
586                                let _ = rsp_tx.send(Err("timeout waiting for verification result".into()));
587                            }
588                        })
589                        .map_err(|elapsed| (txid, elapsed))
590                        .map(|inner_result| {
591                            match inner_result {
592                                Ok((transaction, spent_mempool_outpoints, tip_height)) => Ok((transaction, spent_mempool_outpoints, tip_height, rsp_tx)),
593                                Err(boxed_err) => {
594                                    let (tx_verifier_error, tx_id) = *boxed_err;
595                                    if let Some(rsp_tx) = rsp_tx.take() {
596                                        let error_msg = format!(
597                                            "failed to validate tx: {tx_id}, error: {tx_verifier_error}"
598                                        );
599                                        let _ = rsp_tx.send(Err(error_msg.into()));
600                                    };
601
602                                    Err(Box::new((tx_verifier_error, tx_id)))
603                                }
604                            }
605                        })
606                },
607            };
608
609            // Queue before notifying: the woken mempool must see the result even if this task
610            // has not exited yet. A dropped downloader needs no notification.
611            //
612            // Only a verified transaction can be stored and announced. Failures wait for the next
613            // mempool request or the queue checker's backstop, so each one doesn't trigger its own
614            // queue check and mempool change.
615            let is_verified = matches!(result, Ok(Ok(_)));
616            if results_sender.send(result).is_ok() && is_verified {
617                transaction_verified.notify_one();
618            }
619        });
620
621        self.pending.push(task);
622        self.in_flight += 1;
623        assert!(
624            self.cancel_handles
625                .insert(txid, (cancel_tx, gossiped_tx_req, source))
626                .is_none(),
627            "transactions are only queued once"
628        );
629        if let Some(source) = source {
630            // The per-peer cap check above ensures this can't exceed
631            // `MAX_INBOUND_CONCURRENCY_PER_PEER`.
632            *self.pending_per_peer.entry(source.ip()).or_insert(0) += 1;
633        }
634
635        debug!(
636            ?txid,
637            queue_len = self.in_flight,
638            ?MAX_INBOUND_CONCURRENCY,
639            "queued transaction hash for download"
640        );
641        metrics::gauge!("mempool.currently.queued.transactions",).set(self.in_flight as f64);
642        metrics::counter!("mempool.queued.transactions.total").increment(1);
643
644        Ok(())
645    }
646
647    /// Cancel download/verification tasks of transactions with the
648    /// given transaction hash (see [`UnminedTxId::mined_id`]).
649    pub fn cancel(&mut self, mined_ids: &HashSet<transaction::Hash>) {
650        // TODO: this can be simplified with [`HashMap::drain_filter`] which
651        // is currently nightly-only experimental API.
652        let removed_txids: Vec<UnminedTxId> = self
653            .cancel_handles
654            .keys()
655            .filter(|txid| mined_ids.contains(&txid.mined_id()))
656            .cloned()
657            .collect();
658
659        for txid in removed_txids {
660            if let Some((cancel_tx, _gossip, source)) = self.cancel_handles.remove(&txid) {
661                let _ = cancel_tx.send(CancelDownloadAndVerify);
662                if let Some(source) = source {
663                    Self::release_peer_slot(&mut self.pending_per_peer, source);
664                }
665            }
666        }
667    }
668
669    /// Cancel all running tasks. Their admission slots remain reserved until results are consumed.
670    // Note: copied from zebrad/src/components/sync/downloads.rs
671    pub fn cancel_all(&mut self) {
672        // Replace the pending task list with an empty one and drop it.
673        let _ = std::mem::take(&mut self.pending);
674        // Signal cancellation to all running tasks.
675        // Since we already dropped the JoinHandles above, they should
676        // fail silently.
677        for (_hash, (cancel_tx, _gossip, _source)) in self.cancel_handles.drain() {
678            let _ = cancel_tx.send(CancelDownloadAndVerify);
679        }
680        self.pending_per_peer.clear();
681        assert!(self.pending.is_empty());
682        assert!(self.cancel_handles.is_empty());
683        metrics::gauge!("mempool.currently.queued.transactions",).set(self.in_flight as f64);
684    }
685
686    /// Decrement the per-host pending count for `source`'s IP, removing the entry
687    /// when it reaches zero.
688    fn release_peer_slot(pending_per_peer: &mut HashMap<IpAddr, usize>, source: SocketAddr) {
689        let ip = source.ip();
690        if let Some(count) = pending_per_peer.get_mut(&ip) {
691            *count = count.saturating_sub(1);
692            if *count == 0 {
693                pending_per_peer.remove(&ip);
694            }
695        }
696    }
697
698    /// Get the number of transactions whose results have not been consumed.
699    #[allow(dead_code)]
700    pub fn in_flight(&self) -> usize {
701        self.in_flight
702    }
703
704    /// Get a list of the currently pending transaction requests.
705    pub fn transaction_requests(&self) -> impl Iterator<Item = &Gossip> {
706        self.cancel_handles
707            .iter()
708            .map(|(_tx_id, (_handle, tx, _source))| tx)
709    }
710
711    /// Check if transaction is already in the best chain.
712    async fn transaction_in_best_chain(
713        state: &mut ZS,
714        txid: UnminedTxId,
715    ) -> Result<(), TransactionDownloadVerifyError> {
716        match state
717            .ready()
718            .await
719            .map_err(CloneError::from)
720            .map_err(TransactionDownloadVerifyError::StateError)?
721            .call(zs::Request::Transaction(txid.mined_id()))
722            .await
723        {
724            Ok(zs::Response::Transaction(None)) => Ok(()),
725            Ok(zs::Response::Transaction(Some(_))) => Err(TransactionDownloadVerifyError::InState),
726            Ok(_) => unreachable!("wrong response"),
727            Err(e) => Err(TransactionDownloadVerifyError::StateError(e.into())),
728        }?;
729
730        Ok(())
731    }
732}
733
734#[pinned_drop]
735impl<ZN, ZV, ZS> PinnedDrop for Downloads<ZN, ZV, ZS>
736where
737    ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
738    ZN::Future: Send,
739    ZV: Service<tx::MempoolRequest, Response = tx::MempoolResponse, Error = BoxError>
740        + Send
741        + Clone
742        + 'static,
743    ZV::Future: Send,
744    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
745    ZS::Future: Send,
746{
747    fn drop(mut self: Pin<&mut Self>) {
748        self.cancel_all();
749
750        metrics::gauge!("mempool.currently.queued.transactions").set(0 as f64);
751    }
752}
753
754#[cfg(test)]
755mod tests;