1use std::{
22 collections::HashSet,
23 future::Future,
24 iter,
25 ops::Bound,
26 pin::{pin, Pin},
27 sync::Arc,
28 task::{Context, Poll},
29};
30
31use chrono::{DateTime, Duration, Utc};
32use futures::{future::FutureExt, stream::Stream};
33use tokio::sync::{broadcast, mpsc, oneshot, Notify};
34use tower::{buffer::Buffer, timeout::Timeout, util::BoxService, Service};
35
36use zebra_chain::{
37 block::{self, Height},
38 chain_sync_status::ChainSyncStatus,
39 chain_tip::ChainTip,
40 parameters::{Network, NetworkUpgrade},
41 serialization::TrustedPreallocate,
42 transaction::{Transaction, UnminedTxId},
43};
44use zebra_consensus::{error::TransactionError, transaction};
45use zebra_network as zn;
46use zebra_node_services::mempool::{
47 CreatedOrSpent, Gossip, MempoolChange, MempoolTxSubscriber, Request, Response,
48};
49use zebra_state as zs;
50use zebra_state::{ChainTipChange, TipAction};
51
52use crate::components::sync::SyncStatus;
53
54pub mod config;
55mod crawler;
56pub mod downloads;
57mod error;
58pub mod gossip;
59mod pending_outputs;
60mod queue_checker;
61mod storage;
62
63#[cfg(test)]
64mod tests;
65
66pub use crate::BoxError;
67
68pub use config::Config;
69pub use crawler::Crawler;
70pub use error::MempoolError;
71pub use gossip::gossip_mempool_transaction_id;
72pub use queue_checker::QueueChecker;
73pub use storage::{
74 ExactTipRejectionError, SameEffectsChainRejectionError, SameEffectsTipRejectionError, Storage,
75};
76
77#[cfg(test)]
78pub use self::tests::UnboxMempoolError;
79
80use downloads::{
81 Downloads as TxDownloads, TransactionDownloadVerifyError, TRANSACTION_DOWNLOAD_TIMEOUT,
82 TRANSACTION_VERIFY_TIMEOUT,
83};
84
85type Outbound = Buffer<BoxService<zn::Request, zn::Response, zn::BoxError>, zn::Request>;
86type State = Buffer<BoxService<zs::Request, zs::Response, zs::BoxError>, zs::Request>;
87type TxVerifier = Buffer<
88 BoxService<transaction::MempoolRequest, transaction::MempoolResponse, TransactionError>,
89 transaction::MempoolRequest,
90>;
91type InboundTxDownloads = TxDownloads<Timeout<Outbound>, Timeout<TxVerifier>, State>;
92
93const BRANCH_ID_GRACE_PERIOD: Duration = Duration::minutes(50);
96
97const MAX_START_TIP_AGE: Duration = Duration::seconds(7_500);
103
104fn is_near_network_tip(
109 network: &Network,
110 latest_chain_tip: &impl ChainTip,
111 now: DateTime<Utc>,
112) -> bool {
113 !matches!(network, Network::Mainnet)
114 || latest_chain_tip
115 .best_tip_block_time()
116 .is_some_and(|block_time| now - block_time <= MAX_START_TIP_AGE)
117}
118
119fn adjusted_mempool_misbehavior_score(
121 error: &TransactionError,
122 transaction_upgrade: Option<NetworkUpgrade>,
123 verification_height: Height,
124 network: &Network,
125) -> u32 {
126 let is_grace_mismatch =
127 match (error, transaction_upgrade) {
128 (TransactionError::WrongConsensusBranchId, Some(_)) => true,
129 (TransactionError::Script(_), None) => true,
133 _ => false,
134 } && is_in_branch_id_grace_period(transaction_upgrade, verification_height, network);
135
136 let is_future_branch_id = matches!(error, TransactionError::WrongConsensusBranchId)
139 && transaction_upgrade
140 .and_then(|transaction_upgrade| transaction_upgrade.activation_height(network))
141 .is_some_and(|activation_height| activation_height > verification_height);
142
143 let is_tip_relative_lock_time = matches!(
146 error,
147 TransactionError::LockedUntilAfterBlockHeight(_)
148 | TransactionError::LockedUntilAfterBlockTime(_)
149 );
150
151 if is_grace_mismatch || is_future_branch_id || is_tip_relative_lock_time {
152 0
153 } else {
154 error.mempool_misbehavior_score()
155 }
156}
157
158fn is_in_branch_id_grace_period(
162 transaction_upgrade: Option<NetworkUpgrade>,
163 height: Height,
164 network: &Network,
165) -> bool {
166 let activations = network.activation_list();
167 let Some((¤t_height, ¤t)) = activations.range(..=height).next_back() else {
168 return false;
169 };
170 let grace_blocks =
171 BRANCH_ID_GRACE_PERIOD.num_seconds() / current.target_spacing().num_seconds();
172 let matches = |upgrade| transaction_upgrade.is_none_or(|tx_upgrade| tx_upgrade == upgrade);
173
174 let previous = activations.range(..current_height).next_back();
175 let next = activations
176 .range((Bound::Excluded(height), Bound::Unbounded))
177 .next();
178
179 previous
180 .is_some_and(|(_, &previous)| matches(previous) && height - current_height < grace_blocks)
181 || next.is_some_and(|(&next_height, &next)| {
182 matches(next) && next_height - height <= grace_blocks
183 })
184}
185
186#[allow(clippy::large_enum_variant)]
193#[derive(Default)]
194enum ActiveState {
195 #[default]
197 Disabled,
198
199 Enabled {
201 storage: Storage,
208
209 tx_downloads: Pin<Box<InboundTxDownloads>>,
211
212 last_seen_tip_hash: block::Hash,
216 },
217}
218
219impl ActiveState {
220 fn take(&mut self) -> Self {
222 std::mem::take(self)
223 }
224
225 fn transaction_retry_requests(&self) -> Vec<Gossip> {
227 match self {
228 ActiveState::Disabled => Vec::new(),
229 ActiveState::Enabled {
230 storage,
231 tx_downloads,
232 ..
233 } => {
234 let mut transactions = Vec::new();
235
236 let storage = storage
237 .transactions()
238 .values()
239 .map(|tx| tx.transaction.clone().into());
240 transactions.extend(storage);
241
242 let pending = tx_downloads.transaction_requests().cloned();
243 transactions.extend(pending);
244
245 transactions
246 }
247 }
248 }
249
250 #[cfg(feature = "progress-bar")]
253 fn queued_transaction_count(&self) -> usize {
254 match self {
255 ActiveState::Disabled => 0,
256 ActiveState::Enabled { tx_downloads, .. } => tx_downloads.in_flight(),
257 }
258 }
259
260 #[cfg(feature = "progress-bar")]
262 fn transaction_count(&self) -> usize {
263 match self {
264 ActiveState::Disabled => 0,
265 ActiveState::Enabled { storage, .. } => storage.transaction_count(),
266 }
267 }
268
269 #[cfg(feature = "progress-bar")]
272 fn total_cost(&self) -> u64 {
273 match self {
274 ActiveState::Disabled => 0,
275 ActiveState::Enabled { storage, .. } => storage.total_cost(),
276 }
277 }
278
279 #[cfg(feature = "progress-bar")]
284 pub fn total_serialized_size(&self) -> usize {
285 match self {
286 ActiveState::Disabled => 0,
287 ActiveState::Enabled { storage, .. } => storage.total_serialized_size(),
288 }
289 }
290
291 #[cfg(feature = "progress-bar")]
294 fn rejected_transaction_count(&mut self) -> usize {
295 match self {
296 ActiveState::Disabled => 0,
297 ActiveState::Enabled { storage, .. } => storage.rejected_transaction_count(),
298 }
299 }
300}
301
302pub struct Mempool {
308 network: Network,
310
311 config: Config,
313
314 active_state: ActiveState,
316
317 sync_status: SyncStatus,
319
320 #[cfg(test)]
322 skip_tip_age_check: bool,
323
324 debug_enable_at_height: Option<Height>,
326
327 latest_chain_tip: zs::LatestChainTip,
329
330 chain_tip_change: ChainTipChange,
333
334 outbound: Outbound,
337
338 state: State,
341
342 tx_verifier: TxVerifier,
345
346 transaction_sender: broadcast::Sender<MempoolChange>,
349
350 misbehavior_sender: mpsc::Sender<zn::MisbehaviorReport>,
352
353 #[cfg(feature = "progress-bar")]
358 queued_count_bar: Option<howudoin::Tx>,
359
360 #[cfg(feature = "progress-bar")]
363 transaction_count_bar: Option<howudoin::Tx>,
364
365 #[cfg(feature = "progress-bar")]
368 transaction_cost_bar: Option<howudoin::Tx>,
369
370 #[cfg(feature = "progress-bar")]
373 rejected_count_bar: Option<howudoin::Tx>,
374
375 transaction_verified: Arc<Notify>,
377}
378
379impl Mempool {
380 #[allow(clippy::too_many_arguments)]
385 pub(crate) fn new(
386 network: &Network,
387 config: &Config,
388 outbound: Outbound,
389 state: State,
390 tx_verifier: TxVerifier,
391 sync_status: SyncStatus,
392 latest_chain_tip: zs::LatestChainTip,
393 chain_tip_change: ChainTipChange,
394 misbehavior_sender: mpsc::Sender<zn::MisbehaviorReport>,
395 ) -> (Self, MempoolTxSubscriber, Arc<Notify>) {
396 let (transaction_sender, _) =
397 tokio::sync::broadcast::channel(gossip::MAX_CHANGES_BEFORE_SEND * 2);
398 let transaction_subscriber = MempoolTxSubscriber::new(transaction_sender.clone());
399 let transaction_verified = Arc::new(Notify::new());
400
401 let mut service = Mempool {
402 network: network.clone(),
403 config: config.clone(),
404 active_state: ActiveState::Disabled,
405 sync_status,
406 #[cfg(test)]
407 skip_tip_age_check: false,
408 debug_enable_at_height: config.debug_enable_at_height.map(Height),
409 latest_chain_tip,
410 chain_tip_change,
411 outbound,
412 state,
413 tx_verifier,
414 transaction_sender,
415 misbehavior_sender,
416 transaction_verified: transaction_verified.clone(),
417 #[cfg(feature = "progress-bar")]
418 queued_count_bar: None,
419 #[cfg(feature = "progress-bar")]
420 transaction_count_bar: None,
421 #[cfg(feature = "progress-bar")]
422 transaction_cost_bar: None,
423 #[cfg(feature = "progress-bar")]
424 rejected_count_bar: None,
425 };
426
427 let is_caught_up_to_start = service.is_caught_up_to_start();
430 service.update_state(None, is_caught_up_to_start);
431
432 (service, transaction_subscriber, transaction_verified)
433 }
434
435 fn is_enabled_by_debug(&self) -> bool {
437 let mut is_debug_enabled = false;
438
439 if self.debug_enable_at_height.is_none() {
441 return is_debug_enabled;
442 }
443
444 let enable_at_height = self
445 .debug_enable_at_height
446 .expect("unexpected debug_enable_at_height: just checked for None");
447
448 if let Some(best_tip_height) = self.latest_chain_tip.best_tip_height() {
449 is_debug_enabled = best_tip_height >= enable_at_height;
450
451 if is_debug_enabled && !self.is_enabled() {
452 info!(
453 ?best_tip_height,
454 ?enable_at_height,
455 "enabling mempool for debugging"
456 );
457 }
458 }
459
460 is_debug_enabled
461 }
462
463 fn is_caught_up_to_start(&self) -> bool {
465 #[cfg(test)]
466 let skip_tip_age_check = self.skip_tip_age_check;
467 #[cfg(not(test))]
468 let skip_tip_age_check = false;
469
470 let is_near_tip = self.sync_status.is_close_to_tip()
471 && (skip_tip_age_check
472 || is_near_network_tip(&self.network, &self.latest_chain_tip, Utc::now()));
473
474 is_near_tip || self.is_enabled_by_debug()
475 }
476
477 fn enable_at_tip(&mut self, tip_action: &TipAction) {
480 let (last_seen_tip_hash, _) = tip_action.best_tip_hash_and_height();
481
482 let tx_downloads = Box::pin(
483 TxDownloads::new(
484 Timeout::new(self.outbound.clone(), TRANSACTION_DOWNLOAD_TIMEOUT),
485 Timeout::new(self.tx_verifier.clone(), TRANSACTION_VERIFY_TIMEOUT),
486 self.state.clone(),
487 self.transaction_verified.clone(),
488 )
489 .with_max_datacarrier_bytes(
490 self.config
491 .max_datacarrier_bytes
492 .unwrap_or(config::DEFAULT_MAX_DATACARRIER_BYTES),
493 ),
494 );
495 self.active_state = ActiveState::Enabled {
496 storage: storage::Storage::new(&self.config),
497 tx_downloads,
498 last_seen_tip_hash,
499 };
500 }
501
502 fn update_state(
514 &mut self,
515 tip_action: Option<&TipAction>,
516 is_caught_up_to_start: bool,
517 ) -> bool {
518 match (is_caught_up_to_start, self.is_enabled(), tip_action) {
521 (false, false, _) | (true, true, _) | (true, false, None) => return false,
523
524 (true, false, Some(tip_action)) => {
526 info!(
527 tip_height = ?tip_action.best_tip_height(),
528 "activating mempool: Zebra is close to the tip"
529 );
530
531 self.enable_at_tip(tip_action);
532 }
533
534 (false, true, _) => {
543 return false;
544 }
545 };
546
547 true
548 }
549
550 pub fn is_enabled(&self) -> bool {
552 match self.active_state {
553 ActiveState::Disabled => false,
554 ActiveState::Enabled { .. } => true,
555 }
556 }
557
558 fn remove_expired_from_peer_list(
560 send_to_peers_ids: &HashSet<UnminedTxId>,
561 expired_transactions: &HashSet<UnminedTxId>,
562 ) -> HashSet<UnminedTxId> {
563 send_to_peers_ids
564 .iter()
565 .filter(|id| !expired_transactions.contains(id))
566 .copied()
567 .collect()
568 }
569
570 fn update_metrics(&mut self) {
572 #[cfg(feature = "progress-bar")]
574 if matches!(howudoin::cancelled(), Some(true)) {
575 self.disable_metrics();
576 return;
577 }
578
579 #[cfg(feature = "progress-bar")]
581 if self.is_enabled()
582 && (self.queued_count_bar.is_none()
583 || self.transaction_count_bar.is_none()
584 || self.transaction_cost_bar.is_none()
585 || self.rejected_count_bar.is_none())
586 {
587 let _max_transaction_count = self.config.tx_cost_limit
588 / zebra_chain::transaction::MEMPOOL_TRANSACTION_COST_THRESHOLD;
589
590 let transaction_count_bar = *howudoin::new_root()
591 .label("Mempool Transactions")
592 .set_pos(0u64);
593 let transaction_cost_bar = howudoin::new_with_parent(transaction_count_bar.id())
596 .label("Mempool Cost")
597 .set_pos(0u64)
598 .fmt_as_bytes(true);
600
601 let queued_count_bar = *howudoin::new_with_parent(transaction_cost_bar.id())
602 .label("Mempool Queue")
603 .set_pos(0u64);
604 let rejected_count_bar = *howudoin::new_with_parent(queued_count_bar.id())
609 .label("Mempool Rejects")
610 .set_pos(0u64);
611 self.transaction_count_bar = Some(transaction_count_bar);
616 self.transaction_cost_bar = Some(transaction_cost_bar);
617 self.queued_count_bar = Some(queued_count_bar);
618 self.rejected_count_bar = Some(rejected_count_bar);
619 }
620
621 #[cfg(feature = "progress-bar")]
623 if let (
624 Some(queued_count_bar),
625 Some(transaction_count_bar),
626 Some(transaction_cost_bar),
627 Some(rejected_count_bar),
628 ) = (
629 self.queued_count_bar,
630 self.transaction_count_bar,
631 self.transaction_cost_bar,
632 self.rejected_count_bar,
633 ) {
634 let queued_count = self.active_state.queued_transaction_count();
635 let transaction_count = self.active_state.transaction_count();
636
637 let transaction_cost = self.active_state.total_cost();
638 let transaction_size = self.active_state.total_serialized_size();
639 let transaction_size =
640 indicatif::HumanBytes(transaction_size.try_into().expect("fits in u64"));
641
642 let rejected_count = self.active_state.rejected_transaction_count();
643
644 queued_count_bar.set_pos(u64::try_from(queued_count).expect("fits in u64"));
645
646 transaction_count_bar.set_pos(u64::try_from(transaction_count).expect("fits in u64"));
647
648 transaction_cost_bar
653 .set_pos(transaction_cost)
654 .desc(format!("Actual size {transaction_size}"));
655
656 rejected_count_bar.set_pos(u64::try_from(rejected_count).expect("fits in u64"));
657 }
658 }
659
660 fn disable_metrics(&self) {
662 #[cfg(feature = "progress-bar")]
663 {
664 if let Some(bar) = self.queued_count_bar {
665 bar.close()
666 }
667 if let Some(bar) = self.transaction_count_bar {
668 bar.close()
669 }
670 if let Some(bar) = self.transaction_cost_bar {
671 bar.close()
672 }
673 if let Some(bar) = self.rejected_count_bar {
674 bar.close()
675 }
676 }
677 }
678}
679
680impl Service<Request> for Mempool {
681 type Response = Response;
682 type Error = BoxError;
683 type Future =
684 Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
685
686 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
687 let is_caught_up_to_start = self.is_caught_up_to_start();
688 let should_check_tip = self.is_enabled() || is_caught_up_to_start;
689 let tip_action = should_check_tip
690 .then(|| self.chain_tip_change.last_tip_change())
691 .flatten();
692
693 let is_state_changed = self.update_state(tip_action.as_ref(), is_caught_up_to_start);
695
696 tracing::trace!(is_enabled = ?self.is_enabled(), ?is_state_changed, "started polling the mempool...");
697
698 if !self.is_enabled() {
701 self.update_metrics();
702
703 return Poll::Ready(Ok(()));
704 }
705
706 let reset_tip_action = match tip_action.as_ref() {
711 Some(reset_tip_action @ TipAction::Reset { .. }) if !is_state_changed => {
712 Some(reset_tip_action)
713 }
714 _ => None,
715 };
716
717 if let Some(reset_tip_action) = reset_tip_action {
718 info!(
719 tip_height = ?reset_tip_action.best_tip_height(),
720 "resetting mempool: switched best chain, skipped blocks, or activated network upgrade"
721 );
722
723 let previous_state = self.active_state.take();
724 let tx_retries = previous_state.transaction_retry_requests();
725
726 std::mem::drop(previous_state);
733
734 self.enable_at_tip(reset_tip_action);
742
743 if let ActiveState::Enabled { tx_downloads, .. } = &mut self.active_state {
746 info!(
747 transactions = tx_retries.len(),
748 "re-verifying mempool transactions after a chain fork"
749 );
750
751 for tx in tx_retries {
752 let _result = tx_downloads.download_if_needed_and_verify(tx, None, None);
755 }
756 }
757
758 self.update_metrics();
759
760 return Poll::Ready(Ok(()));
761 }
762
763 if let ActiveState::Enabled {
764 storage,
765 tx_downloads,
766 last_seen_tip_hash,
767 } = &mut self.active_state
768 {
769 let mut send_to_peers_ids = HashSet::<_>::new();
771 let mut invalidated_ids = HashSet::<_>::new();
772 let mut mined_mempool_ids = HashSet::<_>::new();
773
774 let best_tip_height = self.latest_chain_tip.best_tip_height();
775
776 while let Poll::Ready(Some(result)) = pin!(&mut *tx_downloads).poll_next(cx) {
778 match result {
779 Ok(Ok((tx, spent_mempool_outpoints, expected_tip_height, rsp_tx))) => {
780 if best_tip_height == expected_tip_height {
791 let tx_id = tx.transaction.id;
792 let insert_result =
793 storage.insert(tx, spent_mempool_outpoints, best_tip_height);
794
795 tracing::trace!(
796 ?insert_result,
797 "got Ok(_) transaction verify, tried to store",
798 );
799
800 if let Ok(inserted_id) = insert_result {
801 send_to_peers_ids.insert(inserted_id);
803 } else {
804 invalidated_ids.insert(tx_id);
805 }
806
807 if let Some(rsp_tx) = rsp_tx {
809 let _ = rsp_tx
810 .send(insert_result.map(|_| ()).map_err(|err| err.into()));
811 }
812 } else {
813 tracing::trace!("chain grew during tx verification, retrying ..",);
814
815 let _result = tx_downloads.download_if_needed_and_verify(
817 tx.transaction.into(),
818 None,
819 rsp_tx,
820 );
821 }
822 }
823 Ok(Err(boxed_err)) => {
824 let (tx_id, error) = *boxed_err;
825 if let TransactionDownloadVerifyError::Invalid {
826 error,
827 advertiser_addr: Some(advertiser_addr),
828 transaction_upgrade,
829 verification_height,
830 } = &error
831 {
832 let score = adjusted_mempool_misbehavior_score(
833 error,
834 *transaction_upgrade,
835 *verification_height,
836 &self.network,
837 );
838
839 if score != 0 {
840 let _ =
841 self.misbehavior_sender.try_send(zn::MisbehaviorReport::new(
842 *advertiser_addr,
843 score,
844 format!("invalid mempool transaction {tx_id}: {error}"),
845 ));
846 }
847 };
848
849 tracing::debug!(?tx_id, ?error, "mempool transaction failed to verify");
850
851 metrics::counter!("mempool.failed.verify.tasks.total", "reason" => error.metric_label()).increment(1);
852
853 invalidated_ids.insert(tx_id);
854 storage.reject_if_needed(tx_id, error);
855 }
856 Err((tx_id, _elapsed)) => {
857 tracing::info!(
858 ?tx_id,
859 "mempool transaction failed to verify due to timeout"
860 );
861
862 invalidated_ids.insert(tx_id);
863
864 metrics::counter!("mempool.failed.verify.tasks.total", "reason" => "timeout").increment(1);
865 }
866 };
867 }
868
869 if let Some(TipAction::Grow { block }) = tip_action {
871 tracing::trace!(block_height = ?block.height, "handling blocks added to tip");
872 *last_seen_tip_hash = block.hash;
873 let cleanup_start = std::time::Instant::now();
874
875 let mined_ids = block.transaction_hashes.iter().cloned().collect();
878 tx_downloads.cancel(&mined_ids);
879 storage.clear_mined_dependencies(&mined_ids);
880
881 let storage::RemovedTransactionIds { mined, invalidated } =
882 storage.reject_and_remove_same_effects(&mined_ids, block.transactions);
883
884 storage.clear_tip_rejections();
887 metrics::histogram!("mempool.tip_cleanup.duration_seconds")
888 .record(cleanup_start.elapsed().as_secs_f64());
889
890 mined_mempool_ids.extend(mined);
891 invalidated_ids.extend(invalidated);
892 }
893
894 if let Some(tip_height) = best_tip_height {
899 let expiry_start = std::time::Instant::now();
900 let expired_transactions = storage.remove_expired_transactions(tip_height);
901 metrics::histogram!("mempool.expiry.duration_seconds")
902 .record(expiry_start.elapsed().as_secs_f64());
903 send_to_peers_ids =
905 Self::remove_expired_from_peer_list(&send_to_peers_ids, &expired_transactions);
906
907 if !expired_transactions.is_empty() {
908 tracing::debug!(
909 ?expired_transactions,
910 "removed expired transactions from the mempool",
911 );
912
913 invalidated_ids.extend(expired_transactions);
914 }
915 }
916
917 if !send_to_peers_ids.is_empty() {
919 tracing::trace!(
920 ?send_to_peers_ids,
921 "sending new transactions to peers and RPC listeners"
922 );
923
924 let _ = self
932 .transaction_sender
933 .send(MempoolChange::added(send_to_peers_ids));
934 }
935
936 if !invalidated_ids.is_empty() {
938 tracing::trace!(
939 ?invalidated_ids,
940 "sending invalidated transactions to RPC listeners"
941 );
942
943 let _ = self
946 .transaction_sender
947 .send(MempoolChange::invalidated(invalidated_ids));
948 }
949
950 if !mined_mempool_ids.is_empty() {
952 tracing::trace!(
953 ?mined_mempool_ids,
954 "sending mined transactions to RPC listeners"
955 );
956
957 let _ = self
960 .transaction_sender
961 .send(MempoolChange::mined(mined_mempool_ids));
962 }
963 }
964
965 self.update_metrics();
966
967 Poll::Ready(Ok(()))
968 }
969
970 #[instrument(name = "mempool", skip(self, req))]
975 fn call(&mut self, req: Request) -> Self::Future {
976 match &mut self.active_state {
977 ActiveState::Enabled {
978 storage,
979 tx_downloads,
980 last_seen_tip_hash,
981 } => match req {
982 Request::TransactionIds => {
984 trace!(?req, "got mempool request");
985
986 let res: HashSet<_> = storage.tx_ids().collect();
987
988 trace!(?req, res_count = ?res.len(), "answered mempool request");
989
990 async move { Ok(Response::TransactionIds(res)) }.boxed()
991 }
992
993 Request::TransactionsById(ref ids) => {
994 trace!(?req, "got mempool request");
995
996 let res: Vec<_> = storage.transactions_exact(ids.clone()).cloned().collect();
997
998 trace!(?req, res_count = ?res.len(), "answered mempool request");
999
1000 async move { Ok(Response::Transactions(res)) }.boxed()
1001 }
1002 Request::TransactionsByMinedId(ref ids) => {
1003 trace!(?req, "got mempool request");
1004
1005 let res: Vec<_> = storage
1006 .transactions_same_effects(ids.clone())
1007 .cloned()
1008 .collect();
1009
1010 trace!(?req, res_count = ?res.len(), "answered mempool request");
1011
1012 async move { Ok(Response::Transactions(res)) }.boxed()
1013 }
1014 Request::VerifiedTransactionsForBlock {
1015 transaction_hashes,
1016 parent_hash,
1017 } => {
1018 let transactions = if *last_seen_tip_hash == parent_hash
1019 && transaction_hashes.len()
1020 <= usize::try_from(Transaction::max_allocation())
1021 .expect("the block size keeps this limit far below usize::MAX")
1022 {
1023 transaction_hashes
1024 .iter()
1025 .filter_map(|hash| {
1026 storage
1027 .transactions()
1028 .get(hash)
1029 .map(|tx| (*hash, tx.clone()))
1030 })
1031 .collect()
1032 } else {
1033 Default::default()
1034 };
1035
1036 async move { Ok(Response::VerifiedTransactionsForBlock(transactions)) }.boxed()
1037 }
1038 Request::TransactionWithDepsByMinedId(tx_id) => {
1039 trace!(?req, "got mempool request");
1040
1041 let res = if let Some((transaction, dependencies)) =
1042 storage.transaction_with_deps(tx_id)
1043 {
1044 Ok(Response::TransactionWithDeps {
1045 transaction,
1046 dependencies,
1047 })
1048 } else {
1049 Err("transaction not found in mempool".into())
1050 };
1051
1052 trace!(?req, ?res, "answered mempool request");
1053
1054 async move { res }.boxed()
1055 }
1056
1057 Request::AwaitOutput(outpoint) => {
1058 trace!(?req, "got mempool request");
1059
1060 let response_fut = storage.pending_outputs.queue(outpoint);
1061
1062 if let Some(output) = storage.created_output(&outpoint) {
1063 storage.pending_outputs.respond(&outpoint, output)
1064 }
1065
1066 trace!("answered mempool request");
1067
1068 response_fut.boxed()
1069 }
1070
1071 Request::FullTransactions => {
1072 trace!(?req, "got mempool request");
1073
1074 let transactions: Vec<_> = storage.transactions().values().cloned().collect();
1075 let transaction_dependencies = storage.transaction_dependencies().clone();
1076
1077 trace!(?req, transactions_count = ?transactions.len(), "answered mempool request");
1078
1079 let response = Response::FullTransactions {
1080 transactions,
1081 transaction_dependencies,
1082 last_seen_tip_hash: *last_seen_tip_hash,
1083 };
1084
1085 async move { Ok(response) }.boxed()
1086 }
1087
1088 Request::RejectedTransactionIds(ref ids) => {
1089 trace!(?req, "got mempool request");
1090
1091 let res = storage.rejected_transactions(ids.clone()).collect();
1092
1093 trace!(?req, ?res, "answered mempool request");
1094
1095 async move { Ok(Response::RejectedTransactionIds(res)) }.boxed()
1096 }
1097
1098 Request::Queue(gossiped_txs) => {
1100 trace!(req_count = ?gossiped_txs.len(), "got mempool Queue request");
1101
1102 let rsp: Vec<Result<oneshot::Receiver<Result<(), BoxError>>, BoxError>> =
1103 gossiped_txs
1104 .into_iter()
1105 .map(
1106 |gossiped_tx| -> Result<
1107 oneshot::Receiver<Result<(), BoxError>>,
1108 MempoolError,
1109 > {
1110 let (rsp_tx, rsp_rx) = oneshot::channel();
1111 storage.should_download_or_verify(gossiped_tx.id())?;
1112 tx_downloads.download_if_needed_and_verify(
1113 gossiped_tx,
1114 None,
1115 Some(rsp_tx),
1116 )?;
1117
1118 Ok(rsp_rx)
1119 },
1120 )
1121 .map(|result| result.map_err(BoxError::from))
1122 .collect();
1123
1124 self.update_metrics();
1126
1127 async move { Ok(Response::Queued(rsp)) }.boxed()
1128 }
1129
1130 Request::QueueFromPeer { candidates, source } => {
1134 trace!(req_count = ?candidates.len(), ?source, "got mempool QueueFromPeer request");
1135
1136 for candidate in candidates {
1137 if storage.should_download_or_verify(candidate.id()).is_err() {
1138 continue;
1139 }
1140 let _ = tx_downloads.download_if_needed_and_verify(
1141 candidate,
1142 Some(source),
1143 None,
1144 );
1145 }
1146
1147 self.update_metrics();
1148
1149 async move { Ok(Response::Queued(Vec::new())) }.boxed()
1150 }
1151
1152 Request::CheckForVerifiedTransactions => {
1154 trace!(?req, "got mempool request");
1155
1156 storage.pending_outputs.prune();
1158
1159 async move { Ok(Response::CheckedForVerifiedTransactions) }.boxed()
1161 }
1162
1163 Request::QueueStats => {
1167 trace!(?req, "got mempool request");
1168
1169 let size = storage.transaction_count();
1170
1171 let bytes = storage.total_serialized_size();
1172
1173 let usage = bytes; let fully_notified = None;
1177
1178 trace!(size, bytes, usage, "answered mempool request");
1179
1180 async move {
1181 Ok(Response::QueueStats {
1182 size,
1183 bytes,
1184 usage,
1185 fully_notified,
1186 })
1187 }
1188 .boxed()
1189 }
1190 Request::UnspentOutput(outpoint) => {
1191 trace!(?req, "got mempool request");
1192
1193 if storage.has_spent_outpoint(&outpoint) {
1194 trace!(?req, "answered mempool request");
1195
1196 return async move {
1197 Ok(Response::TransparentOutput(Some(CreatedOrSpent::Spent)))
1198 }
1199 .boxed();
1200 }
1201
1202 if let Some((tx_version, output)) = storage
1203 .transactions()
1204 .get(&outpoint.hash)
1205 .map(|tx| tx.transaction.transaction.clone())
1206 .and_then(|tx| {
1207 tx.outputs()
1208 .get(outpoint.index as usize)
1209 .map(|output| (tx.version(), output.clone()))
1210 })
1211 {
1212 trace!(?req, "answered mempool request");
1213
1214 let last_seen_hash = *last_seen_tip_hash;
1215 return async move {
1216 Ok(Response::TransparentOutput(Some(CreatedOrSpent::Created {
1217 output,
1218 tx_version,
1219 last_seen_hash,
1220 })))
1221 }
1222 .boxed();
1223 }
1224
1225 trace!(?req, "answered mempool request");
1226
1227 async move { Ok(Response::TransparentOutput(None)) }.boxed()
1228 }
1229 },
1230 ActiveState::Disabled => {
1231 trace!("got mempool request while mempool is disabled");
1234
1235 let resp = match req {
1240 Request::TransactionIds => Response::TransactionIds(Default::default()),
1242
1243 Request::TransactionsById(_) => Response::Transactions(Default::default()),
1244 Request::TransactionsByMinedId(_) => Response::Transactions(Default::default()),
1245 Request::VerifiedTransactionsForBlock { .. } => {
1246 Response::VerifiedTransactionsForBlock(Default::default())
1247 }
1248 Request::TransactionWithDepsByMinedId(_)
1249 | Request::AwaitOutput(_)
1250 | Request::UnspentOutput(_) => {
1251 return async move {
1252 Err("mempool is not active: wait for Zebra to sync to the tip".into())
1253 }
1254 .boxed()
1255 }
1256
1257 Request::FullTransactions => {
1258 return async move {
1259 Err("mempool is not active: wait for Zebra to sync to the tip".into())
1260 }
1261 .boxed()
1262 }
1263
1264 Request::RejectedTransactionIds(_) => {
1265 Response::RejectedTransactionIds(Default::default())
1266 }
1267
1268 Request::Queue(gossiped_txs) => Response::Queued(
1270 iter::repeat_n(MempoolError::Disabled, gossiped_txs.len())
1273 .map(BoxError::from)
1274 .map(Err)
1275 .collect(),
1276 ),
1277
1278 Request::QueueFromPeer { .. } => Response::Queued(Vec::new()),
1280
1281 Request::CheckForVerifiedTransactions => {
1284 Response::CheckedForVerifiedTransactions
1286 }
1287
1288 Request::QueueStats => Response::QueueStats {
1290 size: 0,
1291 bytes: 0,
1292 usage: 0,
1293 fully_notified: None,
1294 },
1295 };
1296
1297 async move { Ok(resp) }.boxed()
1298 }
1299 }
1300 }
1301}
1302
1303impl Drop for Mempool {
1304 fn drop(&mut self) {
1305 self.disable_metrics();
1306 }
1307}