zebra_network/protocol/external/message.rs
1//! Definitions of network messages.
2
3use std::{error::Error, fmt, sync::Arc};
4
5use chrono::{DateTime, Utc};
6
7use zebra_chain::{
8 block::{self, Block},
9 transaction::UnminedTx,
10};
11
12use crate::{meta_addr::MetaAddr, BoxError};
13
14use super::{
15 addr::AddrInVersion,
16 compact::{BlockTransactions, BlockTransactionsRequest, CompactBlock},
17 inv::InventoryHash,
18 types::*,
19};
20
21#[cfg(any(test, feature = "proptest-impl"))]
22use proptest_derive::Arbitrary;
23
24#[cfg(any(test, feature = "proptest-impl"))]
25use zebra_chain::serialization::arbitrary::datetime_full;
26
27/// A Bitcoin-like network message for the Zcash protocol.
28///
29/// The Zcash network protocol is mostly inherited from Bitcoin, and a list of
30/// Bitcoin network messages can be found [on the Bitcoin
31/// wiki][btc_wiki_protocol].
32///
33/// That page describes the wire format of the messages, while this enum stores
34/// an internal representation. The internal representation is unlinked from the
35/// wire format, and the translation between the two happens only during
36/// serialization and deserialization. For instance, Bitcoin identifies messages
37/// by a 12-byte ascii command string; we consider this a serialization detail
38/// and use the enum discriminant instead. (As a side benefit, this also means
39/// that we have a clearly-defined validation boundary for network messages
40/// during serialization).
41///
42/// [btc_wiki_protocol]: https://en.bitcoin.it/wiki/Protocol_documentation
43#[derive(Clone, Eq, PartialEq, Debug)]
44#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
45pub enum Message {
46 /// A `version` message.
47 ///
48 /// Note that although this is called `version` in Bitcoin, its role is really
49 /// analogous to a `ClientHello` message in TLS, used to begin a handshake, and
50 /// is distinct from a simple version number.
51 ///
52 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#version)
53 Version(VersionMessage),
54
55 /// A `verack` message.
56 ///
57 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#verack)
58 Verack,
59
60 /// A `ping` message.
61 ///
62 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#ping)
63 Ping(
64 /// A nonce unique to this [`Self::Ping`] message.
65 Nonce,
66 ),
67
68 /// A `pong` message.
69 ///
70 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#pong)
71 Pong(
72 /// The nonce from the [`Self::Ping`] message this was in response to.
73 Nonce,
74 ),
75
76 /// A `reject` message.
77 ///
78 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#reject)
79 Reject {
80 /// Type of message rejected.
81 // It's unclear if this is strictly limited to message command
82 // codes, so leaving it a String.
83 message: String,
84
85 /// RejectReason code relating to rejected message.
86 ccode: RejectReason,
87
88 /// Human-readable version of rejection reason.
89 reason: String,
90
91 /// Optional extra data provided for some errors.
92 // Currently, all errors which provide this field fill it with
93 // the TXID or block header hash of the object being rejected,
94 // so the field is 32 bytes.
95 data: Option<[u8; 32]>,
96 },
97
98 /// A `getaddr` message.
99 ///
100 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#getaddr)
101 GetAddr,
102
103 /// A sent or received `addr` message, or a received `addrv2` message.
104 ///
105 /// Currently, Zebra:
106 /// - sends and receives `addr` messages,
107 /// - parses received `addrv2` messages, ignoring some address types,
108 /// - but does not send `addrv2` messages.
109 ///
110 ///
111 /// The list contains `0..=MAX_META_ADDR` addresses.
112 ///
113 /// Because some address types are ignored, the deserialized vector can be empty,
114 /// even if the peer sent addresses. This is not an error.
115 ///
116 /// [addr Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#addr)
117 /// [addrv2 ZIP 155](https://zips.z.cash/zip-0155#specification)
118 Addr(Vec<MetaAddr>),
119
120 /// A `getblocks` message.
121 ///
122 /// `known_blocks` is a series of known block hashes spaced out along the
123 /// peer's best chain. The remote peer uses them to compute the intersection
124 /// of its best chain and determine the blocks following the intersection
125 /// point.
126 ///
127 /// The peer responds with an `inv` packet with the hashes of subsequent blocks.
128 /// If supplied, the `stop` parameter specifies the last header to request.
129 /// Otherwise, an inv packet with the maximum number (500) are sent.
130 ///
131 /// The known blocks list contains zero or more block hashes.
132 ///
133 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#getheaders)
134 GetBlocks {
135 /// Hashes of known blocks, ordered from highest height to lowest height.
136 known_blocks: Vec<block::Hash>,
137 /// Optionally, the last header to request.
138 stop: Option<block::Hash>,
139 },
140
141 /// An `inv` message.
142 ///
143 /// Allows a node to advertise its knowledge of one or more
144 /// objects. It can be received unsolicited, or in reply to
145 /// `getblocks`.
146 ///
147 /// The list contains zero or more inventory hashes.
148 ///
149 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#inv)
150 /// [ZIP-239](https://zips.z.cash/zip-0239)
151 Inv(Vec<InventoryHash>),
152
153 /// A `getheaders` message.
154 ///
155 /// `known_blocks` is a series of known block hashes spaced out along the
156 /// peer's best chain. The remote peer uses them to compute the intersection
157 /// of its best chain and determine the blocks following the intersection
158 /// point.
159 ///
160 /// The peer responds with an `headers` packet with the headers of subsequent blocks.
161 /// If supplied, the `stop` parameter specifies the last header to request.
162 /// Otherwise, the maximum number of block headers (160) are sent.
163 ///
164 /// The known blocks list contains zero or more block hashes.
165 ///
166 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#getheaders)
167 GetHeaders {
168 /// Hashes of known blocks, ordered from highest height to lowest height.
169 known_blocks: Vec<block::Hash>,
170 /// Optionally, the last header to request.
171 stop: Option<block::Hash>,
172 },
173
174 /// A `headers` message.
175 ///
176 /// Returns block headers in response to a getheaders packet.
177 ///
178 /// Each block header is accompanied by a transaction count.
179 ///
180 /// The list contains zero or more headers.
181 ///
182 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#headers)
183 Headers(Vec<block::CountedHeader>),
184
185 /// A `getdata` message.
186 ///
187 /// `getdata` is used in response to `inv`, to retrieve the
188 /// content of a specific object, and is usually sent after
189 /// receiving an `inv` packet, after filtering known elements.
190 ///
191 /// `zcashd` returns requested items in a single batch of messages.
192 /// Missing blocks are silently skipped. Missing transaction hashes are
193 /// included in a single `notfound` message following the transactions.
194 /// Other item or non-item messages can come before or after the batch.
195 ///
196 /// The list contains zero or more inventory hashes.
197 ///
198 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#getdata)
199 /// [ZIP-239](https://zips.z.cash/zip-0239)
200 /// [zcashd code](https://github.com/zcash/zcash/blob/e7b425298f6d9a54810cb7183f00be547e4d9415/src/main.cpp#L5523)
201 GetData(Vec<InventoryHash>),
202
203 /// A `block` message.
204 ///
205 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#block)
206 Block(Arc<Block>),
207
208 /// Compact relay opt-in; requires both peers to set the compact block relay service bit.
209 SendCompact {
210 /// Whether to push high-bandwidth announcements.
211 high_bandwidth: bool,
212 /// Encoding version; currently only provisional version 1 is supported.
213 version: u64,
214 },
215
216 /// An ordered compact block announcement, including its complete coinbase.
217 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
218 CompactBlock(Arc<CompactBlock>),
219
220 /// One recovery request for missing transactions from an advertised block.
221 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
222 GetBlockTransactions(BlockTransactionsRequest),
223
224 /// Complete transactions in the order requested by compact recovery.
225 #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
226 BlockTransactions(BlockTransactions),
227
228 /// A `tx` message.
229 ///
230 /// This message can be used to:
231 /// - send unmined transactions in response to `GetData` requests, and
232 /// - advertise unmined transactions for the mempool.
233 ///
234 /// Zebra chooses to advertise new transactions using `Inv(hash)` rather than `Tx(transaction)`.
235 ///
236 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#tx)
237 Tx(UnminedTx),
238
239 /// A `notfound` message.
240 ///
241 /// Zebra responds with this message when it doesn't have the requested blocks or transactions.
242 ///
243 /// When a peer requests a list of transaction hashes, `zcashd` returns:
244 /// - a batch of messages containing found transactions, then
245 /// - a `notfound` message containing a list of transaction hashes that
246 /// aren't available in its mempool or state.
247 ///
248 /// But when a peer requests blocks or headers, any missing items are
249 /// silently skipped, without any `notfound` messages.
250 ///
251 /// The list contains zero or more inventory hashes.
252 ///
253 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#notfound)
254 /// [ZIP-239](https://zips.z.cash/zip-0239)
255 /// [zcashd code](https://github.com/zcash/zcash/blob/e7b425298f6d9a54810cb7183f00be547e4d9415/src/main.cpp#L5632)
256 // See note above on `Inventory`.
257 NotFound(Vec<InventoryHash>),
258
259 /// A `mempool` message.
260 ///
261 /// This was defined in [BIP35], which is included in Zcash.
262 ///
263 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#mempool)
264 ///
265 /// [BIP35]: https://github.com/bitcoin/bips/blob/master/bip-0035.mediawiki
266 Mempool,
267
268 /// A `filterload` message.
269 ///
270 /// This was defined in [BIP37], which is included in Zcash.
271 ///
272 /// Zebra currently ignores this message.
273 ///
274 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#filterload.2C_filteradd.2C_filterclear.2C_merkleblock)
275 ///
276 /// [BIP37]: https://github.com/bitcoin/bips/blob/master/bip-0037.mediawiki
277 FilterLoad {
278 /// The filter itself is simply a bit field of arbitrary
279 /// byte-aligned size. The maximum size is 36,000 bytes.
280 filter: Filter,
281
282 /// The number of hash functions to use in this filter. The
283 /// maximum value allowed in this field is 50.
284 hash_functions_count: u32,
285
286 /// A random value to add to the seed value in the hash
287 /// function used by the bloom filter.
288 tweak: Tweak,
289
290 /// A set of flags that control how matched items are added to the filter.
291 flags: u8,
292 },
293
294 /// A `filteradd` message.
295 ///
296 /// This was defined in [BIP37], which is included in Zcash.
297 ///
298 /// Zebra currently ignores this message.
299 ///
300 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#filterload.2C_filteradd.2C_filterclear.2C_merkleblock)
301 ///
302 /// [BIP37]: https://github.com/bitcoin/bips/blob/master/bip-0037.mediawiki
303 FilterAdd {
304 /// The data element to add to the current filter.
305 // The data field must be smaller than or equal to 520 bytes
306 // in size (the maximum size of any potentially matched
307 // object).
308 //
309 // A Vec instead of [u8; 520] because of needed traits.
310 data: Vec<u8>,
311 },
312
313 /// A `filterclear` message.
314 ///
315 /// This was defined in [BIP37], which is included in Zcash.
316 ///
317 /// Zebra currently ignores this message.
318 ///
319 /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#filterload.2C_filteradd.2C_filterclear.2C_merkleblock)
320 ///
321 /// [BIP37]: https://github.com/bitcoin/bips/blob/master/bip-0037.mediawiki
322 FilterClear,
323}
324
325/// The maximum size of the user agent string.
326///
327/// This is equivalent to `MAX_SUBVERSION_LENGTH` in `zcashd`:
328/// <https://github.com/zcash/zcash/blob/adfc7218435faa1c8985a727f997a795dcffa0c7/src/net.h#L56>
329pub const MAX_USER_AGENT_LENGTH: usize = 256;
330
331/// A `version` message.
332///
333/// Note that although this is called `version` in Bitcoin, its role is really
334/// analogous to a `ClientHello` message in TLS, used to begin a handshake, and
335/// is distinct from a simple version number.
336///
337/// This struct provides a type that is guaranteed to be a `version` message,
338/// and allows [`Message::Version`](Message) fields to be accessed directly.
339///
340/// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#version)
341#[derive(Clone, Eq, PartialEq, Debug)]
342#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
343pub struct VersionMessage {
344 /// The network version number supported by the sender.
345 pub version: Version,
346
347 /// The network services advertised by the sender.
348 pub services: PeerServices,
349
350 /// The time when the version message was sent.
351 ///
352 /// This is a 64-bit field. Zebra rejects out-of-range times as invalid.
353 ///
354 /// TODO: replace with a custom DateTime64 type (#2171)
355 #[cfg_attr(
356 any(test, feature = "proptest-impl"),
357 proptest(strategy = "datetime_full()")
358 )]
359 pub timestamp: DateTime<Utc>,
360
361 /// The network address of the node receiving this message, and its
362 /// advertised network services.
363 ///
364 /// Q: how does the handshake know the remote peer's services already?
365 pub address_recv: AddrInVersion,
366
367 /// The network address of the node sending this message, and its
368 /// advertised network services.
369 pub address_from: AddrInVersion,
370
371 /// Node random nonce, randomly generated every time a version
372 /// packet is sent. This nonce is used to detect connections
373 /// to self.
374 pub nonce: Nonce,
375
376 /// The Zcash user agent advertised by the sender.
377 pub user_agent: String,
378
379 /// The last block received by the emitting node.
380 pub start_height: block::Height,
381
382 /// Whether the remote peer should announce relayed
383 /// transactions or not, see [BIP 0037].
384 ///
385 /// Zebra does not implement the bloom filters in [BIP 0037].
386 /// Instead, it only relays:
387 /// - newly verified best chain block hashes and mempool transaction IDs,
388 /// - after it reaches the chain tip.
389 ///
390 /// [BIP 0037]: https://github.com/bitcoin/bips/blob/master/bip-0037.mediawiki
391 pub relay: bool,
392}
393
394/// The maximum size of the rejection message.
395///
396/// This is equivalent to `COMMAND_SIZE` in zcashd:
397/// <https://github.com/zcash/zcash/blob/adfc7218435faa1c8985a727f997a795dcffa0c7/src/protocol.h#L33>
398/// <https://github.com/zcash/zcash/blob/c0fbeb809bf2303e30acef0d2b74db11e9177427/src/main.cpp#L7544>
399pub const MAX_REJECT_MESSAGE_LENGTH: usize = 12;
400
401/// The maximum size of the rejection reason.
402///
403/// This is equivalent to `MAX_REJECT_MESSAGE_LENGTH` in zcashd:
404/// <https://github.com/zcash/zcash/blob/adfc7218435faa1c8985a727f997a795dcffa0c7/src/main.h#L126>
405/// <https://github.com/zcash/zcash/blob/c0fbeb809bf2303e30acef0d2b74db11e9177427/src/main.cpp#L7544>
406pub const MAX_REJECT_REASON_LENGTH: usize = 111;
407
408impl From<VersionMessage> for Message {
409 fn from(version_message: VersionMessage) -> Self {
410 Message::Version(version_message)
411 }
412}
413
414impl TryFrom<Message> for VersionMessage {
415 type Error = BoxError;
416
417 fn try_from(message: Message) -> Result<Self, Self::Error> {
418 match message {
419 Message::Version(version_message) => Ok(version_message),
420 _ => Err(format!(
421 "{} message is not a version message: {message:?}",
422 message.command()
423 )
424 .into()),
425 }
426 }
427}
428
429// TODO: add tests for Error conversion and Reject message serialization
430// (Zebra does not currently send reject messages, and it ignores received reject messages.)
431impl<E> From<E> for Message
432where
433 E: Error,
434{
435 fn from(e: E) -> Self {
436 let message = e
437 .to_string()
438 .escape_default()
439 .take(MAX_REJECT_MESSAGE_LENGTH)
440 .collect();
441 let reason = e
442 .source()
443 .map(ToString::to_string)
444 .unwrap_or_default()
445 .escape_default()
446 .take(MAX_REJECT_REASON_LENGTH)
447 .collect();
448
449 Message::Reject {
450 message,
451
452 // The generic case, impls for specific error types should
453 // use specific varieties of `RejectReason`.
454 ccode: RejectReason::Other,
455
456 reason,
457
458 // The hash of the rejected block or transaction.
459 // We don't have that data here, so the caller needs to fill it in later.
460 data: None,
461 }
462 }
463}
464
465/// Reject Reason CCodes
466///
467/// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#reject)
468#[derive(Copy, Clone, Debug, Eq, PartialEq)]
469#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
470#[repr(u8)]
471#[allow(missing_docs)]
472pub enum RejectReason {
473 Malformed = 0x01,
474 Invalid = 0x10,
475 Obsolete = 0x11,
476 Duplicate = 0x12,
477 Nonstandard = 0x40,
478 Dust = 0x41,
479 InsufficientFee = 0x42,
480 Checkpoint = 0x43,
481 Other = 0x50,
482}
483
484impl fmt::Display for Message {
485 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
486 f.write_str(&match self {
487 Message::Version(VersionMessage {
488 version,
489 address_recv,
490 address_from,
491 user_agent,
492 ..
493 }) => format!(
494 "version {{ network: {}, recv: {},_from: {}, user_agent: {:?} }}",
495 version,
496 address_recv.addr(),
497 address_from.addr(),
498 user_agent,
499 ),
500 Message::Verack => "verack".to_string(),
501
502 Message::Ping(_) => "ping".to_string(),
503 Message::Pong(_) => "pong".to_string(),
504
505 Message::Reject {
506 message,
507 reason,
508 data,
509 ..
510 } => format!(
511 "reject {{ message: {:?}, reason: {:?}, data: {} }}",
512 message,
513 reason,
514 if data.is_some() { "Some" } else { "None" },
515 ),
516
517 Message::GetAddr => "getaddr".to_string(),
518 Message::Addr(addrs) => format!("addr {{ addrs: {} }}", addrs.len()),
519
520 Message::GetBlocks { known_blocks, stop } => format!(
521 "getblocks {{ known_blocks: {}, stop: {} }}",
522 known_blocks.len(),
523 if stop.is_some() { "Some" } else { "None" },
524 ),
525 Message::Inv(invs) => format!("inv {{ invs: {} }}", invs.len()),
526
527 Message::GetHeaders { known_blocks, stop } => format!(
528 "getheaders {{ known_blocks: {}, stop: {} }}",
529 known_blocks.len(),
530 if stop.is_some() { "Some" } else { "None" },
531 ),
532 Message::Headers(headers) => format!("headers {{ headers: {} }}", headers.len()),
533
534 Message::GetData(invs) => format!("getdata {{ invs: {} }}", invs.len()),
535 Message::Block(block) => format!(
536 "block {{ height: {}, hash: {} }}",
537 block
538 .coinbase_height()
539 .as_ref()
540 .map(|h| h.0.to_string())
541 .unwrap_or_else(|| "None".into()),
542 block.hash(),
543 ),
544 Message::Tx(_) => "tx".to_string(),
545 Message::SendCompact { .. }
546 | Message::CompactBlock(_)
547 | Message::GetBlockTransactions(_)
548 | Message::BlockTransactions(_) => self.command().to_string(),
549 Message::NotFound(invs) => format!("notfound {{ invs: {} }}", invs.len()),
550
551 Message::Mempool => "mempool".to_string(),
552
553 Message::FilterLoad { .. } => "filterload".to_string(),
554 Message::FilterAdd { .. } => "filteradd".to_string(),
555 Message::FilterClear => "filterclear".to_string(),
556 })
557 }
558}
559
560impl Message {
561 /// Returns the Zcash protocol message command as a string.
562 pub fn command(&self) -> &'static str {
563 match self {
564 Message::Version(_) => "version",
565 Message::Verack => "verack",
566 Message::Ping(_) => "ping",
567 Message::Pong(_) => "pong",
568 Message::Reject { .. } => "reject",
569 Message::GetAddr => "getaddr",
570 Message::Addr(_) => "addr",
571 Message::GetBlocks { .. } => "getblocks",
572 Message::Inv(_) => "inv",
573 Message::GetHeaders { .. } => "getheaders",
574 Message::Headers(_) => "headers",
575 Message::GetData(_) => "getdata",
576 Message::Block(_) => "block",
577 Message::SendCompact { .. } => "sendcmpct",
578 Message::CompactBlock(_) => "cmpctblock",
579 Message::GetBlockTransactions(_) => "getblocktxn",
580 Message::BlockTransactions(_) => "blocktxn",
581 Message::Tx(_) => "tx",
582 Message::NotFound(_) => "notfound",
583 Message::Mempool => "mempool",
584 Message::FilterLoad { .. } => "filterload",
585 Message::FilterAdd { .. } => "filteradd",
586 Message::FilterClear => "filterclear",
587 }
588 }
589}