Skip to main content

zebrad/components/mempool/storage/
eviction_list.rs

1//! [`EvictionList`] represents the transaction eviction list with
2//! efficient operations.
3use std::{
4    collections::{HashMap, VecDeque},
5    time::Duration,
6};
7
8#[cfg(not(test))]
9use std::time::Instant;
10#[cfg(test)]
11use tokio::time::Instant;
12
13use zebra_chain::transaction;
14
15/// An eviction list that allows Zebra to efficiently add entries, get entries,
16/// and remove older entries in the order they were inserted.
17pub struct EvictionList {
18    // Maps each TXID in the list to the most recent instant they were added.
19    unique_entries: HashMap<transaction::Hash, Instant>,
20    // The same as `unique_entries` but in the order they were inserted.
21    ordered_entries: VecDeque<transaction::Hash>,
22    // The maximum size of `unique_entries`.
23    max_size: usize,
24    /// The mempool transaction eviction age limit.
25    /// Same as [`Config::eviction_memory_time`][1].
26    ///
27    /// [1]: super::super::Config::eviction_memory_time
28    eviction_memory_time: Duration,
29}
30
31impl EvictionList {
32    /// Create a new [`EvictionList`] with the given maximum size and
33    /// eviction time.
34    pub fn new(max_size: usize, eviction_memory_time: Duration) -> Self {
35        Self {
36            unique_entries: Default::default(),
37            ordered_entries: Default::default(),
38            max_size,
39            eviction_memory_time,
40        }
41    }
42
43    /// Inserts a TXID in the list, keeping track of the time it was inserted.
44    ///
45    /// All entries older than [`EvictionList::eviction_memory_time`] will be removed.
46    ///
47    /// # Panics
48    ///
49    /// If the TXID is already in the list.
50    ///
51    pub fn insert(&mut self, key: transaction::Hash) {
52        // From https://zips.z.cash/zip-0401#specification:
53        // > Nodes SHOULD remove transactions from RecentlyEvicted that were evicted more than
54        // > mempoolevictionmemoryminutes minutes ago. This MAY be done periodically,
55        // > and/or just before RecentlyEvicted is accessed when receiving a transaction.
56        self.prune_old();
57        // > Add the txid and the current time to RecentlyEvicted, dropping the oldest entry
58        // > in RecentlyEvicted if necessary to keep it to at most eviction_memory_entries entries.
59        if self.len() >= self.max_size {
60            self.pop_front();
61        }
62        let value = Instant::now();
63        let old_value = self.unique_entries.insert(key, value);
64        // It should be impossible for an already-evicted transaction to be evicted
65        // again since transactions are not added to the mempool if they are evicted,
66        // and the mempool doesn't allow inserting two transactions with the same
67        // hash (they would conflict).
68        assert_eq!(
69            old_value, None,
70            "an already-evicted transaction should not be evicted again"
71        );
72        self.ordered_entries.push_back(key)
73    }
74
75    /// Checks if the given TXID is in the list.
76    pub fn contains_key(&self, txid: &transaction::Hash) -> bool {
77        if let Some(evicted_at) = self.unique_entries.get(txid) {
78            // Since the list is pruned only in mutable functions, make sure
79            // we take expired items into account.
80            if !self.has_expired(evicted_at) {
81                return true;
82            }
83        }
84        false
85    }
86
87    /// Get the size of the list.
88    //
89    // Note: if this method being mutable becomes an issue, it's possible
90    // to compute the number of expired transactions and subtract,
91    // at the cost of `O(len + expired)` performance each time the method is called.
92    //
93    // Currently the performance is `O(expired)` for the first call, then `O(1)` until the next expiry.
94    pub fn len(&mut self) -> usize {
95        self.prune_old();
96        self.unique_entries.len()
97    }
98
99    /// Clear the list.
100    #[allow(dead_code)]
101    pub fn clear(&mut self) {
102        self.unique_entries.clear();
103        self.ordered_entries.clear();
104    }
105
106    /// Prune TXIDs that are older than `eviction_time` ago.
107    ///
108    // This method is public because ZIP-401 states about pruning:
109    // > This MAY be done periodically,
110    pub fn prune_old(&mut self) {
111        while let Some(txid) = self.front() {
112            let evicted_at = self
113                .unique_entries
114                .get(txid)
115                .unwrap_or_else(|| panic!("all entries should exist in both ordered_entries and unique_entries, missing {txid:?} in unique_entries"));
116            if self.has_expired(evicted_at) {
117                self.pop_front();
118            } else {
119                break;
120            }
121        }
122    }
123
124    /// Get the oldest TXID in the list.
125    fn front(&self) -> Option<&transaction::Hash> {
126        self.ordered_entries.front()
127    }
128
129    /// Removes the first element and returns it, or `None` if the `EvictionList`
130    /// is empty.
131    fn pop_front(&mut self) -> Option<transaction::Hash> {
132        if let Some(key) = self.ordered_entries.pop_front() {
133            let removed = self.unique_entries.remove(&key);
134            assert!(
135                removed.is_some(),
136                "all entries should exist in both ordered_entries and unique_entries, missing {key:?} in unique_entries"
137            );
138            Some(key)
139        } else {
140            None
141        }
142    }
143
144    /// Returns if `evicted_at` is considered expired considering the current
145    /// time and the configured eviction time.
146    fn has_expired(&self, evicted_at: &Instant) -> bool {
147        let now = Instant::now();
148        (now - *evicted_at) > self.eviction_memory_time
149    }
150}