1use 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
76pub(crate) const TRANSACTION_DOWNLOAD_TIMEOUT: Duration = BLOCK_DOWNLOAD_TIMEOUT;
82
83pub(crate) const TRANSACTION_VERIFY_TIMEOUT: Duration = BLOCK_VERIFY_TIMEOUT;
91
92pub const MAX_INBOUND_CONCURRENCY: usize = 500;
116
117pub const MAX_INBOUND_CONCURRENCY_PER_PEER: usize = 5;
126
127#[derive(Copy, Clone, Debug, Eq, PartialEq)]
129struct CancelDownloadAndVerify;
130
131#[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 transaction_upgrade: Option<NetworkUpgrade>,
153 verification_height: Height,
155 },
156
157 #[error("transaction is non-standard: {0}")]
158 NonStandard(NonStandardTransactionError),
159}
160
161impl TransactionDownloadVerifyError {
162 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
175type 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#[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 network: ZN,
208
209 verifier: ZV,
211
212 state: ZS,
214
215 max_datacarrier_bytes: u32,
217
218 #[pin]
221 pending: FuturesUnordered<JoinHandle<()>>,
222
223 results: mpsc::UnboundedReceiver<VerifyResult>,
225
226 results_sender: mpsc::UnboundedSender<VerifyResult>,
228
229 in_flight: usize,
231
232 cancel_handles: HashMap<
237 UnminedTxId,
238 (
239 oneshot::Sender<CancelDownloadAndVerify>,
240 Gossip,
241 Option<SocketAddr>,
242 ),
243 >,
244
245 pending_per_peer: HashMap<IpAddr, usize>,
258
259 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 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 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 (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 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 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 #[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 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 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 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 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 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 .map_err(move |e| Box::new((e, txid)))
558 .inspect(move |result| {
559 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 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 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 *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 pub fn cancel(&mut self, mined_ids: &HashSet<transaction::Hash>) {
650 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 pub fn cancel_all(&mut self) {
672 let _ = std::mem::take(&mut self.pending);
674 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 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 #[allow(dead_code)]
700 pub fn in_flight(&self) -> usize {
701 self.in_flight
702 }
703
704 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 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;