Skip to main content

zebrad/components/mempool/
storage.rs

1//! Mempool transaction storage.
2//!
3//! The main struct [`Storage`] holds verified and rejected transactions.
4//! [`Storage`] is effectively the data structure of the mempool. Convenient methods to
5//! manage it are included.
6//!
7//! [`Storage`] does not expose a service so it can only be used by other code directly.
8//! Only code inside the [`crate::components::mempool`] module has access to it.
9
10use std::{
11    collections::{HashMap, HashSet},
12    mem::size_of,
13    sync::Arc,
14    time::Duration,
15};
16
17use thiserror::Error;
18
19use zcash_script::solver;
20use zebra_chain::{
21    block::Height,
22    transaction::{self, Hash, Transaction, UnminedTx, UnminedTxId, VerifiedUnminedTx},
23    transparent,
24};
25use zebra_node_services::mempool::TransactionDependencies;
26
27use self::{eviction_list::EvictionList, verified_set::VerifiedSet};
28use super::{
29    config, downloads::TransactionDownloadVerifyError, pending_outputs::PendingOutputs,
30    MempoolError,
31};
32
33#[cfg(any(test, feature = "proptest-impl"))]
34use proptest_derive::Arbitrary;
35
36#[cfg(test)]
37pub mod tests;
38
39mod eviction_list;
40mod policy;
41mod verified_set;
42
43/// The size limit for mempool transaction rejection lists per [ZIP-401].
44///
45/// > The size of RecentlyEvicted SHOULD never exceed `eviction_memory_entries`
46/// > entries, which is the constant 40000.
47///
48/// We use the specified value for all lists for consistency.
49///
50/// [ZIP-401]: https://zips.z.cash/zip-0401#specification
51pub(crate) const MAX_EVICTION_MEMORY_ENTRIES: usize = 40_000;
52
53/// Transactions rejected based on transaction authorizing data (scripts, proofs, signatures),
54/// or lock times. These rejections are only valid for the current tip.
55///
56/// Each committed block clears these rejections, because new blocks can supply missing inputs.
57#[derive(Error, Clone, Debug, PartialEq, Eq)]
58#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
59#[allow(dead_code)]
60pub enum ExactTipRejectionError {
61    /// Skip this variant in proptest because `TransactionError` is a large enum
62    /// that causes stack overflow during arbitrary value generation.
63    #[error("transaction did not pass consensus validation: {0}")]
64    #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
65    FailedVerification(#[from] zebra_consensus::error::TransactionError),
66    #[error("transaction did not pass standard validation: {0}")]
67    FailedStandard(#[from] NonStandardTransactionError),
68}
69
70/// Transactions rejected based only on their effects (spends, outputs, transaction header).
71/// These rejections are only valid for the current tip.
72///
73/// Each committed block clears these rejections, because new blocks can evict other transactions.
74#[derive(Error, Clone, Debug, PartialEq, Eq)]
75#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
76#[allow(dead_code)]
77pub enum SameEffectsTipRejectionError {
78    #[error(
79        "transaction rejected because another transaction in the mempool has already spent some of \
80        its inputs"
81    )]
82    SpendConflict,
83
84    #[error(
85        "transaction rejected because it spends missing outputs from \
86        another transaction in the mempool"
87    )]
88    MissingOutput,
89}
90
91/// Transactions rejected based only on their effects (spends, outputs, transaction header).
92/// These rejections are valid while the current chain continues to grow.
93///
94/// Rollbacks and network upgrades clear these rejections, because they can lower the tip height,
95/// or change the consensus rules.
96#[derive(Error, Clone, Debug, PartialEq, Eq, Hash)]
97#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
98#[allow(dead_code)]
99pub enum SameEffectsChainRejectionError {
100    #[error("best chain tip has reached transaction expiry height")]
101    Expired,
102
103    #[error("transaction inputs were spent, or nullifiers were revealed, in the best chain")]
104    DuplicateSpend,
105
106    #[error("transaction was committed to the best chain")]
107    Mined,
108
109    /// Otherwise valid transaction removed from mempool due to [ZIP-401] random
110    /// eviction.
111    ///
112    /// Consensus rule:
113    /// > The txid (rather than the wtxid ...) is used even for version 5 transactions
114    ///
115    /// [ZIP-401]: https://zips.z.cash/zip-0401#specification
116    #[error("transaction evicted from the mempool due to ZIP-401 denial of service limits")]
117    RandomlyEvicted,
118}
119
120/// Storage error that combines all other specific error types.
121#[derive(Error, Clone, Debug, PartialEq, Eq)]
122#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
123#[allow(dead_code)]
124pub enum RejectionError {
125    #[error(transparent)]
126    ExactTip(#[from] ExactTipRejectionError),
127    #[error(transparent)]
128    SameEffectsTip(#[from] SameEffectsTipRejectionError),
129    #[error(transparent)]
130    SameEffectsChain(#[from] SameEffectsChainRejectionError),
131    #[error(transparent)]
132    NonStandardTransaction(#[from] NonStandardTransactionError),
133}
134
135/// Non-standard transaction error.
136#[derive(Error, Clone, Debug, PartialEq, Eq)]
137#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
138pub enum NonStandardTransactionError {
139    #[error("transaction is dust")]
140    IsDust,
141    #[error("transaction scriptSig is too large")]
142    ScriptSigTooLarge,
143    #[error("transaction scriptSig is not push-only")]
144    ScriptSigNotPushOnly,
145    #[error("transaction scriptPubKey is non-standard")]
146    ScriptPubKeyNonStandard,
147    #[error("transaction has a bare multisig output")]
148    BareMultiSig,
149    #[error("transaction has multiple OP_RETURN outputs")]
150    MultiOpReturn,
151    #[error("transaction has an OP_RETURN output that exceeds the size limit")]
152    DataCarrierTooLarge,
153    #[error("transaction has too many signature operations")]
154    TooManySigops,
155    #[error("transaction has non-standard inputs")]
156    NonStandardInputs,
157}
158
159/// Checks that a transaction's outputs are standard, like the output checks in zcashd's
160/// `IsStandardTx()`:
161/// <https://github.com/zcash/zcash/blob/v6.11.0/src/policy/policy.cpp#L108-L132>
162///
163/// The mempool runs this before verification, and again when it stores a transaction.
164pub(crate) fn check_standard_outputs(
165    transaction: &Transaction,
166    max_datacarrier_bytes: u32,
167) -> Result<(), NonStandardTransactionError> {
168    // Rule: outputs must be standard script kinds, with special handling for OP_RETURN.
169    let mut data_out_count = 0u32;
170
171    for output in transaction.outputs() {
172        let lock_script = &output.lock_script;
173        let script_len = lock_script.as_raw_bytes().len();
174
175        match policy::standard_script_kind(lock_script) {
176            // Rule: output script must be standard (P2PKH/P2SH/P2PK/multisig/OP_RETURN).
177            None => return Err(NonStandardTransactionError::ScriptPubKeyNonStandard),
178            Some(solver::ScriptKind::NullData { .. }) => {
179                // Rule: OP_RETURN script size is limited.
180                // Cast is safe: u32 always fits in usize on 32-bit and 64-bit platforms.
181                if script_len > max_datacarrier_bytes as usize {
182                    return Err(NonStandardTransactionError::DataCarrierTooLarge);
183                }
184                // Rule: count OP_RETURN outputs to enforce the one-output limit.
185                data_out_count += 1;
186            }
187            Some(solver::ScriptKind::MultiSig { pubkeys, .. }) => {
188                // Rule: multisig must be at most 3-of-3 for standardness.
189                // Note: This check is technically subsumed by the unconditional BareMultiSig
190                // rejection below, but we keep it to distinguish the two error reasons
191                // (ScriptPubKeyNonStandard for >3 keys vs BareMultiSig for valid multisig).
192                if pubkeys.len() > policy::MAX_STANDARD_MULTISIG_PUBKEYS {
193                    return Err(NonStandardTransactionError::ScriptPubKeyNonStandard);
194                }
195                // Rule: bare multisig outputs are non-standard (fIsBareMultisigStd = false).
196                return Err(NonStandardTransactionError::BareMultiSig);
197            }
198            Some(_) => {
199                // Rule: non-OP_RETURN outputs must not be dust.
200                if output.is_dust() {
201                    return Err(NonStandardTransactionError::IsDust);
202                }
203            }
204        }
205    }
206
207    // Rule: only one OP_RETURN output is permitted.
208    if data_out_count > 1 {
209        return Err(NonStandardTransactionError::MultiOpReturn);
210    }
211
212    Ok(())
213}
214
215/// Represents a set of transactions that have been removed from the mempool, either because
216/// they were mined, or because they were invalidated by another transaction that was mined.
217#[derive(Clone, Debug, PartialEq, Eq)]
218pub struct RemovedTransactionIds {
219    /// A list of ids for transactions that were removed mined onto the best chain.
220    pub mined: HashSet<UnminedTxId>,
221    /// A list of ids for transactions that were invalidated by other transactions
222    /// that were mined onto the best chain.
223    pub invalidated: HashSet<UnminedTxId>,
224}
225
226impl RemovedTransactionIds {
227    /// Returns the total number of transactions that were removed from the mempool.
228    pub fn total_len(&self) -> usize {
229        self.mined.len() + self.invalidated.len()
230    }
231}
232
233/// Hold mempool verified and rejected mempool transactions.
234pub struct Storage {
235    /// The set of verified transactions in the mempool.
236    verified: VerifiedSet,
237
238    /// The set of outpoints with pending requests for their associated transparent::Output.
239    pub(super) pending_outputs: PendingOutputs,
240
241    /// The set of transactions rejected due to bad authorizations, or for other
242    /// reasons, and their rejection reasons. These rejections only apply to the
243    /// current tip.
244    ///
245    /// Only transactions with the exact [`UnminedTxId`] are invalid.
246    tip_rejected_exact: HashMap<UnminedTxId, ExactTipRejectionError>,
247
248    /// A set of transactions rejected for their effects, and their rejection
249    /// reasons. These rejections only apply to the current tip.
250    ///
251    /// Any transaction with the same [`transaction::Hash`] is invalid.
252    tip_rejected_same_effects: HashMap<transaction::Hash, SameEffectsTipRejectionError>,
253
254    /// Sets of transactions rejected for their effects, keyed by rejection reason.
255    /// These rejections apply until a rollback or network upgrade.
256    ///
257    /// Any transaction with the same [`transaction::Hash`] is invalid.
258    ///
259    /// An [`EvictionList`] is used for both randomly evicted and expired
260    /// transactions, even if it is only needed for the evicted ones. This was
261    /// done just to simplify the existing code; there is no harm in having a
262    /// timeout for expired transactions too since re-checking expired
263    /// transactions is cheap.
264    // If this code is ever refactored and the lists are split in different
265    // fields, then we can use an `EvictionList` just for the evicted list.
266    chain_rejected_same_effects: HashMap<SameEffectsChainRejectionError, EvictionList>,
267
268    /// The mempool transaction eviction age limit.
269    /// Same as [`config::Config::eviction_memory_time`].
270    eviction_memory_time: Duration,
271
272    /// Max total cost of the verified mempool set, beyond which transactions
273    /// are evicted to make room.
274    tx_cost_limit: u64,
275
276    /// Maximum allowed size of OP_RETURN scripts, in bytes.
277    max_datacarrier_bytes: u32,
278}
279
280impl Drop for Storage {
281    fn drop(&mut self) {
282        self.clear();
283    }
284}
285
286impl Storage {
287    #[allow(clippy::field_reassign_with_default)]
288    pub(crate) fn new(config: &config::Config) -> Self {
289        Self {
290            tx_cost_limit: config.tx_cost_limit,
291            eviction_memory_time: config.eviction_memory_time,
292            max_datacarrier_bytes: config
293                .max_datacarrier_bytes
294                .unwrap_or(config::DEFAULT_MAX_DATACARRIER_BYTES),
295            verified: Default::default(),
296            pending_outputs: Default::default(),
297            tip_rejected_exact: Default::default(),
298            tip_rejected_same_effects: Default::default(),
299            chain_rejected_same_effects: Default::default(),
300        }
301    }
302
303    /// Check and reject non-standard transaction.
304    ///
305    /// Zcashd defines non-consensus standard transaction checks in
306    /// <https://github.com/zcash/zcash/blob/v6.11.0/src/policy/policy.cpp#L58-L135>
307    ///
308    /// This checks are applied before inserting a transaction in `AcceptToMemoryPool`:
309    /// <https://github.com/zcash/zcash/blob/v6.11.0/src/main.cpp#L1819>
310    ///
311    /// Currently, we implement: per-transaction sigops limit, standard input script checks,
312    /// input scriptSig size/push-only checks, standard output script checks (including OP_RETURN
313    /// limits), and dust checks.
314    fn reject_if_non_standard_tx(&mut self, tx: &VerifiedUnminedTx) -> Result<(), MempoolError> {
315        use zcash_script::script::{self, Evaluable as _};
316
317        let transaction = tx.transaction.transaction.as_ref();
318        let spent_outputs = &tx.spent_outputs;
319
320        for input in transaction.inputs() {
321            let unlock_script = match input {
322                transparent::Input::PrevOut { unlock_script, .. } => unlock_script,
323                transparent::Input::Coinbase { .. } => continue,
324            };
325
326            // Rule: scriptSig size must be within the standard limit.
327            if unlock_script.as_raw_bytes().len() > policy::MAX_STANDARD_SCRIPTSIG_SIZE {
328                return self
329                    .reject_non_standard(tx, NonStandardTransactionError::ScriptSigTooLarge);
330            }
331
332            let code = script::Code(unlock_script.as_raw_bytes().to_vec());
333            // Rule: scriptSig must be push-only.
334            if !code.is_push_only() {
335                return self
336                    .reject_non_standard(tx, NonStandardTransactionError::ScriptSigNotPushOnly);
337            }
338        }
339
340        if !spent_outputs.is_empty() {
341            // Validate that spent_outputs aligns with transparent inputs.
342            if transaction.inputs().len() != spent_outputs.len() {
343                tracing::warn!(
344                    inputs = transaction.inputs().len(),
345                    spent_outputs = spent_outputs.len(),
346                    "spent_outputs length mismatch, rejecting as non-standard"
347                );
348                return self
349                    .reject_non_standard(tx, NonStandardTransactionError::NonStandardInputs);
350            }
351
352            // Rule: all transparent inputs must pass `AreInputsStandard()` checks:
353            // https://github.com/zcash/zcash/blob/v6.11.0/src/policy/policy.cpp#L137
354            if !policy::are_inputs_standard(transaction, spent_outputs) {
355                return self
356                    .reject_non_standard(tx, NonStandardTransactionError::NonStandardInputs);
357            }
358
359            // Rule: per-transaction sigops (legacy + P2SH) must not exceed the limit.
360            // zcashd sums GetLegacySigOpCount + GetP2SHSigOpCount for AcceptToMemoryPool:
361            // https://github.com/zcash/zcash/blob/v6.11.0/src/main.cpp#L1819
362            let total_sigops = tx.block_sigop_count();
363            if total_sigops > policy::MAX_STANDARD_TX_SIGOPS {
364                return self.reject_non_standard(tx, NonStandardTransactionError::TooManySigops);
365            }
366        } else {
367            // No spent outputs available (e.g. shielded-only transaction).
368            // Only check legacy sigops.
369            if tx.legacy_sigop_count > policy::MAX_STANDARD_TX_SIGOPS {
370                return self.reject_non_standard(tx, NonStandardTransactionError::TooManySigops);
371            }
372        }
373
374        if let Err(rejection_error) =
375            check_standard_outputs(transaction, self.max_datacarrier_bytes)
376        {
377            return self.reject_non_standard(tx, rejection_error);
378        }
379
380        Ok(())
381    }
382
383    /// Rejects a transaction as non-standard, caches the rejection, and returns the mempool error.
384    ///
385    /// Note: The returned error is `MempoolError::NonStandardTransaction`, while the cached
386    /// rejection (via `reject()`) is stored as
387    /// `ExactTipRejectionError::FailedStandard`. Callers that later check
388    /// `rejection_error()` will get `MempoolError::StorageExactTip(FailedStandard(...))`.
389    fn reject_non_standard(
390        &mut self,
391        tx: &VerifiedUnminedTx,
392        rejection_error: NonStandardTransactionError,
393    ) -> Result<(), MempoolError> {
394        self.reject(tx.transaction.id, rejection_error.clone().into());
395        Err(MempoolError::NonStandardTransaction(rejection_error))
396    }
397
398    /// Insert a [`VerifiedUnminedTx`] into the mempool, caching any rejections.
399    ///
400    /// Accepts the [`VerifiedUnminedTx`] being inserted and `spent_mempool_outpoints`,
401    /// a list of transparent inputs of the provided [`VerifiedUnminedTx`] that were found
402    /// as newly created transparent outputs in the mempool during transaction verification.
403    ///
404    /// Returns an error if the mempool's verified transactions or rejection caches
405    /// prevent this transaction from being inserted.
406    /// These errors should not be propagated to peers, because the transactions are valid.
407    ///
408    /// If inserting this transaction evicts other transactions, they will be tracked
409    /// as [`SameEffectsChainRejectionError::RandomlyEvicted`].
410    #[allow(clippy::unwrap_in_result)]
411    pub fn insert(
412        &mut self,
413        tx: VerifiedUnminedTx,
414        spent_mempool_outpoints: Vec<transparent::OutPoint>,
415        height: Option<Height>,
416    ) -> Result<UnminedTxId, MempoolError> {
417        // # Security
418        //
419        // This method must call `reject`, rather than modifying the rejection lists directly.
420        let unmined_tx_id = tx.transaction.id;
421        let tx_id = unmined_tx_id.mined_id();
422
423        // First, check if we have a cached rejection for this transaction.
424        if let Some(error) = self.rejection_error(&unmined_tx_id) {
425            tracing::trace!(
426                ?tx_id,
427                ?error,
428                stored_transaction_count = ?self.verified.transaction_count(),
429                "returning cached error for transaction",
430            );
431
432            return Err(error);
433        }
434
435        // If `tx` is already in the mempool, we don't change anything.
436        //
437        // Security: transactions must not get refreshed by new queries,
438        // because that allows malicious peers to keep transactions live forever.
439        if self.verified.contains(&tx_id) {
440            tracing::trace!(
441                ?tx_id,
442                stored_transaction_count = ?self.verified.transaction_count(),
443                "returning InMempool error for transaction that is already in the mempool",
444            );
445
446            return Err(MempoolError::InMempool);
447        }
448
449        // Check that the transaction is standard.
450        self.reject_if_non_standard_tx(&tx)?;
451
452        // Then, we try to insert into the pool. If this fails the transaction is rejected.
453        let mut result = Ok(unmined_tx_id);
454        if let Err(rejection_error) = self.verified.insert(
455            tx,
456            spent_mempool_outpoints,
457            &mut self.pending_outputs,
458            height,
459        ) {
460            tracing::debug!(
461                ?tx_id,
462                ?rejection_error,
463                stored_transaction_count = ?self.verified.transaction_count(),
464                "insertion error for transaction",
465            );
466
467            // We could return here, but we still want to check the mempool size
468            self.reject(unmined_tx_id, rejection_error.clone().into());
469            result = Err(rejection_error.into());
470        }
471
472        // Once inserted, we evict transactions over the pool size limit per [ZIP-401];
473        //
474        // > On receiving a transaction: (...)
475        // > Calculate its cost. If the total cost of transactions in the mempool including this
476        // > one would `exceed mempooltxcostlimit`, then the node MUST repeatedly call
477        // > EvictTransaction (with the new transaction included as a candidate to evict) until the
478        // > total cost does not exceed `mempooltxcostlimit`.
479        //
480        // 'EvictTransaction' is equivalent to [`VerifiedSet::evict_one()`] in
481        // our implementation.
482        //
483        // [ZIP-401]: https://zips.z.cash/zip-0401
484        while self.verified.total_cost() > self.tx_cost_limit {
485            // > EvictTransaction MUST do the following:
486            // > Select a random transaction to evict, with probability in direct proportion to
487            // > eviction weight. (...) Remove it from the mempool.
488            let victim_tx = self
489                .verified
490                .evict_one()
491                .expect("mempool is empty, but was expected to be full");
492
493            // > Add the txid and the current time to RecentlyEvicted, dropping the oldest entry in
494            // > RecentlyEvicted if necessary to keep it to at most `eviction_memory_entries entries`.
495            self.reject(
496                victim_tx.transaction.id,
497                SameEffectsChainRejectionError::RandomlyEvicted.into(),
498            );
499
500            // If this transaction gets evicted, set its result to the same error
501            if victim_tx.transaction.id == unmined_tx_id {
502                result = Err(SameEffectsChainRejectionError::RandomlyEvicted.into());
503            }
504        }
505
506        result
507    }
508
509    /// Remove transactions from the mempool via exact [`UnminedTxId`].
510    ///
511    /// For v5 transactions, transactions are matched by WTXID, using both the:
512    /// - non-malleable transaction ID, and
513    /// - authorizing data hash.
514    ///
515    /// This matches the exact transaction, with identical blockchain effects, signatures, and proofs.
516    ///
517    /// Returns the number of transactions which were removed.
518    ///
519    /// Removes from the 'verified' set, if present.
520    /// Maintains the order in which the other unmined transactions have been inserted into the mempool.
521    ///
522    /// Does not add or remove from the 'rejected' tracking set.
523    #[allow(dead_code)]
524    pub fn remove_exact(&mut self, exact_wtxids: &HashSet<UnminedTxId>) -> usize {
525        self.verified
526            .remove_all_that(|tx| exact_wtxids.contains(&tx.transaction.id))
527            .len()
528    }
529
530    /// Clears a list of mined transaction ids from the verified set's tracked transaction dependencies.
531    pub fn clear_mined_dependencies(&mut self, mined_ids: &HashSet<transaction::Hash>) {
532        self.verified.clear_mined_dependencies(mined_ids);
533    }
534
535    /// Reject and remove transactions from the mempool via non-malleable [`transaction::Hash`].
536    /// - For v5 transactions, transactions are matched by TXID,
537    ///   using only the non-malleable transaction ID.
538    ///   This matches any transaction with the same effect on the blockchain state,
539    ///   even if its signatures and proofs are different.
540    /// - Returns the number of transactions which were removed.
541    /// - Removes from the 'verified' set, if present.
542    ///   Maintains the order in which the other unmined transactions have been inserted into the mempool.
543    /// - Prunes `pending_outputs` of any closed channels.
544    ///
545    /// Reject and remove transactions from the mempool that contain any spent outpoints or revealed
546    /// nullifiers from the passed in `transactions`.
547    ///
548    /// Returns the number of transactions that were removed.
549    pub fn reject_and_remove_same_effects(
550        &mut self,
551        mined_ids: &HashSet<transaction::Hash>,
552        transactions: Vec<Arc<Transaction>>,
553    ) -> RemovedTransactionIds {
554        let removed_mined = self
555            .verified
556            .remove_all_that(|tx| mined_ids.contains(&tx.transaction.id.mined_id()));
557
558        let spent_outpoints: HashSet<_> = transactions
559            .iter()
560            .flat_map(|tx| tx.spent_outpoints())
561            .collect();
562        let sprout_nullifiers: HashSet<_> = transactions
563            .iter()
564            .flat_map(|tx| tx.sprout_nullifiers().collect::<Vec<_>>())
565            .collect();
566        let sapling_nullifiers: HashSet<_> = transactions
567            .iter()
568            .flat_map(|tx| tx.sapling_nullifiers().collect::<Vec<_>>())
569            .collect();
570        let orchard_nullifiers: HashSet<_> = transactions
571            .iter()
572            .flat_map(|tx| tx.orchard_nullifiers().collect::<Vec<_>>())
573            .collect();
574        let ironwood_nullifiers: HashSet<_> = transactions
575            .iter()
576            .flat_map(|transaction| transaction.ironwood_nullifiers())
577            .collect();
578
579        let duplicate_spend_ids: HashSet<_> = self
580            .verified
581            .transactions()
582            .values()
583            .map(|tx| (tx.transaction.id, &tx.transaction.transaction))
584            .filter_map(|(tx_id, tx)| {
585                (tx.spent_outpoints()
586                    .any(|outpoint| spent_outpoints.contains(&outpoint))
587                    || tx
588                        .sprout_nullifiers()
589                        .any(|nf| sprout_nullifiers.contains(&nf))
590                    || tx
591                        .sapling_nullifiers()
592                        .any(|nf| sapling_nullifiers.contains(&nf))
593                    || tx
594                        .orchard_nullifiers()
595                        .any(|nf| orchard_nullifiers.contains(&nf))
596                    || tx
597                        .ironwood_nullifiers()
598                        .any(|nf| ironwood_nullifiers.contains(&nf)))
599                .then_some(tx_id)
600            })
601            .collect();
602
603        let removed_duplicate_spend = self
604            .verified
605            .remove_all_that(|tx| duplicate_spend_ids.contains(&tx.transaction.id));
606
607        for &mined_id in mined_ids {
608            self.reject(
609                // the reject and rejection_error fns that store and check `SameEffectsChainRejectionError`s
610                // only use the mined id, so using `Legacy` ids will apply to v5 transactions as well.
611                UnminedTxId::Legacy(mined_id),
612                SameEffectsChainRejectionError::Mined.into(),
613            );
614        }
615
616        for duplicate_spend_id in duplicate_spend_ids {
617            self.reject(
618                duplicate_spend_id,
619                SameEffectsChainRejectionError::DuplicateSpend.into(),
620            );
621        }
622
623        self.pending_outputs.prune();
624
625        RemovedTransactionIds {
626            mined: removed_mined,
627            invalidated: removed_duplicate_spend,
628        }
629    }
630
631    /// Clears the whole mempool storage.
632    #[allow(dead_code)]
633    pub fn clear(&mut self) {
634        self.verified.clear();
635        self.tip_rejected_exact.clear();
636        self.pending_outputs.clear();
637        self.tip_rejected_same_effects.clear();
638        self.chain_rejected_same_effects.clear();
639        self.update_rejected_metrics();
640    }
641
642    /// Clears rejections that only apply to the current tip.
643    pub fn clear_tip_rejections(&mut self) {
644        self.tip_rejected_exact.clear();
645        self.tip_rejected_same_effects.clear();
646        self.update_rejected_metrics();
647    }
648
649    /// Clears rejections that only apply to the current tip.
650    ///
651    /// # Security
652    ///
653    /// This method must be called at the end of every method that adds rejections.
654    /// Otherwise, peers could make our reject lists use a lot of RAM.
655    fn limit_rejection_list_memory(&mut self) {
656        // These lists are an optimisation - it's ok to totally clear them as needed.
657        if self.tip_rejected_exact.len() > MAX_EVICTION_MEMORY_ENTRIES {
658            self.tip_rejected_exact.clear();
659        }
660        if self.tip_rejected_same_effects.len() > MAX_EVICTION_MEMORY_ENTRIES {
661            self.tip_rejected_same_effects.clear();
662        }
663        // `chain_rejected_same_effects` limits its size by itself
664        self.update_rejected_metrics();
665    }
666
667    /// Returns the set of [`UnminedTxId`]s in the mempool.
668    pub fn tx_ids(&self) -> impl Iterator<Item = UnminedTxId> + '_ {
669        self.transactions().values().map(|tx| tx.transaction.id)
670    }
671
672    /// Returns a reference to the [`HashMap`] of [`VerifiedUnminedTx`]s in the verified set.
673    ///
674    /// Each [`VerifiedUnminedTx`] contains an [`UnminedTx`],
675    /// and adds extra fields from the transaction verifier result.
676    pub fn transactions(&self) -> &HashMap<transaction::Hash, VerifiedUnminedTx> {
677        self.verified.transactions()
678    }
679
680    /// Returns a reference to the [`TransactionDependencies`] in the verified set.
681    pub fn transaction_dependencies(&self) -> &TransactionDependencies {
682        self.verified.transaction_dependencies()
683    }
684
685    /// Returns a [`transparent::Output`] created by a mempool transaction for the provided
686    /// [`transparent::OutPoint`] if one exists, or None otherwise.
687    pub fn created_output(&self, outpoint: &transparent::OutPoint) -> Option<transparent::Output> {
688        self.verified.created_output(outpoint)
689    }
690
691    /// Returns true if a tx in the set has spent the output at the provided outpoint.
692    pub fn has_spent_outpoint(&self, outpoint: &transparent::OutPoint) -> bool {
693        self.verified.has_spent_outpoint(outpoint)
694    }
695
696    /// Returns the number of transactions in the mempool.
697    #[allow(dead_code)]
698    pub fn transaction_count(&self) -> usize {
699        self.verified.transaction_count()
700    }
701
702    /// Returns the cost of the transactions in the mempool, according to ZIP-401.
703    #[allow(dead_code)]
704    pub fn total_cost(&self) -> u64 {
705        self.verified.total_cost()
706    }
707
708    /// Returns the total serialized size of the verified transactions in the set.
709    ///
710    /// See [`VerifiedSet::total_serialized_size()`] for details.
711    pub fn total_serialized_size(&self) -> usize {
712        self.verified.total_serialized_size()
713    }
714
715    /// Returns the set of [`UnminedTx`]es with exactly matching `tx_ids` in the
716    /// mempool.
717    ///
718    /// This matches the exact transaction, with identical blockchain effects,
719    /// signatures, and proofs.
720    pub fn transactions_exact(
721        &self,
722        tx_ids: HashSet<UnminedTxId>,
723    ) -> impl Iterator<Item = &UnminedTx> {
724        tx_ids.into_iter().filter_map(|tx_id| {
725            self.transactions()
726                .get(&tx_id.mined_id())
727                .filter(|tx| tx.transaction.id == tx_id)
728                .map(|tx| &tx.transaction)
729        })
730    }
731
732    /// Returns the set of [`UnminedTx`]es with matching [`transaction::Hash`]es
733    /// in the mempool.
734    ///
735    /// This matches transactions with the same effects, regardless of
736    /// [`transaction::AuthDigest`].
737    pub fn transactions_same_effects(
738        &self,
739        tx_ids: HashSet<Hash>,
740    ) -> impl Iterator<Item = &UnminedTx> {
741        self.verified
742            .transactions()
743            .iter()
744            .filter(move |(tx_id, _)| tx_ids.contains(tx_id))
745            .map(|(_, tx)| &tx.transaction)
746    }
747
748    /// Returns a transaction and the transaction ids of its dependencies, if it is in the verified set.
749    pub fn transaction_with_deps(
750        &self,
751        tx_id: transaction::Hash,
752    ) -> Option<(VerifiedUnminedTx, HashSet<transaction::Hash>)> {
753        let tx = self.verified.transactions().get(&tx_id).cloned()?;
754        let deps = self
755            .verified
756            .transaction_dependencies()
757            .dependencies()
758            .get(&tx_id)
759            .cloned()
760            .unwrap_or_default();
761
762        Some((tx, deps))
763    }
764
765    /// Returns `true` if a transaction exactly matching an [`UnminedTxId`] is in
766    /// the mempool.
767    ///
768    /// This matches the exact transaction, with identical blockchain effects,
769    /// signatures, and proofs.
770    pub fn contains_transaction_exact(&self, tx_id: &transaction::Hash) -> bool {
771        self.verified.contains(tx_id)
772    }
773
774    /// Returns the number of rejected [`UnminedTxId`]s or [`transaction::Hash`]es.
775    ///
776    /// Transactions on multiple rejected lists are counted multiple times.
777    #[allow(dead_code)]
778    pub fn rejected_transaction_count(&mut self) -> usize {
779        self.tip_rejected_exact.len()
780            + self.tip_rejected_same_effects.len()
781            + self
782                .chain_rejected_same_effects
783                .iter_mut()
784                .map(|(_, map)| map.len())
785                .sum::<usize>()
786    }
787
788    /// Add a transaction to the rejected list for the given reason.
789    pub fn reject(&mut self, tx_id: UnminedTxId, reason: RejectionError) {
790        match reason {
791            RejectionError::ExactTip(e) => {
792                self.tip_rejected_exact.insert(tx_id, e);
793            }
794            RejectionError::SameEffectsTip(e) => {
795                self.tip_rejected_same_effects.insert(tx_id.mined_id(), e);
796            }
797            RejectionError::SameEffectsChain(e) => {
798                let eviction_memory_time = self.eviction_memory_time;
799                self.chain_rejected_same_effects
800                    .entry(e)
801                    .or_insert_with(|| {
802                        EvictionList::new(MAX_EVICTION_MEMORY_ENTRIES, eviction_memory_time)
803                    })
804                    .insert(tx_id.mined_id());
805            }
806            RejectionError::NonStandardTransaction(e) => {
807                // Non-standard transactions are rejected based on their exact
808                // transaction data.
809                self.tip_rejected_exact
810                    .insert(tx_id, ExactTipRejectionError::from(e));
811            }
812        }
813        self.limit_rejection_list_memory();
814    }
815
816    /// Returns the rejection error if a transaction matching an [`UnminedTxId`]
817    /// is in any mempool rejected list.
818    ///
819    /// This matches transactions based on each rejection list's matching rule.
820    ///
821    /// Returns an arbitrary error if the transaction is in multiple lists.
822    pub fn rejection_error(&self, txid: &UnminedTxId) -> Option<MempoolError> {
823        if let Some(error) = self.tip_rejected_exact.get(txid) {
824            return Some(error.clone().into());
825        }
826
827        if let Some(error) = self.tip_rejected_same_effects.get(&txid.mined_id()) {
828            return Some(error.clone().into());
829        }
830
831        for (error, set) in self.chain_rejected_same_effects.iter() {
832            if set.contains_key(&txid.mined_id()) {
833                return Some(error.clone().into());
834            }
835        }
836
837        None
838    }
839
840    /// Returns the set of [`UnminedTxId`]s matching `tx_ids` in the rejected list.
841    ///
842    /// This matches transactions based on each rejection list's matching rule.
843    pub fn rejected_transactions(
844        &self,
845        tx_ids: HashSet<UnminedTxId>,
846    ) -> impl Iterator<Item = UnminedTxId> + '_ {
847        tx_ids
848            .into_iter()
849            .filter(move |txid| self.contains_rejected(txid))
850    }
851
852    /// Returns `true` if a transaction matching the supplied [`UnminedTxId`] is in
853    /// the mempool rejected list.
854    ///
855    /// This matches transactions based on each rejection list's matching rule.
856    pub fn contains_rejected(&self, txid: &UnminedTxId) -> bool {
857        self.rejection_error(txid).is_some()
858    }
859
860    /// Add a transaction that failed download and verification to the rejected list
861    /// if needed, depending on the reason for the failure.
862    pub fn reject_if_needed(&mut self, tx_id: UnminedTxId, e: TransactionDownloadVerifyError) {
863        match e {
864            // Rejecting a transaction already in state would speed up further
865            // download attempts without checking the state. However it would
866            // make the reject list grow forever.
867            //
868            // TODO: revisit after reviewing the rejected list cleanup criteria?
869            // TODO: if we decide to reject it, then we need to pass the block hash
870            // to State::Confirmed. This would require the zs::Response::Transaction
871            // to include the hash, which would need to be implemented.
872            TransactionDownloadVerifyError::InState |
873            // An unknown error in the state service, better do nothing
874            TransactionDownloadVerifyError::StateError(_) |
875            // If download failed, do nothing; the crawler will end up trying to
876            // download it again.
877            TransactionDownloadVerifyError::DownloadFailed(_) |
878            // If it was cancelled then a block was mined, or there was a network
879            // upgrade, etc. No reason to reject it.
880            TransactionDownloadVerifyError::Cancelled => {}
881
882            // Consensus verification failed. Reject transaction to avoid
883            // having to download and verify it again just for it to fail again.
884            TransactionDownloadVerifyError::Invalid { error, .. }  => {
885                self.reject(tx_id, ExactTipRejectionError::FailedVerification(error).into())
886            }
887
888            // Rejected as non-standard before verification, cached like the storage-time check.
889            TransactionDownloadVerifyError::NonStandard(error) => self.reject(tx_id, error.into()),
890        }
891    }
892
893    /// Remove transactions from the mempool if they have not been mined after a
894    /// specified height, per [ZIP-203].
895    ///
896    /// > Transactions will have a new field, nExpiryHeight, which will set the
897    /// > block height after which transactions will be removed from the mempool
898    /// > if they have not been mined.
899    ///
900    ///
901    /// [ZIP-203]: https://zips.z.cash/zip-0203#specification
902    pub fn remove_expired_transactions(
903        &mut self,
904        tip_height: zebra_chain::block::Height,
905    ) -> HashSet<UnminedTxId> {
906        let mut tx_ids = HashSet::new();
907        let mut unmined_tx_ids = HashSet::new();
908
909        for (&tx_id, tx) in self.transactions() {
910            if let Some(expiry_height) = tx.transaction.transaction.expiry_height() {
911                if tip_height >= expiry_height {
912                    tx_ids.insert(tx_id);
913                    unmined_tx_ids.insert(tx.transaction.id);
914                }
915            }
916        }
917
918        // expiry height is effecting data, so we match by non-malleable TXID
919        self.verified
920            .remove_all_that(|tx| tx_ids.contains(&tx.transaction.id.mined_id()));
921
922        // also reject it
923        for id in tx_ids {
924            self.reject(
925                // It's okay to omit the auth digest here as we know that `reject()` will always
926                // use mined ids for `SameEffectsChainRejectionError`s.
927                UnminedTxId::Legacy(id),
928                SameEffectsChainRejectionError::Expired.into(),
929            );
930        }
931
932        unmined_tx_ids
933    }
934
935    /// Check if transaction should be downloaded and/or verified.
936    ///
937    /// If it is already in the mempool (or in its rejected list)
938    /// then it shouldn't be downloaded/verified.
939    pub fn should_download_or_verify(&mut self, txid: UnminedTxId) -> Result<(), MempoolError> {
940        // Check if the transaction is already in the mempool.
941        if self.contains_transaction_exact(&txid.mined_id()) {
942            return Err(MempoolError::InMempool);
943        }
944        if let Some(error) = self.rejection_error(&txid) {
945            return Err(error);
946        }
947        Ok(())
948    }
949
950    /// Update metrics related to the rejected lists.
951    ///
952    /// Must be called every time the rejected lists change.
953    fn update_rejected_metrics(&mut self) {
954        let rejected_count = self.rejected_transaction_count();
955        metrics::gauge!("mempool.rejected.transaction.ids",).set(rejected_count as f64);
956        // This is just an approximation.
957        // TODO: make it more accurate #2869
958        let item_size = size_of::<(transaction::Hash, SameEffectsTipRejectionError)>();
959        metrics::gauge!("mempool.rejected.transaction.ids.bytes",)
960            .set((rejected_count * item_size) as f64);
961    }
962}