Skip to main content

zebrad/components/mempool/storage/
verified_set.rs

1//! The set of verified transactions in the mempool.
2
3use std::{
4    borrow::Cow,
5    collections::{HashMap, HashSet},
6    hash::Hash,
7};
8
9use zebra_chain::{
10    block::Height,
11    ironwood, orchard, sapling, sprout,
12    transaction::{self, UnminedTx, UnminedTxId, VerifiedUnminedTx},
13    transparent,
14};
15use zebra_node_services::mempool::TransactionDependencies;
16
17use crate::components::mempool::pending_outputs::PendingOutputs;
18
19use super::super::SameEffectsTipRejectionError;
20
21// Imports for doc links
22#[allow(unused_imports)]
23use zebra_chain::transaction::MEMPOOL_TRANSACTION_COST_THRESHOLD;
24
25/// The set of verified transactions stored in the mempool.
26///
27/// This also caches the all the spent outputs from the transactions in the mempool. The spent
28/// outputs include:
29///
30/// - the dependencies of transactions that spent the outputs of other transactions in the mempool
31/// - the outputs of transactions in the mempool
32/// - the transparent outpoints spent by transactions in the mempool
33/// - the Sprout nullifiers revealed by transactions in the mempool
34/// - the Sapling nullifiers revealed by transactions in the mempool
35/// - the Orchard nullifiers revealed by transactions in the mempool
36/// - the Ironwood nullifiers revealed by transactions in the mempool
37#[derive(Default)]
38pub struct VerifiedSet {
39    /// The set of verified transactions in the mempool.
40    transactions: HashMap<transaction::Hash, VerifiedUnminedTx>,
41
42    /// A map of dependencies between transactions in the mempool that
43    /// spend or create outputs of other transactions in the mempool.
44    transaction_dependencies: TransactionDependencies,
45
46    /// The [`transparent::Output`]s created by verified transactions in the mempool.
47    ///
48    /// These outputs may be spent by other transactions in the mempool.
49    created_outputs: HashMap<transparent::OutPoint, transparent::Output>,
50
51    /// The total size of the transactions in the mempool if they were
52    /// serialized.
53    transactions_serialized_size: usize,
54
55    /// The total cost of the verified transactions in the set.
56    total_cost: u64,
57
58    /// The set of spent out points by the verified transactions.
59    spent_outpoints: HashSet<transparent::OutPoint>,
60
61    /// The set of revealed Sprout nullifiers.
62    sprout_nullifiers: HashSet<sprout::Nullifier>,
63
64    /// The set of revealed Sapling nullifiers.
65    sapling_nullifiers: HashSet<sapling::Nullifier>,
66
67    /// The set of revealed Orchard nullifiers.
68    orchard_nullifiers: HashSet<orchard::Nullifier>,
69
70    /// The set of revealed Ironwood nullifiers.
71    ironwood_nullifiers: HashSet<ironwood::Nullifier>,
72}
73
74impl Drop for VerifiedSet {
75    fn drop(&mut self) {
76        // zero the metrics on drop
77        self.clear()
78    }
79}
80
81impl VerifiedSet {
82    /// Returns a reference to the [`HashMap`] of [`VerifiedUnminedTx`]s in the set.
83    pub fn transactions(&self) -> &HashMap<transaction::Hash, VerifiedUnminedTx> {
84        &self.transactions
85    }
86
87    /// Returns a reference to the [`TransactionDependencies`] in the set.
88    pub fn transaction_dependencies(&self) -> &TransactionDependencies {
89        &self.transaction_dependencies
90    }
91
92    /// Returns a [`transparent::Output`] created by a mempool transaction for the provided
93    /// [`transparent::OutPoint`] if one exists, or None otherwise.
94    pub fn created_output(&self, outpoint: &transparent::OutPoint) -> Option<transparent::Output> {
95        self.created_outputs.get(outpoint).cloned()
96    }
97
98    /// Returns true if a tx in the set has spent the output at the provided outpoint.
99    pub fn has_spent_outpoint(&self, outpoint: &transparent::OutPoint) -> bool {
100        self.spent_outpoints.contains(outpoint)
101    }
102
103    /// Returns the number of verified transactions in the set.
104    pub fn transaction_count(&self) -> usize {
105        self.transactions.len()
106    }
107
108    /// Returns the total cost of the verified transactions in the set.
109    ///
110    /// [ZIP-401]: https://zips.z.cash/zip-0401
111    pub fn total_cost(&self) -> u64 {
112        self.total_cost
113    }
114
115    /// Returns the total serialized size of the verified transactions in the set.
116    ///
117    /// This can be less than the total cost, because the minimum transaction cost
118    /// is based on the [`MEMPOOL_TRANSACTION_COST_THRESHOLD`].
119    pub fn total_serialized_size(&self) -> usize {
120        self.transactions_serialized_size
121    }
122
123    /// Returns `true` if the set of verified transactions contains the transaction with the
124    /// specified [`transaction::Hash`].
125    pub fn contains(&self, id: &transaction::Hash) -> bool {
126        self.transactions.contains_key(id)
127    }
128
129    /// Clear the set of verified transactions.
130    ///
131    /// Also clears all internal caches.
132    pub fn clear(&mut self) {
133        self.transactions.clear();
134        self.transaction_dependencies.clear();
135        self.spent_outpoints.clear();
136        self.sprout_nullifiers.clear();
137        self.sapling_nullifiers.clear();
138        self.orchard_nullifiers.clear();
139        self.ironwood_nullifiers.clear();
140        self.created_outputs.clear();
141        self.transactions_serialized_size = 0;
142        self.total_cost = 0;
143        self.update_metrics();
144    }
145
146    /// Insert a `transaction` into the set.
147    ///
148    /// Returns an error if the `transaction` has spend conflicts with any other transaction
149    /// already in the set.
150    ///
151    /// Two transactions have a spend conflict if they spend the same UTXO or if they reveal the
152    /// same nullifier.
153    pub fn insert(
154        &mut self,
155        mut transaction: VerifiedUnminedTx,
156        spent_mempool_outpoints: Vec<transparent::OutPoint>,
157        pending_outputs: &mut PendingOutputs,
158        height: Option<Height>,
159    ) -> Result<(), SameEffectsTipRejectionError> {
160        if self.has_spend_conflicts(&transaction.transaction) {
161            return Err(SameEffectsTipRejectionError::SpendConflict);
162        }
163
164        // This likely only needs to check that the transaction hash of the outpoint is still in the mempool,
165        // but it's likely rare that a transaction spends multiple transparent outputs of
166        // a single transaction in practice.
167        for outpoint in &spent_mempool_outpoints {
168            if !self.created_outputs.contains_key(outpoint) {
169                return Err(SameEffectsTipRejectionError::MissingOutput);
170            }
171        }
172
173        let tx_id = transaction.transaction.id.mined_id();
174        self.transaction_dependencies
175            .add(tx_id, spent_mempool_outpoints);
176
177        // Inserts the transaction's outputs into the internal caches and responds to pending output requests.
178        let tx = &transaction.transaction.transaction;
179        for (index, output) in tx.outputs().iter().cloned().enumerate() {
180            let outpoint = transparent::OutPoint::from_usize(tx_id, index);
181            self.created_outputs.insert(outpoint, output.clone());
182            pending_outputs.respond(&outpoint, output)
183        }
184
185        self.spent_outpoints.extend(tx.spent_outpoints());
186        self.sprout_nullifiers.extend(tx.sprout_nullifiers());
187        self.sapling_nullifiers.extend(tx.sapling_nullifiers());
188        self.orchard_nullifiers.extend(tx.orchard_nullifiers());
189        self.ironwood_nullifiers.extend(tx.ironwood_nullifiers());
190
191        self.transactions_serialized_size += transaction.transaction.size;
192        self.total_cost += transaction.cost();
193        transaction.time = Some(chrono::Utc::now());
194        // The block verifier reuses this transaction's verification in blocks in the same
195        // verification rules epoch as `height + 1`, so `height` must be the tip height the
196        // transaction was verified on. `Mempool::poll_ready` only inserts a transaction while its
197        // verification tip height is still the best tip height. See `VerifiedUnminedTx::height`.
198        transaction.height = height;
199        self.transactions.insert(tx_id, transaction);
200
201        self.update_metrics();
202
203        Ok(())
204    }
205
206    /// Evict one transaction and any transactions that directly or indirectly depend on
207    /// its outputs from the set, returns the victim transaction and any dependent transactions.
208    ///
209    /// Removes a transaction with probability in direct proportion to the
210    /// eviction weight, as per [ZIP-401].
211    ///
212    /// Consensus rule:
213    ///
214    /// > Each transaction also has an eviction weight, which is cost +
215    /// > low_fee_penalty, where low_fee_penalty is 16000 if the transaction pays
216    /// > a fee less than the conventional fee, otherwise 0. The conventional fee
217    /// > is currently defined as 1000 zatoshis
218    ///
219    /// # Note
220    ///
221    /// Collecting and calculating weights is O(n). But in practice n is limited
222    /// to 20,000 (mempooltxcostlimit/min(cost)), so the actual cost shouldn't
223    /// be too bad.
224    ///
225    /// This function is equivalent to `EvictTransaction` in [ZIP-401].
226    ///
227    /// [ZIP-401]: https://zips.z.cash/zip-0401
228    #[allow(clippy::unwrap_in_result)]
229    pub fn evict_one(&mut self) -> Option<VerifiedUnminedTx> {
230        use rand::distr::{weighted::WeightedIndex, Distribution};
231
232        let (keys, weights): (Vec<transaction::Hash>, Vec<u64>) = self
233            .transactions
234            .iter()
235            .map(|(&tx_id, tx)| (tx_id, tx.eviction_weight()))
236            .unzip();
237
238        let dist = WeightedIndex::new(weights).expect(
239            "there is at least one weight, all weights are non-negative, and the total is positive",
240        );
241
242        let key_to_remove = keys
243            .get(dist.sample(&mut rand::rng()))
244            .expect("should have a key at every index in the distribution");
245
246        // Removes the randomly selected transaction and all of its dependents from the set,
247        // then returns just the randomly selected transaction
248        self.remove(key_to_remove).pop()
249    }
250
251    /// Clears a list of mined transaction ids from the lists of dependencies for
252    /// any other transactions in the mempool and removes their dependents.
253    pub fn clear_mined_dependencies(&mut self, mined_ids: &HashSet<transaction::Hash>) {
254        self.transaction_dependencies
255            .clear_mined_dependencies(mined_ids);
256    }
257
258    /// Removes all transactions in the set that match the `predicate`.
259    ///
260    /// Returns the amount of transactions removed.
261    pub fn remove_all_that(
262        &mut self,
263        predicate: impl Fn(&VerifiedUnminedTx) -> bool,
264    ) -> HashSet<UnminedTxId> {
265        let keys_to_remove: Vec<_> = self
266            .transactions
267            .iter()
268            .filter_map(|(&tx_id, tx)| predicate(tx).then_some(tx_id))
269            .collect();
270
271        let mut removed_transactions = HashSet::new();
272
273        for key_to_remove in keys_to_remove {
274            if !self.transactions.contains_key(&key_to_remove) {
275                // Skip any keys that may have already been removed as their dependencies were removed.
276                continue;
277            }
278
279            removed_transactions.extend(
280                self.remove(&key_to_remove)
281                    .into_iter()
282                    .map(|tx| tx.transaction.id),
283            );
284        }
285
286        removed_transactions
287    }
288
289    /// Accepts a transaction id for a transaction to remove from the verified set.
290    ///
291    /// Removes the transaction and any transactions that directly or indirectly
292    /// depend on it from the set.
293    ///
294    /// Returns a list of transactions that have been removed with the target transaction
295    /// as the last item.
296    ///
297    /// Also removes the outputs of any removed transactions from the internal caches.
298    fn remove(&mut self, key_to_remove: &transaction::Hash) -> Vec<VerifiedUnminedTx> {
299        let removed_transactions: Vec<_> = self
300            .transaction_dependencies
301            .remove_all(key_to_remove)
302            .iter()
303            .chain(std::iter::once(key_to_remove))
304            .filter_map(|key_to_remove| {
305                let Some(removed_tx) = self.transactions.remove(key_to_remove) else {
306                    tracing::warn!(?key_to_remove, "invalid transaction key");
307                    return None;
308                };
309
310                self.transactions_serialized_size -= removed_tx.transaction.size;
311                self.total_cost -= removed_tx.cost();
312                self.remove_outputs(&removed_tx.transaction);
313
314                Some(removed_tx)
315            })
316            .collect();
317
318        self.update_metrics();
319        removed_transactions
320    }
321
322    /// Returns `true` if the given `transaction` has any spend conflicts with transactions in the
323    /// mempool.
324    ///
325    /// Two transactions have a spend conflict if they spend the same UTXO or if they reveal the
326    /// same nullifier.
327    fn has_spend_conflicts(&self, unmined_tx: &UnminedTx) -> bool {
328        let tx = &unmined_tx.transaction;
329
330        Self::has_conflicts(&self.spent_outpoints, tx.spent_outpoints())
331            || Self::has_conflicts(&self.sprout_nullifiers, tx.sprout_nullifiers())
332            || Self::has_conflicts(&self.sapling_nullifiers, tx.sapling_nullifiers())
333            || Self::has_conflicts(&self.orchard_nullifiers, tx.orchard_nullifiers())
334            || Self::has_conflicts(&self.ironwood_nullifiers, tx.ironwood_nullifiers())
335    }
336
337    /// Removes the tracked transaction outputs from the mempool.
338    fn remove_outputs(&mut self, unmined_tx: &UnminedTx) {
339        let tx = &unmined_tx.transaction;
340
341        for index in 0..tx.outputs().len() {
342            self.created_outputs
343                .remove(&transparent::OutPoint::from_usize(
344                    unmined_tx.id.mined_id(),
345                    index,
346                ));
347        }
348
349        let spent_outpoints = tx.spent_outpoints().map(Cow::Owned);
350
351        // All the nullifier accessors yield owned nullifiers, so they are wrapped as `Cow::Owned`.
352        // They are collected first so `tx` is no longer borrowed while `self` is mutated.
353        let sprout_nfs: Vec<_> = tx.sprout_nullifiers().collect();
354        let sapling_nfs: Vec<_> = tx.sapling_nullifiers().collect();
355        let orchard_nfs: Vec<_> = tx.orchard_nullifiers().collect();
356        let ironwood_nfs: Vec<_> = tx.ironwood_nullifiers().collect();
357
358        Self::remove_from_set(&mut self.spent_outpoints, spent_outpoints);
359        Self::remove_from_set(
360            &mut self.sprout_nullifiers,
361            sprout_nfs.into_iter().map(Cow::Owned),
362        );
363        Self::remove_from_set(
364            &mut self.sapling_nullifiers,
365            sapling_nfs.into_iter().map(Cow::Owned),
366        );
367        Self::remove_from_set(
368            &mut self.orchard_nullifiers,
369            orchard_nfs.into_iter().map(Cow::Owned),
370        );
371        Self::remove_from_set(
372            &mut self.ironwood_nullifiers,
373            ironwood_nfs.into_iter().map(Cow::Owned),
374        );
375    }
376
377    /// Returns `true` if the two sets have common items.
378    fn has_conflicts<T>(set: &HashSet<T>, mut list: impl Iterator<Item = T>) -> bool
379    where
380        T: Eq + Hash,
381    {
382        list.any(|item| set.contains(&item))
383    }
384
385    /// Removes some items from a [`HashSet`].
386    ///
387    /// Each item in the list of `items` should be wrapped in a [`Cow`]. This allows this generic
388    /// method to support both borrowed and owned items.
389    fn remove_from_set<'t, T>(set: &mut HashSet<T>, items: impl IntoIterator<Item = Cow<'t, T>>)
390    where
391        T: Clone + Eq + Hash + 't,
392    {
393        for item in items {
394            set.remove(&item);
395        }
396    }
397
398    fn update_metrics(&mut self) {
399        // Track the sum of unpaid actions within each transaction (as they are subject to the
400        // unpaid action limit). Transactions that have weight >= 1 have no unpaid actions by
401        // definition.
402        let mut unpaid_actions_with_weight_lt20pct = 0;
403        let mut unpaid_actions_with_weight_lt40pct = 0;
404        let mut unpaid_actions_with_weight_lt60pct = 0;
405        let mut unpaid_actions_with_weight_lt80pct = 0;
406        let mut unpaid_actions_with_weight_lt1 = 0;
407
408        // Track the total number of paid actions across all transactions in the mempool. This
409        // added to the bucketed unpaid actions above is equal to the total number of conventional
410        // actions in the mempool.
411        let mut paid_actions = 0;
412
413        // Track the sum of transaction sizes (the metric by which they are mainly limited) across
414        // several buckets.
415        let mut size_with_weight_lt1 = 0;
416        let mut size_with_weight_eq1 = 0;
417        let mut size_with_weight_gt1 = 0;
418        let mut size_with_weight_gt2 = 0;
419        let mut size_with_weight_gt3 = 0;
420
421        for entry in self.transactions().values() {
422            paid_actions += entry.conventional_actions - entry.unpaid_actions;
423
424            if entry.fee_weight_ratio > 3.0 {
425                size_with_weight_gt3 += entry.transaction.size;
426            } else if entry.fee_weight_ratio > 2.0 {
427                size_with_weight_gt2 += entry.transaction.size;
428            } else if entry.fee_weight_ratio > 1.0 {
429                size_with_weight_gt1 += entry.transaction.size;
430            } else if entry.fee_weight_ratio == 1.0 {
431                size_with_weight_eq1 += entry.transaction.size;
432            } else {
433                size_with_weight_lt1 += entry.transaction.size;
434                if entry.fee_weight_ratio < 0.2 {
435                    unpaid_actions_with_weight_lt20pct += entry.unpaid_actions;
436                } else if entry.fee_weight_ratio < 0.4 {
437                    unpaid_actions_with_weight_lt40pct += entry.unpaid_actions;
438                } else if entry.fee_weight_ratio < 0.6 {
439                    unpaid_actions_with_weight_lt60pct += entry.unpaid_actions;
440                } else if entry.fee_weight_ratio < 0.8 {
441                    unpaid_actions_with_weight_lt80pct += entry.unpaid_actions;
442                } else {
443                    unpaid_actions_with_weight_lt1 += entry.unpaid_actions;
444                }
445            }
446        }
447
448        metrics::gauge!(
449            "zcash.mempool.actions.unpaid",
450            "bk" => "< 0.2",
451        )
452        .set(unpaid_actions_with_weight_lt20pct as f64);
453        metrics::gauge!(
454            "zcash.mempool.actions.unpaid",
455            "bk" => "< 0.4",
456        )
457        .set(unpaid_actions_with_weight_lt40pct as f64);
458        metrics::gauge!(
459            "zcash.mempool.actions.unpaid",
460            "bk" => "< 0.6",
461        )
462        .set(unpaid_actions_with_weight_lt60pct as f64);
463        metrics::gauge!(
464            "zcash.mempool.actions.unpaid",
465            "bk" => "< 0.8",
466        )
467        .set(unpaid_actions_with_weight_lt80pct as f64);
468        metrics::gauge!(
469            "zcash.mempool.actions.unpaid",
470            "bk" => "< 1",
471        )
472        .set(unpaid_actions_with_weight_lt1 as f64);
473        metrics::gauge!("zcash.mempool.actions.paid").set(paid_actions as f64);
474        metrics::gauge!("zcash.mempool.size.transactions",).set(self.transaction_count() as f64);
475        metrics::gauge!(
476            "zcash.mempool.size.weighted",
477            "bk" => "< 1",
478        )
479        .set(size_with_weight_lt1 as f64);
480        metrics::gauge!(
481            "zcash.mempool.size.weighted",
482            "bk" => "1",
483        )
484        .set(size_with_weight_eq1 as f64);
485        metrics::gauge!(
486            "zcash.mempool.size.weighted",
487            "bk" => "> 1",
488        )
489        .set(size_with_weight_gt1 as f64);
490        metrics::gauge!(
491            "zcash.mempool.size.weighted",
492            "bk" => "> 2",
493        )
494        .set(size_with_weight_gt2 as f64);
495        metrics::gauge!(
496            "zcash.mempool.size.weighted",
497            "bk" => "> 3",
498        )
499        .set(size_with_weight_gt3 as f64);
500        metrics::gauge!("zcash.mempool.size.bytes",).set(self.transactions_serialized_size as f64);
501        metrics::gauge!("zcash.mempool.cost.bytes").set(self.total_cost as f64);
502    }
503}