Skip to main content

zebra_network/protocol/external/
codec.rs

1//! A Tokio codec mapping byte streams to Bitcoin message streams.
2
3use std::{
4    cmp::min,
5    fmt,
6    io::{Cursor, Read, Write},
7    sync::Arc,
8    time::{Duration, Instant},
9};
10
11use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
12use bytes::{BufMut, BytesMut};
13use chrono::{TimeZone, Utc};
14use tokio_util::codec::{Decoder, Encoder};
15
16use zebra_chain::{
17    block::{self, Block},
18    parameters::{Magic, Network},
19    serialization::{
20        sha256d, zcash_deserialize_bytes_external_count, zcash_deserialize_external_count,
21        zcash_deserialize_string_external_count, CompactSizeMessage, FakeWriter, ReadZcashExt,
22        SerializationError as Error, ZcashDeserialize, ZcashDeserializeInto, ZcashSerialize,
23        MAX_HEADERS_PER_MESSAGE, MAX_PROTOCOL_MESSAGE_LEN,
24    },
25    transaction::Transaction,
26};
27
28use crate::constants;
29
30use super::{
31    addr::{AddrInVersion, AddrV1, AddrV2},
32    compact::{
33        BlockTransactions, BlockTransactionsRequest, CompactBlock, ExpectedBlockTransactions,
34    },
35    message::{
36        Message, RejectReason, VersionMessage, MAX_REJECT_MESSAGE_LENGTH, MAX_REJECT_REASON_LENGTH,
37        MAX_USER_AGENT_LENGTH,
38    },
39    types::*,
40};
41
42#[cfg(test)]
43mod tests;
44
45/// The length of a Bitcoin message header.
46const HEADER_LEN: usize = 24usize;
47
48/// The number of messages in a row that one [`Decoder::decode`] call ignores.
49///
50/// The messages behind them in the buffer are decoded when the peer sends more bytes. Peers
51/// don't send this many ignored messages in a row in normal operation.
52pub(super) const MAX_IGNORED_MESSAGES_PER_DECODE: usize = 1024;
53
54/// The maximum body length allowed before the handshake completes.
55///
56/// Version messages are ~344 bytes max (including a 256-byte user agent);
57/// verack is 0 bytes. 1 KB provides headroom for future protocol changes.
58const MAX_HANDSHAKE_BODY_LEN: usize = 1024;
59
60/// Initial cap on reserved body capacity, before any body bytes have arrived.
61///
62/// `body_len` is peer-declared and untrusted; this bounds the upfront cost of
63/// a header-only peer to one step instead of the full declared length.
64const INITIAL_BODY_RESERVATION_STEP: usize = 16 * 1024;
65
66/// A codec which produces Bitcoin messages from byte streams and vice versa.
67pub struct Codec {
68    builder: Builder,
69    state: DecodeState,
70    early_block_relay: bool,
71    compact_sent: bool,
72    compact_receive: bool,
73    compact_recovery: Option<tokio::sync::watch::Receiver<Option<ExpectedBlockTransactions>>>,
74}
75
76/// A builder for specifying [`Codec`] options.
77pub struct Builder {
78    /// The network magic to use in encoding.
79    network: Network,
80    /// The protocol version to speak when encoding/decoding.
81    version: Version,
82    /// The maximum allowable message length.
83    max_len: usize,
84}
85
86impl Codec {
87    /// Return a builder for constructing a [`Codec`].
88    pub fn builder() -> Builder {
89        Builder {
90            network: Network::Mainnet,
91            version: constants::CURRENT_NETWORK_PROTOCOL_VERSION,
92            max_len: MAX_HANDSHAKE_BODY_LEN,
93        }
94    }
95
96    /// Reconfigure the version used by the codec, e.g., after completing a handshake.
97    pub fn reconfigure_version(&mut self, version: Version) {
98        self.builder.version = version;
99    }
100
101    /// Raise the maximum accepted body length to the full protocol limit.
102    ///
103    /// Called after a successful handshake so post-handshake messages (blocks,
104    /// transactions) can use the full `MAX_PROTOCOL_MESSAGE_LEN`.
105    pub fn reconfigure_full_body_len(&mut self) {
106        self.builder.max_len = MAX_PROTOCOL_MESSAGE_LEN;
107    }
108
109    /// Enables compact negotiation only after both ends advertised the service bit.
110    pub(crate) fn reconfigure_early_block_relay(&mut self, enabled: bool) {
111        self.early_block_relay = enabled;
112    }
113
114    /// Track the connection's live recovery request independently of announcement preferences.
115    pub(crate) fn reconfigure_compact_recovery(
116        &mut self,
117        recovery: tokio::sync::watch::Receiver<Option<ExpectedBlockTransactions>>,
118    ) {
119        self.compact_recovery = Some(recovery);
120    }
121}
122
123impl Builder {
124    /// Finalize the builder and return a [`Codec`].
125    pub fn finish(self) -> Codec {
126        Codec {
127            builder: self,
128            state: DecodeState::Head,
129            early_block_relay: false,
130            compact_sent: false,
131            compact_receive: false,
132            compact_recovery: None,
133        }
134    }
135
136    /// Configure the codec for the given [`Network`].
137    pub fn for_network(mut self, network: &Network) -> Self {
138        self.network = network.clone();
139        self
140    }
141
142    /// Configure the codec for the given [`Version`].
143    #[allow(dead_code)]
144    pub fn for_version(mut self, version: Version) -> Self {
145        self.version = version;
146        self
147    }
148
149    /// Configure the codec's maximum accepted payload size, in bytes.
150    #[allow(dead_code)]
151    pub fn with_max_body_len(mut self, len: usize) -> Self {
152        self.max_len = len;
153        self
154    }
155}
156
157// ======== Encoding =========
158
159impl Encoder<Message> for Codec {
160    type Error = Error;
161
162    fn encode(&mut self, item: Message, dst: &mut BytesMut) -> Result<(), Self::Error> {
163        use Error::Parse;
164
165        let body_length = self.body_length(&item)?;
166
167        if body_length > self.builder.max_len {
168            return Err(Parse("body length exceeded maximum size"));
169        }
170        match &item {
171            Message::SendCompact {
172                high_bandwidth,
173                version,
174            } => {
175                self.compact_receive = self.early_block_relay && *high_bandwidth && *version == 1;
176            }
177            Message::CompactBlock(_) => self.compact_sent = true,
178            _ => {}
179        }
180
181        // The bounded message length plus its header fits in u64.
182        metrics::counter!("zcash.net.out.bytes.total").increment((body_length + HEADER_LEN) as u64);
183
184        use Message::*;
185        // Note: because all match arms must have
186        // the same type, and the array length is
187        // part of the type, having at least one
188        // of length 12 checks that they are all
189        // of length 12, as they must be &[u8; 12].
190        let command = match item {
191            Version { .. } => b"version\0\0\0\0\0",
192            Verack => b"verack\0\0\0\0\0\0",
193            Ping { .. } => b"ping\0\0\0\0\0\0\0\0",
194            Pong { .. } => b"pong\0\0\0\0\0\0\0\0",
195            Reject { .. } => b"reject\0\0\0\0\0\0",
196            Addr { .. } => b"addr\0\0\0\0\0\0\0\0",
197            GetAddr => b"getaddr\0\0\0\0\0",
198            Block { .. } => b"block\0\0\0\0\0\0\0",
199            SendCompact { .. } => b"sendcmpct\0\0\0",
200            CompactBlock { .. } => b"cmpctblock\0\0",
201            GetBlockTransactions { .. } => b"getblocktxn\0",
202            BlockTransactions { .. } => b"blocktxn\0\0\0\0",
203            GetBlocks { .. } => b"getblocks\0\0\0",
204            Headers { .. } => b"headers\0\0\0\0\0",
205            GetHeaders { .. } => b"getheaders\0\0",
206            Inv { .. } => b"inv\0\0\0\0\0\0\0\0\0",
207            GetData { .. } => b"getdata\0\0\0\0\0",
208            NotFound { .. } => b"notfound\0\0\0\0",
209            Tx { .. } => b"tx\0\0\0\0\0\0\0\0\0\0",
210            Mempool => b"mempool\0\0\0\0\0",
211            FilterLoad { .. } => b"filterload\0\0",
212            FilterAdd { .. } => b"filteradd\0\0\0",
213            FilterClear => b"filterclear\0",
214        };
215        trace!(?item, len = body_length);
216
217        dst.reserve(HEADER_LEN + body_length);
218        let start_len = dst.len();
219        {
220            let dst = &mut dst.writer();
221            dst.write_all(&self.builder.network.magic().0[..])?;
222            dst.write_all(command)?;
223            dst.write_u32::<LittleEndian>(body_length as u32)?;
224
225            // We zero the checksum at first, and compute it later
226            // after the body has been written.
227            dst.write_u32::<LittleEndian>(0)?;
228
229            self.write_body(&item, dst)?;
230        }
231        let checksum = sha256d::Checksum::from(&dst[start_len + HEADER_LEN..]);
232        dst[start_len + 20..][..4].copy_from_slice(&checksum.0);
233
234        Ok(())
235    }
236}
237
238impl Codec {
239    /// Obtain the size of the body of a given message. This will match the
240    /// number of bytes written to the writer provided to `write_body` for the
241    /// same message.
242    // # Performance TODO
243    //
244    // If this code shows up in profiles, replace with a size estimate or cached size,
245    // to avoid multiple serializations for large data structures like lists, blocks, and transactions.
246    fn body_length(&self, msg: &Message) -> Result<usize, Error> {
247        let mut writer = FakeWriter(0);
248        self.write_body(msg, &mut writer)?;
249        Ok(writer.0)
250    }
251
252    /// Write the body of the message into the given writer. This allows writing
253    /// the message body prior to writing the header, so that the header can
254    /// contain a checksum of the message body.
255    fn write_body<W: Write>(&self, msg: &Message, mut writer: W) -> Result<(), Error> {
256        match msg {
257            Message::Version(VersionMessage {
258                version,
259                services,
260                timestamp,
261                address_recv,
262                address_from,
263                nonce,
264                user_agent,
265                start_height,
266                relay,
267            }) => {
268                writer.write_u32::<LittleEndian>(version.0)?;
269                writer.write_u64::<LittleEndian>(services.bits())?;
270                // # Security
271                // DateTime<Utc>::timestamp has a smaller range than i64, so
272                // serialization can not error.
273                writer.write_i64::<LittleEndian>(timestamp.timestamp())?;
274
275                address_recv.zcash_serialize(&mut writer)?;
276                address_from.zcash_serialize(&mut writer)?;
277
278                writer.write_u64::<LittleEndian>(nonce.0)?;
279
280                if user_agent.len() > MAX_USER_AGENT_LENGTH {
281                    // zcashd won't accept this version message
282                    return Err(Error::Parse(
283                        "user agent too long: must be 256 bytes or less",
284                    ));
285                }
286
287                user_agent.zcash_serialize(&mut writer)?;
288                writer.write_u32::<LittleEndian>(start_height.0)?;
289                writer.write_u8(*relay as u8)?;
290            }
291            Message::Verack => { /* Empty payload -- no-op */ }
292            Message::Ping(nonce) => {
293                writer.write_u64::<LittleEndian>(nonce.0)?;
294            }
295            Message::Pong(nonce) => {
296                writer.write_u64::<LittleEndian>(nonce.0)?;
297            }
298            Message::Reject {
299                message,
300                ccode,
301                reason,
302                data,
303            } => {
304                if message.len() > MAX_REJECT_MESSAGE_LENGTH {
305                    // zcashd won't accept this reject message
306                    return Err(Error::Parse(
307                        "reject message too long: must be 12 bytes or less",
308                    ));
309                }
310
311                message.zcash_serialize(&mut writer)?;
312
313                writer.write_u8(*ccode as u8)?;
314
315                if reason.len() > MAX_REJECT_REASON_LENGTH {
316                    return Err(Error::Parse(
317                        "reject reason too long: must be 111 bytes or less",
318                    ));
319                }
320
321                reason.zcash_serialize(&mut writer)?;
322                if let Some(data) = data {
323                    writer.write_all(data)?;
324                }
325            }
326            Message::Addr(addrs) => {
327                assert!(
328                    addrs.len() <= constants::MAX_ADDRS_IN_MESSAGE,
329                    "unexpectedly large Addr message: greater than MAX_ADDRS_IN_MESSAGE addresses"
330                );
331
332                // Regardless of the way we received the address,
333                // Zebra always sends `addr` messages
334                let v1_addrs: Vec<AddrV1> = addrs
335                    .iter()
336                    .map(|addr| AddrV1::from(addr.clone()))
337                    .collect();
338                v1_addrs.zcash_serialize(&mut writer)?
339            }
340            Message::GetAddr => { /* Empty payload -- no-op */ }
341            Message::Block(block) => block.zcash_serialize(&mut writer)?,
342            Message::SendCompact {
343                high_bandwidth,
344                version,
345            } => {
346                writer.write_u8(u8::from(*high_bandwidth))?;
347                writer.write_u64::<LittleEndian>(*version)?;
348            }
349            Message::CompactBlock(block) => block.zcash_serialize(&mut writer)?,
350            Message::GetBlockTransactions(request) => request.zcash_serialize(&mut writer)?,
351            Message::BlockTransactions(response) => response.zcash_serialize(&mut writer)?,
352            Message::GetBlocks { known_blocks, stop } => {
353                writer.write_u32::<LittleEndian>(self.builder.version.0)?;
354                known_blocks.zcash_serialize(&mut writer)?;
355                stop.unwrap_or(block::Hash([0; 32]))
356                    .zcash_serialize(&mut writer)?;
357            }
358            Message::GetHeaders { known_blocks, stop } => {
359                writer.write_u32::<LittleEndian>(self.builder.version.0)?;
360                known_blocks.zcash_serialize(&mut writer)?;
361                stop.unwrap_or(block::Hash([0; 32]))
362                    .zcash_serialize(&mut writer)?;
363            }
364            Message::Headers(headers) => headers.zcash_serialize(&mut writer)?,
365            Message::Inv(hashes) => hashes.zcash_serialize(&mut writer)?,
366            Message::GetData(hashes) => hashes.zcash_serialize(&mut writer)?,
367            Message::NotFound(hashes) => hashes.zcash_serialize(&mut writer)?,
368            Message::Tx(transaction) => transaction.transaction.zcash_serialize(&mut writer)?,
369            Message::Mempool => { /* Empty payload -- no-op */ }
370            Message::FilterLoad {
371                filter,
372                hash_functions_count,
373                tweak,
374                flags,
375            } => {
376                writer.write_all(&filter.0)?;
377                writer.write_u32::<LittleEndian>(*hash_functions_count)?;
378                writer.write_u32::<LittleEndian>(tweak.0)?;
379                writer.write_u8(*flags)?;
380            }
381            Message::FilterAdd { data } => {
382                writer.write_all(data)?;
383            }
384            Message::FilterClear => { /* Empty payload -- no-op */ }
385        }
386        Ok(())
387    }
388}
389
390// ======== Decoding =========
391
392enum DecodeState {
393    Head,
394    Body {
395        body_len: usize,
396        command: [u8; 12],
397        checksum: sha256d::Checksum,
398    },
399}
400
401impl fmt::Debug for DecodeState {
402    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
403        match self {
404            DecodeState::Head => write!(f, "DecodeState::Head"),
405            DecodeState::Body {
406                body_len,
407                command,
408                checksum,
409            } => f
410                .debug_struct("DecodeState::Body")
411                .field("body_len", &body_len)
412                .field("command", &String::from_utf8_lossy(command))
413                .field("checksum", &checksum)
414                .finish(),
415        }
416    }
417}
418
419/// The result of decoding the next message in a buffer.
420enum Decoded {
421    /// A message.
422    Message(Message),
423
424    /// A message that Zebra ignores, which has been consumed from the buffer.
425    Ignored,
426
427    /// The buffer doesn't hold the whole message yet.
428    Incomplete,
429}
430
431impl Decoder for Codec {
432    type Item = Message;
433    type Error = Error;
434
435    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
436        // The reader only calls this again once the peer has sent more bytes, so after an ignored
437        // message, decode the messages behind it that are already in the buffer. Each message
438        // consumes at least a header, so this ends when the buffer runs out.
439        //
440        // An ignored message can be as small as its header, so a full buffer can hold tens of
441        // thousands of them. This stops after `MAX_IGNORED_MESSAGES_PER_DECODE` of them, so the
442        // connection's task goes back to the reader, where it can yield to other tasks.
443        for _ in 0..MAX_IGNORED_MESSAGES_PER_DECODE {
444            match self.decode_message(src)? {
445                Decoded::Message(message) => return Ok(Some(message)),
446                Decoded::Ignored => {}
447                Decoded::Incomplete => return Ok(None),
448            }
449        }
450
451        Ok(None)
452    }
453}
454
455impl Codec {
456    /// Decodes the next message in `src`, if `src` holds all of it.
457    #[allow(clippy::unwrap_in_result)]
458    fn decode_message(&mut self, src: &mut BytesMut) -> Result<Decoded, Error> {
459        use Error::Parse;
460        match self.state {
461            DecodeState::Head => {
462                // First check that the src buffer contains an entire header.
463                if src.len() < HEADER_LEN {
464                    trace!(?self.state, "src buffer does not have an entire header, waiting");
465                    // Signal that decoding requires more data.
466                    return Ok(Decoded::Incomplete);
467                }
468
469                // Now that we know that src contains a header, split off the header section.
470                let header = src.split_to(HEADER_LEN);
471
472                // Create a cursor over the header and parse its fields.
473                let mut header_reader = Cursor::new(&header);
474                let magic = Magic(header_reader.read_4_bytes()?);
475                let command = header_reader.read_12_bytes()?;
476                let body_len = header_reader.read_u32::<LittleEndian>()? as usize;
477                let checksum = sha256d::Checksum(header_reader.read_4_bytes()?);
478                trace!(
479                    ?self.state,
480                    ?magic,
481                    command = %String::from_utf8(
482                        command.iter()
483                            .cloned()
484                            .flat_map(std::ascii::escape_default)
485                            .collect()
486                    ).unwrap(),
487                    body_len,
488                    ?checksum,
489                    "read header from src buffer"
490                );
491
492                if magic != self.builder.network.magic() {
493                    return Err(Parse("supplied magic did not meet expectations"));
494                }
495                if body_len > self.builder.max_len {
496                    return Err(Parse("body length exceeded maximum size"));
497                }
498
499                // The bounded message length plus its header fits in u64.
500                metrics::counter!("zcash.net.in.bytes.total")
501                    .increment((body_len + HEADER_LEN) as u64);
502
503                // Cap the upfront reservation instead of trusting body_len; grows
504                // as more of the body arrives, never beyond the declared length
505                // (below).
506                src.reserve(HEADER_LEN + body_len.min(INITIAL_BODY_RESERVATION_STEP));
507
508                self.state = DecodeState::Body {
509                    body_len,
510                    command,
511                    checksum,
512                };
513
514                // Now that the state is updated, recurse to attempt body decoding.
515                self.decode_message(src)
516            }
517            DecodeState::Body {
518                body_len,
519                command,
520                checksum,
521            } => {
522                if src.len() < body_len {
523                    // Grow as the body arrives, never reserving beyond the
524                    // declared length, instead of trusting the peer-declared
525                    // remaining length upfront.
526                    let remaining = body_len - src.len();
527
528                    if src.capacity() - src.len() < remaining.min(INITIAL_BODY_RESERVATION_STEP) {
529                        // `BytesMut::reserve` grows the underlying `Vec` by doubling its
530                        // capacity, which can overshoot `body_len` by up to ~2x (see #11793
531                        // review). Allocate exactly instead: proportional to the bytes
532                        // received so far, capped at the declared body length.
533                        let target = body_len
534                            .min(src.len() + src.len().max(2 * INITIAL_BODY_RESERVATION_STEP));
535                        let mut grown = BytesMut::with_capacity(target + HEADER_LEN);
536                        grown.extend_from_slice(src);
537                        *src = grown;
538                    }
539
540                    trace!(?self.state, len = src.len(), "src buffer does not have an entire body, waiting");
541                    return Ok(Decoded::Incomplete);
542                }
543
544                // Now that we know we have the full body, split off the body,
545                // and reset the decoder state for the next message. Otherwise
546                // we will attempt to read the next header as the current body.
547                let body = src.split_to(body_len);
548                self.state = DecodeState::Head;
549
550                // With compact relay, ignore the compact messages this connection isn't waiting
551                // for, before hashing or deserializing their bodies. Without it, they are unknown
552                // commands, which are ignored below, after their checksum is checked.
553                let expected = match &command {
554                    b"cmpctblock\0\0" => self.compact_receive,
555                    // The connection checks the retained block and its serving deadline.
556                    b"getblocktxn\0" => self.compact_sent,
557                    // Only the response to the live request, with the number of transactions it
558                    // asked for, is decoded.
559                    b"blocktxn\0\0\0\0" => self.compact_recovery.as_ref().is_some_and(|recovery| {
560                        recovery.has_changed().is_ok()
561                            && recovery
562                                .borrow()
563                                .is_some_and(|expected| expected.matches(&body))
564                    }),
565                    _ => true,
566                };
567                if self.early_block_relay && !expected {
568                    return Ok(Decoded::Ignored);
569                }
570
571                if checksum != sha256d::Checksum::from(&body[..]) {
572                    return Err(Parse(
573                        "supplied message checksum does not match computed checksum",
574                    ));
575                }
576
577                let mut body_reader = Cursor::new(&body);
578                match &command {
579                    b"version\0\0\0\0\0" => self.read_version(&mut body_reader),
580                    b"verack\0\0\0\0\0\0" => self.read_verack(&mut body_reader),
581                    b"ping\0\0\0\0\0\0\0\0" => self.read_ping(&mut body_reader),
582                    b"pong\0\0\0\0\0\0\0\0" => self.read_pong(&mut body_reader),
583                    b"reject\0\0\0\0\0\0" => self.read_reject(&mut body_reader),
584                    b"addr\0\0\0\0\0\0\0\0" => self.read_addr(&mut body_reader),
585                    b"addrv2\0\0\0\0\0\0" => self.read_addrv2(&mut body_reader),
586                    b"getaddr\0\0\0\0\0" => self.read_getaddr(&mut body_reader),
587                    b"block\0\0\0\0\0\0\0" => self.read_block(&mut body_reader),
588                    b"sendcmpct\0\0\0" if self.early_block_relay => {
589                        let high_bandwidth = match body_reader.read_u8()? {
590                            0 => false,
591                            1 => true,
592                            _ => return Err(Parse("invalid sendcmpct boolean")),
593                        };
594                        let version = body_reader.read_u64::<LittleEndian>()?;
595                        Ok(Message::SendCompact {
596                            high_bandwidth,
597                            version,
598                        })
599                    }
600                    b"cmpctblock\0\0" if self.early_block_relay => {
601                        Self::deserialize_spawning::<CompactBlock, _>(&mut body_reader)
602                            .map(|block| Message::CompactBlock(Arc::new(block)))
603                    }
604                    b"getblocktxn\0" if self.early_block_relay => {
605                        BlockTransactionsRequest::zcash_deserialize(&mut body_reader)
606                            .map(Message::GetBlockTransactions)
607                    }
608                    b"blocktxn\0\0\0\0" if self.early_block_relay => {
609                        Self::deserialize_spawning::<BlockTransactions, _>(&mut body_reader)
610                            .map(Message::BlockTransactions)
611                    }
612                    b"getblocks\0\0\0" => self.read_getblocks(&mut body_reader),
613                    b"headers\0\0\0\0\0" => self.read_headers(&mut body_reader),
614                    b"getheaders\0\0" => self.read_getheaders(&mut body_reader),
615                    b"inv\0\0\0\0\0\0\0\0\0" => self.read_inv(&mut body_reader),
616                    b"getdata\0\0\0\0\0" => self.read_getdata(&mut body_reader),
617                    b"notfound\0\0\0\0" => self.read_notfound(&mut body_reader),
618                    b"tx\0\0\0\0\0\0\0\0\0\0" => self.read_tx(&mut body_reader),
619                    b"mempool\0\0\0\0\0" => self.read_mempool(&mut body_reader),
620                    b"filterload\0\0" => self.read_filterload(&mut body_reader, body_len),
621                    b"filteradd\0\0\0" => self.read_filteradd(&mut body_reader, body_len),
622                    b"filterclear\0" => self.read_filterclear(&mut body_reader),
623                    _ => {
624                        let command_string = String::from_utf8_lossy(&command);
625
626                        // # Security
627                        //
628                        // Zcash connections are not authenticated, so malicious nodes can
629                        // send fake messages, with connected peers' IP addresses in the IP header.
630                        //
631                        // Since we can't verify their source, Zebra needs to ignore unexpected messages,
632                        // because closing the connection could cause a denial of service or eclipse attack.
633                        debug!(?command, %command_string, "unknown message command from peer");
634                        return Ok(Decoded::Ignored);
635                    }
636                }
637                // This is also convenient for tracing the parse result.
638                .map(|msg| {
639                    // bitcoin allows extra data at the end of most messages,
640                    // so that old nodes can still read newer message formats,
641                    // and ignore any extra fields
642                    let extra_bytes = body.len() as u64 - body_reader.position();
643                    if extra_bytes == 0 {
644                        trace!(?extra_bytes, %msg, "finished message decoding");
645                    } else {
646                        // log when there are extra bytes, so we know when we need to
647                        // upgrade message formats
648                        debug!(?extra_bytes, %msg, "extra data after decoding message");
649                    }
650                    Decoded::Message(msg)
651                })
652            }
653        }
654    }
655}
656
657impl Codec {
658    /// Deserializes a version message.
659    ///
660    /// The `relay` field is optional, as defined in <https://developer.bitcoin.org/reference/p2p_networking.html#version>
661    ///
662    /// Note: zcashd only requires fields up to `address_recv`, but everything up to `relay` is required in Zebra.
663    ///       see <https://github.com/zcash/zcash/blob/11d563904933e889a11d9685c3b249f1536cfbe7/src/main.cpp#L6490-L6507>
664    fn read_version<R: Read>(&self, mut reader: R) -> Result<Message, Error> {
665        Ok(VersionMessage {
666            version: Version(reader.read_u32::<LittleEndian>()?),
667            // Use from_bits_truncate to discard unknown service bits.
668            services: PeerServices::from_bits_truncate(reader.read_u64::<LittleEndian>()?),
669            timestamp: Utc
670                .timestamp_opt(reader.read_i64::<LittleEndian>()?, 0)
671                .single()
672                .ok_or(Error::Parse(
673                    "version timestamp is out of range for DateTime",
674                ))?,
675            address_recv: AddrInVersion::zcash_deserialize(&mut reader)?,
676            address_from: AddrInVersion::zcash_deserialize(&mut reader)?,
677            nonce: Nonce(reader.read_u64::<LittleEndian>()?),
678            user_agent: {
679                let byte_count: CompactSizeMessage = (&mut reader).zcash_deserialize_into()?;
680                let byte_count: usize = byte_count.into();
681
682                // # Security
683                //
684                // Limit peer set memory usage, Zebra stores an `Arc<VersionMessage>` per
685                // connected peer.
686                //
687                // Without this check, we can use `200 peers * 2 MB message size limit = 400 MB`.
688                if byte_count > MAX_USER_AGENT_LENGTH {
689                    return Err(Error::Parse(
690                        "user agent too long: must be 256 bytes or less",
691                    ));
692                }
693
694                zcash_deserialize_string_external_count(byte_count, &mut reader)?
695            },
696            start_height: block::Height(reader.read_u32::<LittleEndian>()?),
697            relay: match reader.read_u8() {
698                Ok(val @ 0..=1) => val == 1,
699                Ok(_) => return Err(Error::Parse("non-bool value supplied in relay field")),
700                Err(err) if err.kind() == std::io::ErrorKind::UnexpectedEof => true,
701                Err(err) => Err(err)?,
702            },
703        }
704        .into())
705    }
706
707    fn read_verack<R: Read>(&self, mut _reader: R) -> Result<Message, Error> {
708        Ok(Message::Verack)
709    }
710
711    fn read_ping<R: Read>(&self, mut reader: R) -> Result<Message, Error> {
712        Ok(Message::Ping(Nonce(reader.read_u64::<LittleEndian>()?)))
713    }
714
715    fn read_pong<R: Read>(&self, mut reader: R) -> Result<Message, Error> {
716        Ok(Message::Pong(Nonce(reader.read_u64::<LittleEndian>()?)))
717    }
718
719    fn read_reject<R: Read>(&self, mut reader: R) -> Result<Message, Error> {
720        Ok(Message::Reject {
721            message: {
722                let byte_count: CompactSizeMessage = (&mut reader).zcash_deserialize_into()?;
723                let byte_count: usize = byte_count.into();
724
725                // # Security
726                //
727                // Limit log size on disk, Zebra might print large reject messages to disk.
728                if byte_count > MAX_REJECT_MESSAGE_LENGTH {
729                    return Err(Error::Parse(
730                        "reject message too long: must be 12 bytes or less",
731                    ));
732                }
733
734                zcash_deserialize_string_external_count(byte_count, &mut reader)?
735            },
736            ccode: match reader.read_u8()? {
737                0x01 => RejectReason::Malformed,
738                0x10 => RejectReason::Invalid,
739                0x11 => RejectReason::Obsolete,
740                0x12 => RejectReason::Duplicate,
741                0x40 => RejectReason::Nonstandard,
742                0x41 => RejectReason::Dust,
743                0x42 => RejectReason::InsufficientFee,
744                0x43 => RejectReason::Checkpoint,
745                0x50 => RejectReason::Other,
746                _ => return Err(Error::Parse("invalid RejectReason value in ccode field")),
747            },
748            reason: {
749                let byte_count: CompactSizeMessage = (&mut reader).zcash_deserialize_into()?;
750                let byte_count: usize = byte_count.into();
751
752                // # Security
753                //
754                // Limit log size on disk, Zebra might print large reject messages to disk.
755                if byte_count > MAX_REJECT_REASON_LENGTH {
756                    return Err(Error::Parse(
757                        "reject reason too long: must be 111 bytes or less",
758                    ));
759                }
760
761                zcash_deserialize_string_external_count(byte_count, &mut reader)?
762            },
763            // Sometimes there's data, sometimes there isn't. There's no length
764            // field, this is just implicitly encoded by the body_len.
765            // Apparently all existing implementations only supply 32 bytes of
766            // data (hash identifying the rejected object) or none (and we model
767            // the Reject message that way), so instead of passing in the
768            // body_len separately and calculating remaining bytes, just try to
769            // read 32 bytes and ignore any failures. (The caller will log and
770            // ignore any trailing bytes.)
771            data: reader.read_32_bytes().ok(),
772        })
773    }
774
775    /// Deserialize an `addr` (v1) message into a list of `MetaAddr`s.
776    pub(super) fn read_addr<R: Read>(&self, reader: R) -> Result<Message, Error> {
777        let addrs: Vec<AddrV1> = reader.zcash_deserialize_into()?;
778
779        if addrs.len() > constants::MAX_ADDRS_IN_MESSAGE {
780            return Err(Error::Parse(
781                "more than MAX_ADDRS_IN_MESSAGE in addr message",
782            ));
783        }
784
785        // Convert the received address format to Zebra's internal `MetaAddr`.
786        let addrs = addrs.into_iter().map(Into::into).collect();
787        Ok(Message::Addr(addrs))
788    }
789
790    /// Deserialize an `addrv2` message into a list of `MetaAddr`s.
791    ///
792    /// Currently, Zebra parses received `addrv2`s, ignoring some address types.
793    /// Zebra never sends `addrv2` messages.
794    pub(super) fn read_addrv2<R: Read>(&self, reader: R) -> Result<Message, Error> {
795        let addrs: Vec<AddrV2> = reader.zcash_deserialize_into()?;
796
797        if addrs.len() > constants::MAX_ADDRS_IN_MESSAGE {
798            return Err(Error::Parse(
799                "more than MAX_ADDRS_IN_MESSAGE in addrv2 message",
800            ));
801        }
802
803        // Convert the received address format to Zebra's internal `MetaAddr`,
804        // ignoring unsupported network IDs.
805        let addrs = addrs
806            .into_iter()
807            .filter_map(|addr| addr.try_into().ok())
808            .collect();
809        Ok(Message::Addr(addrs))
810    }
811
812    fn read_getaddr<R: Read>(&self, mut _reader: R) -> Result<Message, Error> {
813        Ok(Message::GetAddr)
814    }
815
816    /// Decodes the block at the reader's position as a job in the Rayon thread pool, parsing and
817    /// hashing a large block's transactions in parallel, and moves the reader past the block.
818    #[allow(clippy::unwrap_in_result)]
819    fn read_block(&self, body_reader: &mut Cursor<&BytesMut>) -> Result<Message, Error> {
820        let decode_start = Instant::now();
821        let body: &BytesMut = body_reader.get_ref();
822        // A position past the end of the body leaves no bytes to decode.
823        let position = usize::try_from(body_reader.position())
824            .map_or(body.len(), |position| position.min(body.len()));
825        let mut unread = &body[position..];
826        let mut result = None;
827        let mut wait = Duration::ZERO;
828
829        // Correctness: decoding is CPU-intensive, so it runs as a job in the Rayon pool. The
830        // other blocks wait as message bytes, however many connections receive one.
831        //
832        // A worker that waits for the tasks of a parallel decode can start another queued
833        // decode. The decoder only decodes one block at a time in parallel, for peers and RPCs
834        // together, and decodes the others serially, as they are without the parallel decoder.
835        // Each worker then has at most one serial decode in progress, and the pool has at most
836        // one block more than its threads. The decoder checks for another parallel decode inside
837        // this job, so a block that waits for a worker doesn't keep others from the parallel
838        // decoder.
839        //
840        // Since we use `block_in_place()`, other futures running on the connection task will be
841        // blocked: https://docs.rs/tokio/latest/tokio/task/fn.block_in_place.html
842        let wait_start = Instant::now();
843        tokio::task::block_in_place(|| {
844            rayon::in_place_scope_fifo(|s| {
845                s.spawn_fifo(|_s| {
846                    wait = wait_start.elapsed();
847                    result = Some(Block::zcash_deserialize_parallel(&mut unread))
848                })
849            })
850        });
851        metrics::histogram!("zebra.net.block.decode.wait_seconds").record(wait.as_secs_f64());
852        let block = result.expect("scope has already finished")?;
853
854        // The decoder reads from the message bytes, so tell the reader how far it got.
855        let read = body.len() - unread.len();
856        body_reader
857            .set_position(u64::try_from(read).expect("a message is smaller than 2^64 bytes"));
858
859        let message = Message::Block(block.into());
860        metrics::histogram!("zebra.net.block.decode.duration_seconds")
861            .record(decode_start.elapsed().as_secs_f64());
862        Ok(message)
863    }
864
865    fn read_getblocks<R: Read>(&self, mut reader: R) -> Result<Message, Error> {
866        if self.builder.version == Version(reader.read_u32::<LittleEndian>()?) {
867            let known_blocks = Vec::zcash_deserialize(&mut reader)?;
868            let stop_hash = block::Hash::zcash_deserialize(&mut reader)?;
869            let stop = if stop_hash != block::Hash([0; 32]) {
870                Some(stop_hash)
871            } else {
872                None
873            };
874            Ok(Message::GetBlocks { known_blocks, stop })
875        } else {
876            Err(Error::Parse("getblocks version did not match negotiation"))
877        }
878    }
879
880    /// Deserialize a `headers` message.
881    ///
882    /// See [Zcash block header] for the enumeration of these fields.
883    ///
884    /// [Zcash block header](https://zips.z.cash/protocol/protocol.pdf#page=84)
885    fn read_headers<R: Read>(&self, mut reader: R) -> Result<Message, Error> {
886        // CompactSizeMessage is bounded to MAX_PROTOCOL_MESSAGE_LEN on deserialization.
887        let count: CompactSizeMessage = (&mut reader).zcash_deserialize_into()?;
888        // Infallible: CompactSizeMessage wraps u32, which always fits in usize.
889        let count: usize = count.into();
890        if count > MAX_HEADERS_PER_MESSAGE {
891            return Err(Error::Parse(
892                "headers message exceeds the protocol limit of 160 entries",
893            ));
894        }
895        Ok(Message::Headers(zcash_deserialize_external_count(
896            count,
897            &mut reader,
898        )?))
899    }
900
901    fn read_getheaders<R: Read>(&self, mut reader: R) -> Result<Message, Error> {
902        if self.builder.version == Version(reader.read_u32::<LittleEndian>()?) {
903            let known_blocks = Vec::zcash_deserialize(&mut reader)?;
904            let stop_hash = block::Hash::zcash_deserialize(&mut reader)?;
905            let stop = if stop_hash != block::Hash([0; 32]) {
906                Some(stop_hash)
907            } else {
908                None
909            };
910            Ok(Message::GetHeaders { known_blocks, stop })
911        } else {
912            Err(Error::Parse("getblocks version did not match negotiation"))
913        }
914    }
915
916    fn read_inv<R: Read>(&self, reader: R) -> Result<Message, Error> {
917        Ok(Message::Inv(Vec::zcash_deserialize(reader)?))
918    }
919
920    fn read_getdata<R: Read>(&self, reader: R) -> Result<Message, Error> {
921        Ok(Message::GetData(Vec::zcash_deserialize(reader)?))
922    }
923
924    fn read_notfound<R: Read>(&self, reader: R) -> Result<Message, Error> {
925        Ok(Message::NotFound(Vec::zcash_deserialize(reader)?))
926    }
927
928    fn read_tx<R: Read + std::marker::Send>(&self, reader: R) -> Result<Message, Error> {
929        let result = Self::deserialize_spawning::<Transaction, _>(reader);
930        Ok(Message::Tx(Arc::new(result?).into()))
931    }
932
933    fn read_mempool<R: Read>(&self, mut _reader: R) -> Result<Message, Error> {
934        Ok(Message::Mempool)
935    }
936
937    fn read_filterload<R: Read>(&self, mut reader: R, body_len: usize) -> Result<Message, Error> {
938        // The maximum length of a filter.
939        const MAX_FILTERLOAD_FILTER_LENGTH: usize = 36000;
940
941        // The data length of the fields:
942        // hash_functions_count + tweak + flags.
943        const FILTERLOAD_FIELDS_LENGTH: usize = 4 + 4 + 1;
944
945        // The maximum length of a filter message's data.
946        const MAX_FILTERLOAD_MESSAGE_LENGTH: usize =
947            MAX_FILTERLOAD_FILTER_LENGTH + FILTERLOAD_FIELDS_LENGTH;
948
949        if !(FILTERLOAD_FIELDS_LENGTH..=MAX_FILTERLOAD_MESSAGE_LENGTH).contains(&body_len) {
950            return Err(Error::Parse("Invalid filterload message body length."));
951        }
952
953        // Memory Denial of Service: we just checked the untrusted parsed length
954        let filter_length: usize = body_len - FILTERLOAD_FIELDS_LENGTH;
955        let filter_bytes = zcash_deserialize_bytes_external_count(filter_length, &mut reader)?;
956
957        Ok(Message::FilterLoad {
958            filter: Filter(filter_bytes),
959            hash_functions_count: reader.read_u32::<LittleEndian>()?,
960            tweak: Tweak(reader.read_u32::<LittleEndian>()?),
961            flags: reader.read_u8()?,
962        })
963    }
964
965    fn read_filteradd<R: Read>(&self, mut reader: R, body_len: usize) -> Result<Message, Error> {
966        const MAX_FILTERADD_LENGTH: usize = 520;
967
968        // Memory Denial of Service: limit the untrusted parsed length
969        let filter_length: usize = min(body_len, MAX_FILTERADD_LENGTH);
970        let filter_bytes = zcash_deserialize_bytes_external_count(filter_length, &mut reader)?;
971
972        Ok(Message::FilterAdd { data: filter_bytes })
973    }
974
975    fn read_filterclear<R: Read>(&self, mut _reader: R) -> Result<Message, Error> {
976        Ok(Message::FilterClear)
977    }
978
979    /// Deserializes transaction-bearing messages on the existing blocking Rayon path.
980    #[allow(clippy::unwrap_in_result)]
981    fn deserialize_spawning<T: ZcashDeserialize + Send, R: Read + Send>(
982        reader: R,
983    ) -> Result<T, Error> {
984        let mut result = None;
985
986        // Correctness: Do CPU-intensive work on a dedicated thread, to avoid blocking other futures.
987        //
988        // Since we use `block_in_place()`, other futures running on the connection task will be blocked:
989        // https://docs.rs/tokio/latest/tokio/task/fn.block_in_place.html
990        //
991        // We can't use `spawn_blocking()` because:
992        // - The `reader` has a lifetime (but we could replace it with a `Vec` of message data)
993        // - There is no way to check the blocking task's future for panics
994        tokio::task::block_in_place(|| {
995            rayon::in_place_scope_fifo(|s| {
996                s.spawn_fifo(|_s| result = Some(T::zcash_deserialize(reader)))
997            })
998        });
999
1000        result.expect("scope has already finished")
1001    }
1002}