zebra_node_services/mempool.rs
1//! The Zebra mempool.
2//!
3//! A service that manages known unmined Zcash transactions.
4
5use std::{
6 collections::{HashMap, HashSet},
7 net::SocketAddr,
8 sync::Arc,
9};
10
11use tokio::sync::oneshot;
12use zebra_chain::{
13 block,
14 transaction::{self, UnminedTx, UnminedTxId, VerifiedUnminedTx},
15 transparent,
16};
17
18use crate::BoxError;
19
20mod gossip;
21mod mempool_change;
22mod service_trait;
23mod transaction_dependencies;
24
25pub use self::{
26 gossip::Gossip,
27 mempool_change::{MempoolChange, MempoolChangeKind, MempoolTxSubscriber},
28 service_trait::MempoolService,
29 transaction_dependencies::TransactionDependencies,
30};
31
32/// A mempool service request.
33///
34/// Requests can query the current set of mempool transactions,
35/// queue transactions to be downloaded and verified, or
36/// run the mempool to check for newly verified transactions.
37///
38/// Requests can't modify the mempool directly,
39/// because all mempool transactions must be verified.
40#[derive(Debug, Eq, PartialEq)]
41pub enum Request {
42 /// Query all [`UnminedTxId`]s in the mempool.
43 TransactionIds,
44
45 /// Query matching [`UnminedTx`] in the mempool,
46 /// using a unique set of [`UnminedTxId`]s.
47 TransactionsById(HashSet<UnminedTxId>),
48
49 /// Query matching [`UnminedTx`] in the mempool,
50 /// using a unique set of [`transaction::Hash`]es. Pre-V5 transactions are matched
51 /// directly; V5 transaction are matched just by the Hash, disregarding
52 /// the [`AuthDigest`](zebra_chain::transaction::AuthDigest).
53 TransactionsByMinedId(HashSet<transaction::Hash>),
54
55 /// Query verified candidates for a block by their mined hashes.
56 ///
57 /// Returns no candidates if the mempool is disabled, its last seen tip differs from
58 /// the parent, or the request exceeds the block transaction allocation limit.
59 /// Callers must check full [`UnminedTxId`]s, the verification rules epoch, and
60 /// block-specific consensus rules before reuse. Missing verification heights are not reusable.
61 ///
62 /// # Correctness
63 ///
64 /// The block verifier in `zebra-consensus` trusts the transactions in the response, apart from
65 /// the rules that it checks again for each block. It doesn't look up their spent outputs or
66 /// verify their scripts, proofs and signatures, and it adds their
67 /// [`miner_fee`](VerifiedUnminedTx::miner_fee) and signature operation counts to the block's
68 /// totals, which the block's miner fee and signature operation limit checks use.
69 ///
70 /// So a mempool service must only return transactions when its last seen tip is
71 /// `parent_hash`. For each transaction, it must return the [`VerifiedUnminedTx`] that the
72 /// mempool transaction verifier in `zebra-consensus` returned for it, with every field
73 /// unmodified, apart from [`VerifiedUnminedTx::time`] and [`VerifiedUnminedTx::height`], which
74 /// the mempool sets when it stores the transaction. The unmodified fields are the transaction,
75 /// its miner fee, its signature operation counts, its spent outputs, and the fields computed
76 /// from them. `height` must be the tip height that the transaction was verified at, one below
77 /// the height of the next block that the verifier checked it for. A response can leave out any
78 /// transaction, or be empty.
79 ///
80 /// A later change to a transaction's fee, such as a fee delta that prioritises it in block
81 /// templates, must be kept in a separate field, never in `miner_fee`, which must stay the fee
82 /// that the verifier computed.
83 VerifiedTransactionsForBlock {
84 /// Mined hashes of the candidate block's transactions.
85 transaction_hashes: Arc<[transaction::Hash]>,
86 /// Parent hash of the candidate block.
87 parent_hash: block::Hash,
88 },
89
90 /// Request a [`transparent::Output`] identified by the given [`OutPoint`](transparent::OutPoint),
91 /// waiting until it becomes available if it is unknown.
92 ///
93 /// This request is purely informational, and there are no guarantees about
94 /// whether the UTXO remains unspent or is on the best chain, or any chain.
95 /// Its purpose is to allow orphaned mempool transaction verification.
96 ///
97 /// # Correctness
98 ///
99 /// Output requests should be wrapped in a timeout, so that
100 /// out-of-order and invalid requests do not hang indefinitely.
101 ///
102 /// Outdated requests are pruned on a regular basis.
103 AwaitOutput(transparent::OutPoint),
104
105 /// Request a [`VerifiedUnminedTx`] and its dependencies by its mined id.
106 TransactionWithDepsByMinedId(transaction::Hash),
107
108 /// Get all the [`VerifiedUnminedTx`] in the mempool.
109 ///
110 /// Equivalent to `TransactionsById(TransactionIds)`,
111 /// but each transaction also includes the `miner_fee` and `legacy_sigop_count` fields.
112 //
113 // TODO: make the Transactions response return VerifiedUnminedTx,
114 // and remove the FullTransactions variant
115 FullTransactions,
116
117 /// Query matching cached rejected transaction IDs in the mempool,
118 /// using a unique set of [`UnminedTxId`]s.
119 RejectedTransactionIds(HashSet<UnminedTxId>),
120
121 /// Queue a list of gossiped transactions or transaction IDs, or
122 /// crawled transaction IDs.
123 ///
124 /// The transaction downloader checks for duplicates across IDs and transactions.
125 Queue(Vec<Gossip>),
126
127 /// Queue candidate transactions received from a specific peer — either
128 /// transaction IDs advertised via an `Inv` message, or a full transaction
129 /// pushed via a `Tx` message — tagging each one with the sending peer so the
130 /// downloader can enforce a per-peer queue cap. This routes every
131 /// peer-originated candidate through the same per-peer admission accounting,
132 /// so a single peer cannot crowd out honest peers' transaction relay.
133 /// See `GHSA-4fc2-h7jh-287c` and `GHSA-m9xx-8rcj-vmgp`.
134 QueueFromPeer {
135 /// The candidate transactions received from the peer.
136 candidates: Vec<Gossip>,
137 /// The address of the peer that sent them.
138 source: SocketAddr,
139 },
140
141 /// Check for newly verified transactions.
142 ///
143 /// The transaction downloader does not push transactions into the mempool.
144 /// So a task should send this request regularly (every 5-10 seconds).
145 ///
146 /// These checks also happen for other request variants,
147 /// but we can't rely on peers to send queries regularly,
148 /// and crawler queue requests depend on peer responses.
149 /// Also, crawler requests aren't frequent enough for transaction propagation.
150 ///
151 /// # Correctness
152 ///
153 /// This request is required to avoid hangs in the mempool.
154 ///
155 /// The queue checker task can't call `poll_ready` directly on the mempool
156 /// service, because the service is wrapped in a `Buffer`. Calling
157 /// `Buffer::poll_ready` reserves a buffer slot, which can cause hangs
158 /// when too many slots are reserved but unused:
159 /// <https://docs.rs/tower/0.4.10/tower/buffer/struct.Buffer.html#a-note-on-choosing-a-bound>
160 CheckForVerifiedTransactions,
161
162 /// Request summary statistics from the mempool for `getmempoolinfo`.
163 QueueStats,
164
165 /// Check whether a transparent output is spent in the mempool.
166 UnspentOutput(transparent::OutPoint),
167}
168
169/// A response to a mempool service request.
170///
171/// Responses can read the current set of mempool transactions,
172/// check the queued status of transactions to be downloaded and verified, or
173/// confirm that the mempool has been checked for newly verified transactions.
174#[derive(Debug)]
175pub enum Response {
176 /// Returns all [`UnminedTxId`]s from the mempool.
177 TransactionIds(HashSet<UnminedTxId>),
178
179 /// Returns matching [`UnminedTx`] from the mempool.
180 ///
181 /// Since the [`Request::TransactionsById`] request is unique,
182 /// the response transactions are also unique. The same applies to
183 /// [`Request::TransactionsByMinedId`] requests, since the mempool does not allow
184 /// different transactions with different mined IDs.
185 Transactions(Vec<UnminedTx>),
186
187 /// Verified candidates for [`Request::VerifiedTransactionsForBlock`], by mined hash.
188 ///
189 /// Contains only requested mined hashes. Each transaction is the mempool transaction verifier's
190 /// unmodified output, with the tip height that it was verified at. See the request's
191 /// correctness rules.
192 VerifiedTransactionsForBlock(HashMap<transaction::Hash, VerifiedUnminedTx>),
193
194 /// Response to [`Request::AwaitOutput`] with the transparent output
195 UnspentOutput(transparent::Output),
196
197 /// Response to [`Request::TransactionWithDepsByMinedId`].
198 TransactionWithDeps {
199 /// The queried transaction
200 transaction: VerifiedUnminedTx,
201 /// A list of dependencies of the queried transaction.
202 dependencies: HashSet<transaction::Hash>,
203 },
204
205 /// Returns all [`VerifiedUnminedTx`] in the mempool.
206 //
207 // TODO: make the Transactions response return VerifiedUnminedTx,
208 // and remove the FullTransactions variant
209 FullTransactions {
210 /// All [`VerifiedUnminedTx`]s in the mempool
211 transactions: Vec<VerifiedUnminedTx>,
212
213 /// All transaction dependencies in the mempool
214 transaction_dependencies: TransactionDependencies,
215
216 /// Last seen chain tip hash by mempool service
217 last_seen_tip_hash: zebra_chain::block::Hash,
218 },
219
220 /// Returns matching cached rejected [`UnminedTxId`]s from the mempool,
221 RejectedTransactionIds(HashSet<UnminedTxId>),
222
223 /// Returns a list of initial queue checks results and a oneshot receiver
224 /// for awaiting download and/or verification results.
225 ///
226 /// Each result matches the request at the corresponding vector index.
227 Queued(Vec<Result<oneshot::Receiver<Result<(), BoxError>>, BoxError>>),
228
229 /// Confirms that the mempool has checked for recently verified transactions.
230 CheckedForVerifiedTransactions,
231
232 /// Summary statistics for the mempool: count, total size, memory usage, and regtest info.
233 QueueStats {
234 /// Number of transactions currently in the mempool
235 size: usize,
236 /// Total size in bytes of all transactions
237 bytes: usize,
238 /// Estimated memory usage in bytes
239 usage: usize,
240 /// Whether all transactions have been fully notified (regtest only)
241 fully_notified: Option<bool>,
242 },
243
244 /// Returns whether a transparent output is created or spent in the mempool, if present.
245 TransparentOutput(Option<CreatedOrSpent>),
246}
247
248/// Indicates whether an output was created or spent by a mempool transaction.
249#[derive(Debug)]
250pub enum CreatedOrSpent {
251 /// An unspent output that was created by a transaction in the mempool and not spent by any other mempool tx.
252 Created {
253 /// The output
254 output: transparent::Output,
255 /// The version
256 tx_version: u32,
257 /// The last seen hash
258 last_seen_hash: block::Hash,
259 },
260 /// Indicates that an output was spent by a mempool transaction.
261 Spent,
262}