zebra_network/protocol/internal/request.rs
1use std::{collections::HashSet, fmt, sync::Arc};
2
3use zebra_chain::{
4 block,
5 transaction::{UnminedTx, UnminedTxId},
6};
7
8use super::super::types::Nonce;
9use crate::{compact::CompactBlock, PeerSocketAddr};
10
11#[cfg(any(test, feature = "proptest-impl"))]
12use proptest_derive::Arbitrary;
13
14/// A network request, represented in internal format.
15///
16/// The network layer aims to abstract away the details of the Bitcoin wire
17/// protocol into a clear request/response API. Each [`Request`] documents the
18/// possible [`Response`s](super::Response) it can generate; it is fine (and
19/// recommended!) to match on the expected responses and treat the others as
20/// `unreachable!()`, since their return indicates a bug in the network code.
21///
22/// # Cancellations
23///
24/// The peer set handles cancelled requests (i.e., requests where the future
25/// returned by `Service::call` is dropped before it resolves) on a best-effort
26/// basis. Requests are routed to a particular peer connection, and then
27/// translated into Zcash protocol messages and sent over the network. If a
28/// request is cancelled after it is submitted but before it is processed by a
29/// peer connection, no messages will be sent. Otherwise, if it is cancelled
30/// while waiting for a response, the peer connection resets its state and makes
31/// a best-effort attempt to ignore any messages responsive to the cancelled
32/// request, subject to limitations in the underlying Zcash protocol.
33#[derive(Clone, Debug, Eq, PartialEq)]
34#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
35pub enum Request {
36 /// Requests additional peers from the server.
37 ///
38 /// # Response
39 ///
40 /// Returns [`Response::Peers`](super::Response::Peers).
41 Peers,
42
43 /// Heartbeats triggered on peer connection start.
44 ///
45 /// This is included as a bit of a hack, it should only be used
46 /// internally for connection management. You should not expect to
47 /// be firing or handling `Ping` requests or `Pong` responses.
48 #[doc(hidden)]
49 Ping(Nonce),
50
51 /// Request block data by block hashes.
52 ///
53 /// This uses a `HashSet` rather than a `Vec` for two reasons. First, it
54 /// automatically deduplicates the requested blocks. Second, the internal
55 /// protocol translator needs to maintain a `HashSet` anyways, in order to
56 /// keep track of which requested blocks have been received and when the
57 /// request is ready. Rather than force the internals to always convert into
58 /// a `HashSet`, we require the caller to pass one, so that if the caller
59 /// didn't start with a `Vec` but with, e.g., an iterator, they can collect
60 /// directly into a `HashSet` and save work.
61 ///
62 /// Single-block requests prefer a connected peer that advertised the block. For blocks
63 /// nobody advertised, they prefer peers that serve historic blocks. If no ready peer can
64 /// serve the block but a busy peer might have it, the request waits for up to
65 /// [`INVENTORY_BUSY_PEER_WAIT_TIMEOUT`](crate::constants::INVENTORY_BUSY_PEER_WAIT_TIMEOUT).
66 /// Larger request sets use normal load balancing.
67 ///
68 /// The list contains zero or more block hashes.
69 ///
70 /// # Returns
71 ///
72 /// Returns [`Response::Blocks`](super::Response::Blocks), or
73 /// [`Response::EarlyBlocks`](super::Response::EarlyBlocks) from a connection that negotiated
74 /// compact block relay.
75 BlocksByHash(HashSet<block::Hash>),
76
77 /// Admits a screened compact advertisement to the ordinary bounded gossip downloader.
78 ///
79 /// Only the inbound connection creates this request, on connections that negotiated compact
80 /// relay. Returns [`super::Response::Nil`] only when a new download was queued. Duplicate
81 /// hashes, exhausted global capacity, and the per-IP cap return errors; no compact body may be
82 /// retained.
83 AdvertiseCompactBlock(block::Hash, Option<PeerSocketAddr>),
84
85 /// Screens a compact header before retaining its body, without querying the mempool.
86 ///
87 /// Returns [`super::Response::Nil`] only for a valid next-tip candidate. Errors require
88 /// ordinary full-block fallback, not peer punishment.
89 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
90 CheckCompactHeader(Arc<CompactBlock>),
91
92 /// Finds verified mempool candidates for a negotiated compact block.
93 ///
94 /// The inbound service screens the compact shape, proof of work, and current committed-tip
95 /// header context before consulting the mempool.
96 /// Returns [`super::Response::CompactBlockTransactions`].
97 /// Errors mean full-block fallback, not peer punishment or block rejection.
98 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
99 CompactBlockTransactions(Arc<CompactBlock>),
100
101 /// Authenticates a reconstructed body against the current committed tip without caching it.
102 ///
103 /// Returns [`super::Response::Nil`] on success. Errors require full-block fallback and must
104 /// not enter the block rejection cache. Success does not replace normal block verification.
105 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
106 CheckCompactBlock(Arc<block::Block>),
107
108 /// Download one block from a connected peer, waiting for eligible peer capacity.
109 ///
110 /// This outbound-only request is used by sync and gossip downloaders. Unlike
111 /// [`Request::BlocksByHash`], temporary lack of capacity does not cause a local refusal.
112 /// Callers must bound the entire readiness and response operation with a deadline.
113 /// The peer's response timeout starts only when the request is dispatched.
114 ///
115 /// A known advertiser is preferred even if its advertisement was lost from the inventory
116 /// registry. Missing-inventory reports, prior failures, and connection eligibility still apply.
117 /// Without an eligible advertiser, routing prefers peers that serve historic blocks.
118 ///
119 /// The wire request is the same single-item `getdata` as [`Request::BlocksByHash`].
120 /// Inbound `getdata` messages are always decoded as [`Request::BlocksByHash`], never this variant.
121 ///
122 /// # Returns
123 ///
124 /// Returns [`Response::Blocks`](super::Response::Blocks) containing the requested block,
125 /// or [`Response::EarlyBlocks`](super::Response::EarlyBlocks) from a connection that
126 /// negotiated compact block relay, or an error if the download fails.
127 BlockDownload {
128 /// The hash of the block to download.
129 hash: block::Hash,
130 /// A connected peer known to have advertised this block, if any.
131 advertiser: Option<PeerSocketAddr>,
132 },
133
134 /// Request transactions by their unmined transaction ID.
135 ///
136 /// v4 transactions use a legacy transaction ID, and
137 /// v5 transactions use a witnessed transaction ID.
138 ///
139 /// This uses a `HashSet` for the same reason as [`Request::BlocksByHash`].
140 ///
141 /// If this requests a recently-advertised transaction, the peer set will
142 /// make a best-effort attempt to route the request to a peer that advertised
143 /// the transaction. This routing is only used for request sets of size 1.
144 /// Otherwise, it is routed using the normal load-balancing strategy.
145 ///
146 /// The list contains zero or more unmined transaction IDs.
147 ///
148 /// # Returns
149 ///
150 /// Returns [`Response::Transactions`](super::Response::Transactions).
151 TransactionsById(HashSet<UnminedTxId>),
152
153 /// Request block hashes of subsequent blocks in the chain, given hashes of
154 /// known blocks.
155 ///
156 /// The known blocks list contains zero or more block hashes.
157 ///
158 /// # Returns
159 ///
160 /// Returns
161 /// [`Response::BlockHashes`](super::Response::BlockHashes).
162 ///
163 /// # Warning
164 ///
165 /// This is implemented by sending a `getblocks` message. Bitcoin nodes
166 /// respond to `getblocks` with an `inv` message containing a list of the
167 /// subsequent blocks. However, Bitcoin nodes *also* send `inv` messages
168 /// unsolicited in order to gossip new blocks to their peers. These gossip
169 /// messages can race with the response to a `getblocks` request, and there
170 /// is no way for the network layer to distinguish them. For this reason, the
171 /// response may occasionally contain a single hash of a new chain tip rather
172 /// than a list of hashes of subsequent blocks. We believe that unsolicited
173 /// `inv` messages will always have exactly one block hash.
174 FindBlocks {
175 /// Hashes of known blocks, ordered from highest height to lowest height.
176 //
177 // TODO: make this into an IndexMap - an ordered unique list of hashes (#2244)
178 known_blocks: Vec<block::Hash>,
179 /// Optionally, the last block hash to request.
180 stop: Option<block::Hash>,
181 },
182
183 /// Request headers of subsequent blocks in the chain, given hashes of
184 /// known blocks.
185 ///
186 /// The known blocks list contains zero or more block hashes.
187 ///
188 /// # Returns
189 ///
190 /// Returns
191 /// [`Response::BlockHeaders`](super::Response::BlockHeaders).
192 FindHeaders {
193 /// Hashes of known blocks, ordered from highest height to lowest height.
194 //
195 // TODO: make this into an IndexMap - an ordered unique list of hashes (#2244)
196 known_blocks: Vec<block::Hash>,
197 /// Optionally, the last header to request.
198 stop: Option<block::Hash>,
199 },
200
201 /// Push an unmined transaction to a remote peer, without advertising it to them first.
202 ///
203 /// This is implemented by sending an unsolicited `tx` message.
204 ///
205 /// The second field is the address of the peer that pushed this `tx` to us:
206 /// `Some(addr)` when a remote peer sent us the full transaction directly,
207 /// and `None` when Zebra originates the push itself. Used by the mempool
208 /// downloader to enforce a per-peer queue cap, mirroring
209 /// [`Request::AdvertiseTransactionIds`]. See `GHSA-m9xx-8rcj-vmgp`.
210 ///
211 /// # Returns
212 ///
213 /// Returns [`Response::Nil`](super::Response::Nil).
214 PushTransaction(UnminedTx, Option<PeerSocketAddr>),
215
216 /// Advertise a set of unmined transactions to all peers.
217 ///
218 /// Both Zebra and zcashd sometimes advertise multiple transactions at once.
219 ///
220 /// This is implemented by sending an `inv` message containing the unmined
221 /// transaction IDs, allowing the remote peer to choose whether to download
222 /// them. Remote peers who choose to download the transaction will generate a
223 /// [`Request::TransactionsById`] against the "inbound" service passed to
224 /// [`init`](crate::init).
225 ///
226 /// v4 transactions use a legacy transaction ID, and
227 /// v5 transactions use a witnessed transaction ID.
228 ///
229 /// The list contains zero or more transaction IDs.
230 ///
231 /// The peer set routes this request specially, sending it to *half of*
232 /// the available peers.
233 ///
234 /// The second field is the address of the peer that sent us this `inv`:
235 /// `Some(addr)` when the advertisement was relayed from a remote peer,
236 /// and `None` when Zebra originates the advertisement itself (e.g. the
237 /// mempool gossip task). Used by the mempool downloader to enforce a
238 /// per-peer queue cap. See `GHSA-4fc2-h7jh-287c`.
239 ///
240 /// # Returns
241 ///
242 /// Returns [`Response::Nil`](super::Response::Nil).
243 AdvertiseTransactionIds(HashSet<UnminedTxId>, Option<PeerSocketAddr>),
244
245 /// Advertise a block to all peers.
246 ///
247 /// This is implemented by sending an `inv` message containing the
248 /// block hash, allowing the remote peer to choose whether to download
249 /// it. Remote peers who choose to download the block will generate a
250 /// [`Request::BlocksByHash`] against the "inbound" service passed to
251 /// [`init`](crate::init).
252 ///
253 /// Outbound block adverts use [`crate::BlockAdvertiser`], which samples peers and always
254 /// includes configured sidecars independently of ordinary request readiness.
255 ///
256 /// The second field is the address of the peer that sent us this `inv`:
257 /// `Some(addr)` when the advertisement was relayed from a remote peer,
258 /// and `None` when Zebra originates the advertisement itself (for
259 /// example from the sync gossip task). Consumers use the address to
260 /// apply per-peer policies such as the inbound download per-IP cap.
261 ///
262 /// # Returns
263 ///
264 /// Outbound success acknowledges local writes to every selected peer, not remote receipt.
265 /// Inbound handlers return [`Response::Nil`](super::Response::Nil) after accepting inventory.
266 AdvertiseBlock(block::Hash, Option<PeerSocketAddr>),
267
268 /// Advertise a block to every connected, non-banned peer.
269 ///
270 /// Use [`crate::BlockAdvertiser`], not the ordinary peer service. Each peer has a bounded
271 /// advert channel; full or closed queues, revoked authorization, and write errors are failures.
272 ///
273 /// # Returns
274 ///
275 /// Returns [`Response::Nil`](super::Response::Nil) only after all selected local writes succeed.
276 AdvertiseBlockToAll(block::Hash),
277
278 /// Request the contents of this node's mempool.
279 ///
280 /// # Returns
281 ///
282 /// Returns [`Response::TransactionIds`](super::Response::TransactionIds).
283 MempoolTransactionIds,
284
285 /// Drive local peer-set maintenance without sending a request to a remote peer.
286 ///
287 /// The network-owned idle poller routes queued discovery and inventory requests when peers,
288 /// deadlines, or cancellations change. Advert maintenance is acknowledged independently of
289 /// ordinary readiness.
290 ///
291 /// Returns [`Response::Nil`](super::Response::Nil).
292 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
293 PollPeerSet,
294}
295
296impl fmt::Display for Request {
297 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
298 f.write_str(&match self {
299 Request::Peers => "Peers".to_string(),
300 Request::Ping(_) => "Ping".to_string(),
301
302 Request::BlocksByHash(hashes) => {
303 format!("BlocksByHash({})", hashes.len())
304 }
305 Request::BlockDownload { .. } => "BlockDownload".to_string(),
306 Request::AdvertiseCompactBlock(..) => "AdvertiseCompactBlock".to_string(),
307 Request::CheckCompactHeader(_) => "CheckCompactHeader".to_string(),
308 Request::CompactBlockTransactions(_) => "CompactBlockTransactions".to_string(),
309 Request::CheckCompactBlock(_) => "CheckCompactBlock".to_string(),
310 Request::TransactionsById(ids) => format!("TransactionsById({})", ids.len()),
311
312 Request::FindBlocks { known_blocks, stop } => format!(
313 "FindBlocks {{ known_blocks: {}, stop: {} }}",
314 known_blocks.len(),
315 if stop.is_some() { "Some" } else { "None" },
316 ),
317 Request::FindHeaders { known_blocks, stop } => format!(
318 "FindHeaders {{ known_blocks: {}, stop: {} }}",
319 known_blocks.len(),
320 if stop.is_some() { "Some" } else { "None" },
321 ),
322
323 Request::PushTransaction(..) => "PushTransaction".to_string(),
324 Request::AdvertiseTransactionIds(ids, _) => {
325 format!("AdvertiseTransactionIds({})", ids.len())
326 }
327
328 Request::AdvertiseBlock(_, _) => "AdvertiseBlock".to_string(),
329 Request::AdvertiseBlockToAll(_) => "AdvertiseBlockToAll".to_string(),
330 Request::MempoolTransactionIds => "MempoolTransactionIds".to_string(),
331 Request::PollPeerSet => "PollPeerSet".to_string(),
332 })
333 }
334}
335
336impl Request {
337 /// Returns the Zebra internal request type as a string.
338 pub fn command(&self) -> &'static str {
339 match self {
340 Request::Peers => "Peers",
341 Request::Ping(_) => "Ping",
342
343 Request::BlocksByHash(_) => "BlocksByHash",
344 Request::BlockDownload { .. } => "BlockDownload",
345 Request::AdvertiseCompactBlock(..) => "AdvertiseCompactBlock",
346 Request::CheckCompactHeader(_) => "CheckCompactHeader",
347 Request::CompactBlockTransactions(_) => "CompactBlockTransactions",
348 Request::CheckCompactBlock(_) => "CheckCompactBlock",
349 Request::TransactionsById(_) => "TransactionsById",
350
351 Request::FindBlocks { .. } => "FindBlocks",
352 Request::FindHeaders { .. } => "FindHeaders",
353
354 Request::PushTransaction(..) => "PushTransaction",
355 Request::AdvertiseTransactionIds(_, _) => "AdvertiseTransactionIds",
356
357 Request::AdvertiseBlock(_, _) | Request::AdvertiseBlockToAll(_) => "AdvertiseBlock",
358 Request::MempoolTransactionIds => "MempoolTransactionIds",
359 Request::PollPeerSet => "PollPeerSet",
360 }
361 }
362
363 /// Returns true if the request is for block or transaction inventory downloads.
364 pub fn is_inventory_download(&self) -> bool {
365 matches!(
366 self,
367 Request::BlockDownload { .. } | Request::BlocksByHash(_) | Request::TransactionsById(_)
368 )
369 }
370
371 /// Returns the block hash inventory downloads from the request, if any.
372 pub fn block_hash_inventory(&self) -> HashSet<block::Hash> {
373 match self {
374 Request::BlockDownload { hash, .. } => HashSet::from([*hash]),
375 Request::BlocksByHash(block_hashes) => block_hashes.clone(),
376 _ => HashSet::new(),
377 }
378 }
379
380 /// Returns the transaction ID inventory downloads from the request, if any.
381 pub fn transaction_id_inventory(&self) -> HashSet<UnminedTxId> {
382 if let Request::TransactionsById(transaction_ids) = self {
383 transaction_ids.clone()
384 } else {
385 HashSet::new()
386 }
387 }
388}