Skip to main content

zebra_network/protocol/internal/
response.rs

1//! Zebra's internal peer message response format.
2
3use std::{fmt, sync::Arc, time::Duration};
4
5use zebra_chain::{
6    block::{self, Block},
7    transaction::{UnminedTx, UnminedTxId},
8};
9
10use crate::{meta_addr::MetaAddr, protocol::internal::InventoryResponse, PeerSocketAddr};
11
12#[cfg(any(test, feature = "proptest-impl"))]
13use proptest_derive::Arbitrary;
14
15use InventoryResponse::*;
16
17/// A response to a network request, represented in internal format.
18#[derive(Clone, Debug, Eq, PartialEq)]
19#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
20pub enum Response {
21    /// The request does not have a response.
22    ///
23    /// Either:
24    ///  * the request does not need a response, or
25    ///  * we have no useful data to provide in response to the request,
26    ///    and the request was not an inventory request.
27    ///
28    /// (Inventory requests provide a list of missing hashes if none of the hashes were available.)
29    Nil,
30
31    /// A list of peers, used to respond to `GetPeers`.
32    ///
33    /// The list contains `0..=MAX_META_ADDR` peers.
34    //
35    // TODO: make this into a HashMap<PeerSocketAddr, MetaAddr> - a unique list of peer addresses (#2244)
36    Peers(Vec<MetaAddr>),
37
38    /// A pong response containing the round-trip latency for a peer.
39    ///
40    /// Returned after a ping/pong exchange to measure RTT.
41    Pong(Duration),
42
43    /// An ordered list of block hashes.
44    ///
45    /// The list contains zero or more block hashes.
46    //
47    // TODO: make this into an IndexMap - an ordered unique list of hashes (#2244)
48    BlockHashes(Vec<block::Hash>),
49
50    /// An ordered list of block headers.
51    ///
52    /// The list contains zero or more block headers.
53    //
54    // TODO: make this into an IndexMap - an ordered unique list of headers (#2244)
55    BlockHeaders(Vec<block::CountedHeader>),
56
57    /// A list of unmined transaction IDs.
58    ///
59    /// v4 transactions use a legacy transaction ID, and
60    /// v5 transactions use a witnessed transaction ID.
61    ///
62    /// The list contains zero or more transaction IDs.
63    //
64    // TODO: make this into a HashSet - a unique list (#2244)
65    TransactionIds(Vec<UnminedTxId>),
66
67    /// A list of found blocks, and missing block hashes.
68    ///
69    /// Each list contains zero or more entries.
70    ///
71    /// When Zebra doesn't have a block or transaction, it always sends `notfound`.
72    /// `zcashd` sometimes sends no response, and sometimes sends `notfound`.
73    //
74    // TODO: make this into a HashMap<block::Hash, InventoryResponse<Arc<Block>, ()>> - a unique list (#2244)
75    Blocks(Vec<InventoryResponse<(Arc<Block>, Option<PeerSocketAddr>), block::Hash>>),
76
77    /// Blocks downloaded from a connection where both peers set the compact block relay service
78    /// bit, and missing block hashes, as in [`Self::Blocks`].
79    ///
80    /// The [draft Compact Block Relay ZIP] lets these peers send a block before they have
81    /// validated it, so this isn't evidence that a block is valid. Every block download from these
82    /// connections returns this variant, whether the block was rebuilt from a compact block or
83    /// downloaded in full. The inbound service never returns it.
84    ///
85    /// [draft Compact Block Relay ZIP]: https://github.com/zcash/zips/pull/1429
86    EarlyBlocks(Vec<InventoryResponse<(Arc<Block>, Option<PeerSocketAddr>), block::Hash>>),
87
88    /// Verified mempool candidates matching unique compact short IDs by exact witnessed identity.
89    ///
90    /// Local-only response to [`super::Request::CompactBlockTransactions`], never sent on the wire.
91    CompactBlockTransactions(Vec<UnminedTx>),
92
93    /// A list of found unmined transactions, and missing unmined transaction IDs.
94    ///
95    /// Each list contains zero or more entries.
96    //
97    // TODO: make this into a HashMap<UnminedTxId, InventoryResponse<UnminedTx, ()>> - a unique list (#2244)
98    Transactions(Vec<InventoryResponse<(UnminedTx, Option<PeerSocketAddr>), UnminedTxId>>),
99}
100
101impl fmt::Display for Response {
102    #[allow(clippy::unwrap_in_result)]
103    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104        f.write_str(&match self {
105            Response::Nil => "Nil".to_string(),
106
107            Response::Peers(peers) => format!("Peers {{ peers: {} }}", peers.len()),
108
109            Response::Pong(duration) => format!("Pong {{ latency: {duration:?} }}"),
110
111            Response::BlockHashes(hashes) => format!("BlockHashes {{ hashes: {} }}", hashes.len()),
112            Response::BlockHeaders(headers) => {
113                format!("BlockHeaders {{ headers: {} }}", headers.len())
114            }
115            Response::TransactionIds(ids) => format!("TransactionIds {{ ids: {} }}", ids.len()),
116            Response::CompactBlockTransactions(transactions) => {
117                format!("CompactBlockTransactions({})", transactions.len())
118            }
119
120            // Display heights for single-block responses (which Zebra requests and expects)
121            Response::Blocks(blocks) | Response::EarlyBlocks(blocks) if blocks.len() == 1 => {
122                match blocks.first().expect("len is 1") {
123                    Available((block, _)) => format!(
124                        "Block {{ height: {}, hash: {} }}",
125                        block
126                            .coinbase_height()
127                            .as_ref()
128                            .map(|h| h.0.to_string())
129                            .unwrap_or_else(|| "None".into()),
130                        block.hash(),
131                    ),
132                    Missing(hash) => format!("Block {{ missing: {hash} }}"),
133                }
134            }
135            Response::Blocks(blocks) | Response::EarlyBlocks(blocks) => format!(
136                "Blocks {{ blocks: {}, missing: {} }}",
137                blocks.iter().filter(|r| r.is_available()).count(),
138                blocks.iter().filter(|r| r.is_missing()).count()
139            ),
140
141            Response::Transactions(transactions) => format!(
142                "Transactions {{ transactions: {}, missing: {} }}",
143                transactions.iter().filter(|r| r.is_available()).count(),
144                transactions.iter().filter(|r| r.is_missing()).count()
145            ),
146        })
147    }
148}
149
150impl Response {
151    /// Returns the Zebra internal response type as a string.
152    pub fn command(&self) -> &'static str {
153        match self {
154            Response::Nil => "Nil",
155
156            Response::Peers(_) => "Peers",
157
158            Response::Pong(_) => "Pong",
159
160            Response::BlockHashes(_) => "BlockHashes",
161            Response::BlockHeaders(_) => "BlockHeaders",
162            Response::TransactionIds(_) => "TransactionIds",
163
164            Response::Blocks(_) => "Blocks",
165            Response::EarlyBlocks(_) => "EarlyBlocks",
166            Response::CompactBlockTransactions(_) => "CompactBlockTransactions",
167            Response::Transactions(_) => "Transactions",
168        }
169    }
170
171    /// Returns true if the response is a block or transaction inventory download.
172    pub fn is_inventory_download(&self) -> bool {
173        matches!(
174            self,
175            Response::Blocks(_) | Response::EarlyBlocks(_) | Response::Transactions(_)
176        )
177    }
178
179    /// Returns true if self is the [`Response::Nil`] variant.
180    #[allow(dead_code)]
181    pub fn is_nil(&self) -> bool {
182        matches!(self, Self::Nil)
183    }
184}