Skip to main content

zebrad/components/
mempool.rs

1//! Zebra mempool.
2//!
3//! A zebrad application component that manages the active collection, reception,
4//! gossip, verification, in-memory storage, eviction, and rejection of unmined Zcash
5//! transactions (those that have not been confirmed in a mined block on the
6//! blockchain).
7//!
8//! Major parts of the mempool include:
9//!  * [Mempool Service][`Mempool`]
10//!    * activates when the syncer is near the chain tip
11//!    * spawns [download and verify tasks][`downloads::Downloads`] for each crawled or gossiped transaction
12//!    * handles in-memory [storage][`storage::Storage`] of unmined transactions
13//!  * [Crawler][`crawler::Crawler`]
14//!    * runs in the background to periodically poll peers for fresh unmined transactions
15//!  * [Queue Checker][`queue_checker::QueueChecker`]
16//!    * runs in the background, polling the mempool to store newly verified transactions
17//!  * [Transaction Gossip Task][`gossip::gossip_mempool_transaction_id`]
18//!    * runs in the background and gossips newly added mempool transactions
19//!      to peers
20
21use 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
93/// The wall-clock window around a network upgrade activation where an adjacent upgrade's branch ID
94/// receives no peer score: 40 blocks at 75 seconds, 120 blocks at ZIP 218's 25 seconds.
95const BRANCH_ID_GRACE_PERIOD: Duration = Duration::minutes(50);
96
97/// The oldest best tip at which the mempool can start on Mainnet.
98///
99/// Short sync batches don't show that Zebra is near the network tip, because a node with few
100/// useful peers also gets short batches. This matches the tip age limit `getblocktemplate`
101/// applies on Mainnet, so the mempool is active whenever the RPC builds templates.
102const MAX_START_TIP_AGE: Duration = Duration::seconds(7_500);
103
104/// Returns `true` if the best tip is recent enough to start the mempool on `network` at `now`.
105///
106/// Test networks accept any tip age, as `getblocktemplate` does, so miners can restart a
107/// network that has stalled for longer than [`MAX_START_TIP_AGE`].
108fn 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
119/// Returns the mempool peer score after applying branch ID activation policy.
120fn 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            // V4 and older transactions commit to the branch ID only in their signatures, so one
130            // signed for an adjacent upgrade fails its scripts instead. zcashd checks the previous
131            // branch ID explicitly; Zebra doesn't, so it forgives any script failure in the window.
132            (TransactionError::Script(_), None) => true,
133            _ => false,
134        } && is_in_branch_id_grace_period(transaction_upgrade, verification_height, network);
135
136    // A branch ID for an upgrade that activates above our tip is valid on a chain that is ahead
137    // of ours, for example while this node is still syncing, so a peer can honestly relay it.
138    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    // Lock times are checked against our own tip, so a peer whose tip is ahead can honestly
144    // relay a transaction we reject.
145    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
158/// Returns `true` if `transaction_upgrade` activates immediately before or after the upgrade
159/// current at `height` on `network`, and `height` is within the grace window of that boundary.
160/// `None` matches either adjacent upgrade.
161fn 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((&current_height, &current)) = 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/// The state of the mempool.
187///
188/// Indicates whether it is enabled or disabled and, if enabled, contains
189/// the necessary data to run it.
190//
191// Zebra only has one mempool, so the enum variant size difference doesn't matter.
192#[allow(clippy::large_enum_variant)]
193#[derive(Default)]
194enum ActiveState {
195    /// The Mempool is disabled.
196    #[default]
197    Disabled,
198
199    /// The Mempool is enabled.
200    Enabled {
201        /// The Mempool storage itself.
202        ///
203        /// # Correctness
204        ///
205        /// Only components internal to the [`Mempool`] struct are allowed to
206        /// inject transactions into `storage`, as transactions must be verified beforehand.
207        storage: Storage,
208
209        /// The transaction download and verify stream.
210        tx_downloads: Pin<Box<InboundTxDownloads>>,
211
212        /// Last seen chain tip hash that mempool transactions have been verified against.
213        ///
214        /// In some tests, this is initialized to the latest chain tip, then updated in `poll_ready()` before each request.
215        last_seen_tip_hash: block::Hash,
216    },
217}
218
219impl ActiveState {
220    /// Returns the current state, leaving [`Self::Disabled`] in its place.
221    fn take(&mut self) -> Self {
222        std::mem::take(self)
223    }
224
225    /// Returns a list of requests that will retry every stored and pending transaction.
226    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    /// Returns the number of pending transactions waiting for download or verify,
251    /// or zero if the mempool is disabled.
252    #[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    /// Returns the number of transactions in storage, or zero if the mempool is disabled.
261    #[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    /// Returns the cost of the transactions in the mempool, according to ZIP-401.
270    /// Returns zero if the mempool is disabled.
271    #[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    /// Returns the total serialized size of the verified transactions in the set,
280    /// or zero if the mempool is disabled.
281    ///
282    /// See [`Storage::total_serialized_size()`] for details.
283    #[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    /// Returns the number of rejected transaction hashes in storage,
292    /// or zero if the mempool is disabled.
293    #[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
302/// Mempool async management and query service.
303///
304/// The mempool is the set of all verified transactions that this node is aware
305/// of that have yet to be confirmed by the Zcash network. A transaction is
306/// confirmed when it has been included in a block ('mined').
307pub struct Mempool {
308    /// The configured Zcash network.
309    network: Network,
310
311    /// The configurable options for the mempool, persisted between states.
312    config: Config,
313
314    /// The state of the mempool.
315    active_state: ActiveState,
316
317    /// Allows checking if we are near the tip to enable/disable the mempool.
318    sync_status: SyncStatus,
319
320    /// Lets tests whose best tip is an old Mainnet block start the mempool on sync status alone.
321    #[cfg(test)]
322    skip_tip_age_check: bool,
323
324    /// If the state's best chain tip has reached this height, always enable the mempool.
325    debug_enable_at_height: Option<Height>,
326
327    /// Allows efficient access to the best tip of the blockchain.
328    latest_chain_tip: zs::LatestChainTip,
329
330    /// Allows the detection of newly added chain tip blocks,
331    /// and chain tip resets.
332    chain_tip_change: ChainTipChange,
333
334    /// Handle to the outbound service.
335    /// Used to construct the transaction downloader.
336    outbound: Outbound,
337
338    /// Handle to the state service.
339    /// Used to construct the transaction downloader.
340    state: State,
341
342    /// Handle to the transaction verifier service.
343    /// Used to construct the transaction downloader.
344    tx_verifier: TxVerifier,
345
346    /// Sender part of a gossip transactions channel.
347    /// Used to broadcast transaction ids to peers.
348    transaction_sender: broadcast::Sender<MempoolChange>,
349
350    /// Sender for reporting peer addresses that advertised unexpectedly invalid transactions.
351    misbehavior_sender: mpsc::Sender<zn::MisbehaviorReport>,
352
353    // Diagnostics
354    //
355    /// Queued transactions pending download or verification transmitter.
356    /// Only displayed after the mempool's first activation.
357    #[cfg(feature = "progress-bar")]
358    queued_count_bar: Option<howudoin::Tx>,
359
360    /// Number of mempool transactions transmitter.
361    /// Only displayed after the mempool's first activation.
362    #[cfg(feature = "progress-bar")]
363    transaction_count_bar: Option<howudoin::Tx>,
364
365    /// Mempool transaction cost transmitter.
366    /// Only displayed after the mempool's first activation.
367    #[cfg(feature = "progress-bar")]
368    transaction_cost_bar: Option<howudoin::Tx>,
369
370    /// Rejected transactions transmitter.
371    /// Only displayed after the mempool's first activation.
372    #[cfg(feature = "progress-bar")]
373    rejected_count_bar: Option<howudoin::Tx>,
374
375    /// Wakes the queue checker to store and announce verified transactions.
376    transaction_verified: Arc<Notify>,
377}
378
379impl Mempool {
380    /// Builds the mempool using a non-owning outbound network handle.
381    ///
382    /// Pass [`zn::NetworkService::background_service`] because the network's inbound handler
383    /// retains the mempool and must not keep its own network alive.
384    #[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        // Make sure `is_enabled` is accurate.
428        // Otherwise, it is only updated in `poll_ready`, right before each service call.
429        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    /// Is the mempool enabled by a debug config option?
436    fn is_enabled_by_debug(&self) -> bool {
437        let mut is_debug_enabled = false;
438
439        // optimise non-debug performance
440        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    /// Returns `true` if Zebra is caught up enough to start the mempool.
464    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    /// Replaces the active state with a freshly-initialised [`ActiveState::Enabled`],
478    /// using `tip_action`'s best tip hash as the `last_seen_tip_hash`.
479    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    /// Activate the mempool once Zebra is close enough to the tip.
503    ///
504    /// Sync status only gates initial activation. Once the mempool is active,
505    /// this method does not disable it.
506    ///
507    /// Accepts an optional [`TipAction`] for setting the `last_seen_tip_hash`
508    /// field when enabling the mempool state. It will not enable the mempool if
509    /// this is [`None`]. `is_caught_up_to_start` is supplied by the caller, which
510    /// already computes it, to avoid evaluating the sync-status predicate twice.
511    ///
512    /// Returns `true` if the state changed.
513    fn update_state(
514        &mut self,
515        tip_action: Option<&TipAction>,
516        is_caught_up_to_start: bool,
517    ) -> bool {
518        // TODO: revisit these state transitions when sync status can prove
519        // whether Zebra is behind the network tip.
520        match (is_caught_up_to_start, self.is_enabled(), tip_action) {
521            // the active state is up to date, or there is no tip action to activate the mempool
522            (false, false, _) | (true, true, _) | (true, false, None) => return false,
523
524            // Enable state - there should be a chain tip when Zebra is close to the network tip
525            (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            // TODO: only disable an already-active mempool when validated sync
535            // state proves Zebra is behind a higher-work chain that follows
536            // this node's consensus rules.
537            //
538            // The sync status can be triggered by lower-work forks,
539            // stale peers, or peers on incompatible consensus rules, so
540            // it is strong enough to delay initial activation but not to shut
541            // down a working mempool.
542            (false, true, _) => {
543                return false;
544            }
545        };
546
547        true
548    }
549
550    /// Return whether the mempool is enabled or not.
551    pub fn is_enabled(&self) -> bool {
552        match self.active_state {
553            ActiveState::Disabled => false,
554            ActiveState::Enabled { .. } => true,
555        }
556    }
557
558    /// Remove expired transaction ids from a given list of inserted ones.
559    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    /// Update metrics for the mempool.
571    fn update_metrics(&mut self) {
572        // Shutdown if needed
573        #[cfg(feature = "progress-bar")]
574        if matches!(howudoin::cancelled(), Some(true)) {
575            self.disable_metrics();
576            return;
577        }
578
579        // Initialize if just activated
580        #[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            // .set_len(max_transaction_count);
594
595            let transaction_cost_bar = howudoin::new_with_parent(transaction_count_bar.id())
596                .label("Mempool Cost")
597                .set_pos(0u64)
598                // .set_len(self.config.tx_cost_limit)
599                .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            // .set_len(
605            //     u64::try_from(downloads::MAX_INBOUND_CONCURRENCY).expect("fits in u64"),
606            // );
607
608            let rejected_count_bar = *howudoin::new_with_parent(queued_count_bar.id())
609                .label("Mempool Rejects")
610                .set_pos(0u64);
611            // .set_len(
612            //     u64::try_from(storage::MAX_EVICTION_MEMORY_ENTRIES).expect("fits in u64"),
613            // );
614
615            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        // Update if the mempool has ever been active
622        #[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            // Display the cost and cost limit, with the actual size as a description.
649            //
650            // Costs can be much higher than the transaction size due to the
651            // MEMPOOL_TRANSACTION_COST_THRESHOLD minimum cost.
652            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    /// Disable metrics for the mempool.
661    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        // TODO: Consider broadcasting a `MempoolChange` when the mempool is disabled.
694        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        // When the mempool is disabled we still return that the service is ready.
699        // Otherwise, callers could block waiting for the mempool to be enabled.
700        if !self.is_enabled() {
701            self.update_metrics();
702
703            return Poll::Ready(Ok(()));
704        }
705
706        // Clear the mempool and cancel downloads if there has been a chain tip reset.
707        //
708        // But if the mempool was just freshly enabled,
709        // skip resetting and removing mined transactions for this tip.
710        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            // Use the same code for dropping and resetting the mempool,
727            // to avoid subtle bugs.
728            //
729            // Drop the current contents of the state,
730            // cancelling any pending download tasks,
731            // and dropping completed verification results.
732            std::mem::drop(previous_state);
733
734            // Re-initialise an empty state.
735            //
736            // This deliberately bypasses the initial-activation gate in `update_state()`:
737            // the mempool was already active when the reset arrived, and a
738            // far-from-tip sync status must not disable an already-active mempool
739            // (it can be triggered by lower-work forks, stale peers, or peers on
740            // incompatible consensus rules).
741            self.enable_at_tip(reset_tip_action);
742
743            // Re-verify the transactions that were pending or valid at the previous tip.
744            // This saves us the time and data needed to re-download them.
745            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                    // This is just an efficiency optimisation, so we don't care if queueing
753                    // transaction requests fails.
754                    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            // Collect inserted transaction ids.
770            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            // Clean up completed download tasks and add to mempool if successful.
777            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                        // # Correctness:
781                        //
782                        // It's okay to use tip height here instead of the tip hash since
783                        // chain_tip_change.last_tip_change() returns a `TipAction::Reset` when
784                        // the best chain changes (which is the only way to stay at the same height), and the
785                        // mempool re-verifies all pending tx_downloads when there's a `TipAction::Reset`.
786                        //
787                        // This also makes the stored height the tip height the transaction was
788                        // verified on, which block verification relies on when it reuses the
789                        // mempool's verification. See `VerifiedUnminedTx::height`.
790                        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                                // Save transaction ids that we will send to peers
802                                send_to_peers_ids.insert(inserted_id);
803                            } else {
804                                invalidated_ids.insert(tx_id);
805                            }
806
807                            // Send the result to responder channel if one was provided.
808                            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                            // We don't care if re-queueing the transaction request fails.
816                            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            // Handle best chain tip changes
870            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                // Cancel downloads/verifications/storage of transactions
876                // with the same mined IDs as recently mined transactions.
877                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                // Clear any transaction rejections if they might have become valid after
885                // the new block was added to the tip.
886                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            // Remove expired transactions from the mempool.
895            //
896            // Lock times never expire, because block times are strictly increasing.
897            // So we don't need to check them here.
898            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                // Remove transactions that are expired from the peers list
904                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            // Send transactions that were not rejected nor expired to peers and RPC listeners.
918            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                // A send fails only when the broadcast channel has no
925                // subscribers, which is a normal state the mempool must
926                // tolerate: the gossip and indexer tasks are downstream
927                // consumers of this feed, and mempool liveness must not depend
928                // on them staying subscribed. Discard the result so a momentary
929                // absence of subscribers does not make `poll_ready()` return a
930                // service-fatal error. See #10689.
931                let _ = self
932                    .transaction_sender
933                    .send(MempoolChange::added(send_to_peers_ids));
934            }
935
936            // Send transactions that were rejected to RPC listeners.
937            if !invalidated_ids.is_empty() {
938                tracing::trace!(
939                    ?invalidated_ids,
940                    "sending invalidated transactions to RPC listeners"
941                );
942
943                // See the `MempoolChange::added` send above: a missing
944                // subscriber is not a fatal condition. See #10689.
945                let _ = self
946                    .transaction_sender
947                    .send(MempoolChange::invalidated(invalidated_ids));
948            }
949
950            // Send transactions that were mined onto the best chain to RPC listeners.
951            if !mined_mempool_ids.is_empty() {
952                tracing::trace!(
953                    ?mined_mempool_ids,
954                    "sending mined transactions to RPC listeners"
955                );
956
957                // See the `MempoolChange::added` send above: a missing
958                // subscriber is not a fatal condition. See #10689.
959                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    /// Call the mempool service.
971    ///
972    /// Errors indicate that the peer has done something wrong or unexpected,
973    /// and will cause callers to disconnect from the remote peer.
974    #[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                // Queries
983                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                // Queue mempool candidates
1099                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                    // We've added transactions to the queue
1125                    self.update_metrics();
1126
1127                    async move { Ok(Response::Queued(rsp)) }.boxed()
1128                }
1129
1130                // Queue candidates received from a specific peer (advertised IDs
1131                // or a directly pushed transaction). Per-peer accounting is
1132                // enforced inside the downloader.
1133                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                // Store successfully downloaded and verified transactions in the mempool
1153                Request::CheckForVerifiedTransactions => {
1154                    trace!(?req, "got mempool request");
1155
1156                    // Queue checks also reap abandoned waiters when the chain tip stalls.
1157                    storage.pending_outputs.prune();
1158
1159                    // Verified transactions were collected in poll_ready.
1160                    async move { Ok(Response::CheckedForVerifiedTransactions) }.boxed()
1161                }
1162
1163                // Summary statistics for the mempool: count, total size, and memory usage.
1164                //
1165                // Used by the `getmempoolinfo` RPC method
1166                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; // TODO: Placeholder, should be fixed later
1174
1175                    // TODO: Set to Some(true) on regtest once network info is available.
1176                    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                // TODO: add the name of the request, but not the content,
1232                //       like the command() or Display impls of network requests
1233                trace!("got mempool request while mempool is disabled");
1234
1235                // We can't return an error since that will cause a disconnection
1236                // by the peer connection handler. Therefore, return successful
1237                // empty responses.
1238
1239                let resp = match req {
1240                    // Return empty responses for queries.
1241                    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                    // Don't queue mempool candidates, because there is no queue.
1269                    Request::Queue(gossiped_txs) => Response::Queued(
1270                        // Special case; we can signal the error inside the response,
1271                        // because the inbound service ignores inner errors.
1272                        iter::repeat_n(MempoolError::Disabled, gossiped_txs.len())
1273                            .map(BoxError::from)
1274                            .map(Err)
1275                            .collect(),
1276                    ),
1277
1278                    // Drop peer-advertised txids when the mempool is disabled.
1279                    Request::QueueFromPeer { .. } => Response::Queued(Vec::new()),
1280
1281                    // Check if the mempool should be enabled.
1282                    // This request makes sure mempools are debug-enabled in the acceptance tests.
1283                    Request::CheckForVerifiedTransactions => {
1284                        // all the work for this request is done in poll_ready
1285                        Response::CheckedForVerifiedTransactions
1286                    }
1287
1288                    // Return empty mempool stats
1289                    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}