zebra_network/protocol/internal/request.rs
1use std::{collections::HashSet, fmt};
2
3use zebra_chain::{
4 block,
5 transaction::{UnminedTx, UnminedTxId},
6};
7
8use super::super::types::Nonce;
9use crate::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).
73 BlocksByHash(HashSet<block::Hash>),
74
75 /// Download one block from a connected peer, waiting for eligible peer capacity.
76 ///
77 /// This outbound-only request is used by sync and gossip downloaders. Unlike
78 /// [`Request::BlocksByHash`], temporary lack of capacity does not cause a local refusal.
79 /// Callers must bound the entire readiness and response operation with a deadline.
80 /// The peer's response timeout starts only when the request is dispatched.
81 ///
82 /// A known advertiser is preferred even if its advertisement was lost from the inventory
83 /// registry. Missing-inventory reports, prior failures, and connection eligibility still apply.
84 /// Without an eligible advertiser, routing prefers peers that serve historic blocks.
85 ///
86 /// The wire request is the same single-item `getdata` as [`Request::BlocksByHash`].
87 /// Inbound `getdata` messages are always decoded as [`Request::BlocksByHash`], never this variant.
88 ///
89 /// # Returns
90 ///
91 /// Returns [`Response::Blocks`](super::Response::Blocks) containing the requested block,
92 /// or an error if the download fails.
93 BlockDownload {
94 /// The hash of the block to download.
95 hash: block::Hash,
96 /// A connected peer known to have advertised this block, if any.
97 advertiser: Option<PeerSocketAddr>,
98 },
99
100 /// Request transactions by their unmined transaction ID.
101 ///
102 /// v4 transactions use a legacy transaction ID, and
103 /// v5 transactions use a witnessed transaction ID.
104 ///
105 /// This uses a `HashSet` for the same reason as [`Request::BlocksByHash`].
106 ///
107 /// If this requests a recently-advertised transaction, the peer set will
108 /// make a best-effort attempt to route the request to a peer that advertised
109 /// the transaction. This routing is only used for request sets of size 1.
110 /// Otherwise, it is routed using the normal load-balancing strategy.
111 ///
112 /// The list contains zero or more unmined transaction IDs.
113 ///
114 /// # Returns
115 ///
116 /// Returns [`Response::Transactions`](super::Response::Transactions).
117 TransactionsById(HashSet<UnminedTxId>),
118
119 /// Request block hashes of subsequent blocks in the chain, given hashes of
120 /// known blocks.
121 ///
122 /// The known blocks list contains zero or more block hashes.
123 ///
124 /// # Returns
125 ///
126 /// Returns
127 /// [`Response::BlockHashes`](super::Response::BlockHashes).
128 ///
129 /// # Warning
130 ///
131 /// This is implemented by sending a `getblocks` message. Bitcoin nodes
132 /// respond to `getblocks` with an `inv` message containing a list of the
133 /// subsequent blocks. However, Bitcoin nodes *also* send `inv` messages
134 /// unsolicited in order to gossip new blocks to their peers. These gossip
135 /// messages can race with the response to a `getblocks` request, and there
136 /// is no way for the network layer to distinguish them. For this reason, the
137 /// response may occasionally contain a single hash of a new chain tip rather
138 /// than a list of hashes of subsequent blocks. We believe that unsolicited
139 /// `inv` messages will always have exactly one block hash.
140 FindBlocks {
141 /// Hashes of known blocks, ordered from highest height to lowest height.
142 //
143 // TODO: make this into an IndexMap - an ordered unique list of hashes (#2244)
144 known_blocks: Vec<block::Hash>,
145 /// Optionally, the last block hash to request.
146 stop: Option<block::Hash>,
147 },
148
149 /// Request headers of subsequent blocks in the chain, given hashes of
150 /// known blocks.
151 ///
152 /// The known blocks list contains zero or more block hashes.
153 ///
154 /// # Returns
155 ///
156 /// Returns
157 /// [`Response::BlockHeaders`](super::Response::BlockHeaders).
158 FindHeaders {
159 /// Hashes of known blocks, ordered from highest height to lowest height.
160 //
161 // TODO: make this into an IndexMap - an ordered unique list of hashes (#2244)
162 known_blocks: Vec<block::Hash>,
163 /// Optionally, the last header to request.
164 stop: Option<block::Hash>,
165 },
166
167 /// Push an unmined transaction to a remote peer, without advertising it to them first.
168 ///
169 /// This is implemented by sending an unsolicited `tx` message.
170 ///
171 /// The second field is the address of the peer that pushed this `tx` to us:
172 /// `Some(addr)` when a remote peer sent us the full transaction directly,
173 /// and `None` when Zebra originates the push itself. Used by the mempool
174 /// downloader to enforce a per-peer queue cap, mirroring
175 /// [`Request::AdvertiseTransactionIds`]. See `GHSA-m9xx-8rcj-vmgp`.
176 ///
177 /// # Returns
178 ///
179 /// Returns [`Response::Nil`](super::Response::Nil).
180 PushTransaction(UnminedTx, Option<PeerSocketAddr>),
181
182 /// Advertise a set of unmined transactions to all peers.
183 ///
184 /// Both Zebra and zcashd sometimes advertise multiple transactions at once.
185 ///
186 /// This is implemented by sending an `inv` message containing the unmined
187 /// transaction IDs, allowing the remote peer to choose whether to download
188 /// them. Remote peers who choose to download the transaction will generate a
189 /// [`Request::TransactionsById`] against the "inbound" service passed to
190 /// [`init`](crate::init).
191 ///
192 /// v4 transactions use a legacy transaction ID, and
193 /// v5 transactions use a witnessed transaction ID.
194 ///
195 /// The list contains zero or more transaction IDs.
196 ///
197 /// The peer set routes this request specially, sending it to *half of*
198 /// the available peers.
199 ///
200 /// The second field is the address of the peer that sent us this `inv`:
201 /// `Some(addr)` when the advertisement was relayed from a remote peer,
202 /// and `None` when Zebra originates the advertisement itself (e.g. the
203 /// mempool gossip task). Used by the mempool downloader to enforce a
204 /// per-peer queue cap. See `GHSA-4fc2-h7jh-287c`.
205 ///
206 /// # Returns
207 ///
208 /// Returns [`Response::Nil`](super::Response::Nil).
209 AdvertiseTransactionIds(HashSet<UnminedTxId>, Option<PeerSocketAddr>),
210
211 /// Advertise a block to all peers.
212 ///
213 /// This is implemented by sending an `inv` message containing the
214 /// block hash, allowing the remote peer to choose whether to download
215 /// it. Remote peers who choose to download the block will generate a
216 /// [`Request::BlocksByHash`] against the "inbound" service passed to
217 /// [`init`](crate::init).
218 ///
219 /// Outbound block adverts use [`crate::BlockAdvertiser`], which samples peers and always
220 /// includes configured sidecars independently of ordinary request readiness.
221 ///
222 /// The second field is the address of the peer that sent us this `inv`:
223 /// `Some(addr)` when the advertisement was relayed from a remote peer,
224 /// and `None` when Zebra originates the advertisement itself (for
225 /// example from the sync gossip task). Consumers use the address to
226 /// apply per-peer policies such as the inbound download per-IP cap.
227 ///
228 /// # Returns
229 ///
230 /// Outbound success acknowledges local writes to every selected peer, not remote receipt.
231 /// Inbound handlers return [`Response::Nil`](super::Response::Nil) after accepting inventory.
232 AdvertiseBlock(block::Hash, Option<PeerSocketAddr>),
233
234 /// Advertise a block to every connected, non-banned peer.
235 ///
236 /// Use [`crate::BlockAdvertiser`], not the ordinary peer service. Each peer has a bounded
237 /// advert channel; full or closed queues, revoked authorization, and write errors are failures.
238 ///
239 /// # Returns
240 ///
241 /// Returns [`Response::Nil`](super::Response::Nil) only after all selected local writes succeed.
242 AdvertiseBlockToAll(block::Hash),
243
244 /// Request the contents of this node's mempool.
245 ///
246 /// # Returns
247 ///
248 /// Returns [`Response::TransactionIds`](super::Response::TransactionIds).
249 MempoolTransactionIds,
250
251 /// Drive local peer-set maintenance without sending a request to a remote peer.
252 ///
253 /// The network-owned idle poller routes queued discovery and inventory requests when peers,
254 /// deadlines, or cancellations change. Advert maintenance is acknowledged independently of
255 /// ordinary readiness.
256 ///
257 /// Returns [`Response::Nil`](super::Response::Nil).
258 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
259 PollPeerSet,
260}
261
262impl fmt::Display for Request {
263 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
264 f.write_str(&match self {
265 Request::Peers => "Peers".to_string(),
266 Request::Ping(_) => "Ping".to_string(),
267
268 Request::BlocksByHash(hashes) => {
269 format!("BlocksByHash({})", hashes.len())
270 }
271 Request::BlockDownload { .. } => "BlockDownload".to_string(),
272 Request::TransactionsById(ids) => format!("TransactionsById({})", ids.len()),
273
274 Request::FindBlocks { known_blocks, stop } => format!(
275 "FindBlocks {{ known_blocks: {}, stop: {} }}",
276 known_blocks.len(),
277 if stop.is_some() { "Some" } else { "None" },
278 ),
279 Request::FindHeaders { known_blocks, stop } => format!(
280 "FindHeaders {{ known_blocks: {}, stop: {} }}",
281 known_blocks.len(),
282 if stop.is_some() { "Some" } else { "None" },
283 ),
284
285 Request::PushTransaction(..) => "PushTransaction".to_string(),
286 Request::AdvertiseTransactionIds(ids, _) => {
287 format!("AdvertiseTransactionIds({})", ids.len())
288 }
289
290 Request::AdvertiseBlock(_, _) => "AdvertiseBlock".to_string(),
291 Request::AdvertiseBlockToAll(_) => "AdvertiseBlockToAll".to_string(),
292 Request::MempoolTransactionIds => "MempoolTransactionIds".to_string(),
293 Request::PollPeerSet => "PollPeerSet".to_string(),
294 })
295 }
296}
297
298impl Request {
299 /// Returns the Zebra internal request type as a string.
300 pub fn command(&self) -> &'static str {
301 match self {
302 Request::Peers => "Peers",
303 Request::Ping(_) => "Ping",
304
305 Request::BlocksByHash(_) => "BlocksByHash",
306 Request::BlockDownload { .. } => "BlockDownload",
307 Request::TransactionsById(_) => "TransactionsById",
308
309 Request::FindBlocks { .. } => "FindBlocks",
310 Request::FindHeaders { .. } => "FindHeaders",
311
312 Request::PushTransaction(..) => "PushTransaction",
313 Request::AdvertiseTransactionIds(_, _) => "AdvertiseTransactionIds",
314
315 Request::AdvertiseBlock(_, _) | Request::AdvertiseBlockToAll(_) => "AdvertiseBlock",
316 Request::MempoolTransactionIds => "MempoolTransactionIds",
317 Request::PollPeerSet => "PollPeerSet",
318 }
319 }
320
321 /// Returns true if the request is for block or transaction inventory downloads.
322 pub fn is_inventory_download(&self) -> bool {
323 matches!(
324 self,
325 Request::BlockDownload { .. } | Request::BlocksByHash(_) | Request::TransactionsById(_)
326 )
327 }
328
329 /// Returns the block hash inventory downloads from the request, if any.
330 pub fn block_hash_inventory(&self) -> HashSet<block::Hash> {
331 match self {
332 Request::BlockDownload { hash, .. } => HashSet::from([*hash]),
333 Request::BlocksByHash(block_hashes) => block_hashes.clone(),
334 _ => HashSet::new(),
335 }
336 }
337
338 /// Returns the transaction ID inventory downloads from the request, if any.
339 pub fn transaction_id_inventory(&self) -> HashSet<UnminedTxId> {
340 if let Request::TransactionsById(transaction_ids) = self {
341 transaction_ids.clone()
342 } else {
343 HashSet::new()
344 }
345 }
346}