Skip to main content

zebra_chain/serialization/
zcash_deserialize.rs

1//! Converting bytes into Zcash consensus-critical data structures.
2
3use std::{io, io::Read, net::Ipv6Addr, sync::Arc};
4
5use super::{AtLeastOne, CompactSizeMessage, SerializationError, MAX_PROTOCOL_MESSAGE_LEN};
6
7/// Initial-allocation cap for `zcash_deserialize_external_count` and the bytes
8/// path, `zcash_deserialize_bytes_external_count`.
9///
10/// 1024 is large enough that honest messages amortize their growth to a few
11/// reallocations.
12pub(crate) const MAX_INITIAL_ALLOCATION: usize = 1024;
13
14/// Consensus-critical deserialization for Zcash.
15///
16/// This trait provides a generic deserialization for consensus-critical
17/// formats, such as network messages, transactions, blocks, etc.
18///
19/// It is intended for use only for consensus-critical formats.
20/// Internal deserialization can freely use `serde`, or any other format.
21pub trait ZcashDeserialize: Sized {
22    /// Try to read `self` from the given `reader`.
23    ///
24    /// This function has a `zcash_` prefix to alert the reader that the
25    /// serialization in use is consensus-critical serialization, rather than
26    /// some other kind of serialization.
27    fn zcash_deserialize<R: io::Read>(reader: R) -> Result<Self, SerializationError>;
28}
29
30/// Deserialize a `Vec`, where the number of items is set by a CompactSize
31/// prefix in the data. This is the most common format in Zcash.
32///
33/// See `zcash_deserialize_external_count` for more details, and usage
34/// information.
35impl<T: ZcashDeserialize + TrustedPreallocate> ZcashDeserialize for Vec<T> {
36    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
37        let len: CompactSizeMessage = (&mut reader).zcash_deserialize_into()?;
38        zcash_deserialize_external_count(len.into(), reader)
39    }
40}
41
42/// Deserialize an `AtLeastOne` vector, where the number of items is set by a
43/// CompactSize prefix in the data. This is the most common format in Zcash.
44impl<T: ZcashDeserialize + TrustedPreallocate> ZcashDeserialize for AtLeastOne<T> {
45    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
46        let v: Vec<T> = (&mut reader).zcash_deserialize_into()?;
47        let at_least_one: AtLeastOne<T> = v.try_into()?;
48        Ok(at_least_one)
49    }
50}
51
52/// Implement ZcashDeserialize for `Vec<u8>` directly instead of using the blanket Vec implementation
53///
54/// This allows us to optimize the inner loop into a single call to `read_exact()`
55/// Note that we don't implement TrustedPreallocate for u8.
56/// This allows the optimization without relying on specialization.
57impl ZcashDeserialize for Vec<u8> {
58    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
59        let len: CompactSizeMessage = (&mut reader).zcash_deserialize_into()?;
60        zcash_deserialize_bytes_external_count(len.into(), reader)
61    }
62}
63
64/// Deserialize a `Vec` containing `external_count` items.
65///
66/// In Zcash, most arrays are stored as a CompactSize, followed by that number
67/// of items of type `T`. But in `Transaction::V5`, some types are serialized as
68/// multiple arrays in different locations, with a single CompactSize before the
69/// first array.
70///
71/// ## Usage
72///
73/// Use `zcash_deserialize_external_count` when the array count is determined by
74/// other data, or a consensus rule.
75///
76/// Use `Vec::zcash_deserialize` for data that contains CompactSize count,
77/// followed by the data array.
78///
79/// For example, when a single count applies to multiple arrays:
80/// 1. Use `Vec::zcash_deserialize` for the array that has a data count.
81/// 2. Use `zcash_deserialize_external_count` for the arrays with no count in the
82///    data, passing the length of the first array.
83///
84/// This function has a `zcash_` prefix to alert the reader that the
85/// serialization in use is consensus-critical serialization, rather than
86/// some other kind of serialization.
87pub fn zcash_deserialize_external_count<R: io::Read, T: ZcashDeserialize + TrustedPreallocate>(
88    external_count: usize,
89    mut reader: R,
90) -> Result<Vec<T>, SerializationError> {
91    match u64::try_from(external_count) {
92        Ok(external_count) if external_count > T::max_allocation() => {
93            return Err(SerializationError::Parse(
94                "Vector longer than max_allocation",
95            ))
96        }
97        Ok(_) => {}
98        // As of 2021, usize is less than or equal to 64 bits on all (or almost all?) supported Rust platforms.
99        // So in practice this error is impossible. (But the check is required, because Rust is future-proof
100        // for 128 bit memory spaces.)
101        Err(_) => return Err(SerializationError::Parse("Vector longer than u64::MAX")),
102    }
103    // Cap the upfront reservation. The Vec grows via push() as elements
104    // arrive, so a peer-supplied `external_count` can't force a large
105    // allocation before any data is read. Fixes the deserializer-level
106    // case of GHSA-xr93-pcq3-pxf8.
107    let mut vec = Vec::with_capacity(external_count.min(MAX_INITIAL_ALLOCATION));
108    for _ in 0..external_count {
109        vec.push(T::zcash_deserialize(&mut reader)?);
110    }
111    Ok(vec)
112}
113
114/// `zcash_deserialize_external_count`, specialised for raw bytes.
115///
116/// Reads the bytes in bulk instead of one element at a time, while bounding the
117/// upfront allocation against the peer-supplied `external_count`.
118///
119/// This function has a `zcash_` prefix to alert the reader that the
120/// serialization in use is consensus-critical serialization, rather than
121/// some other kind of serialization.
122pub fn zcash_deserialize_bytes_external_count<R: io::Read>(
123    external_count: usize,
124    reader: R,
125) -> Result<Vec<u8>, SerializationError> {
126    if external_count > MAX_U8_ALLOCATION {
127        return Err(SerializationError::Parse(
128            "Byte vector longer than MAX_U8_ALLOCATION",
129        ));
130    }
131    // `external_count` is peer-supplied, so grow the buffer as bytes arrive instead of reserving it all.
132    let mut vec = Vec::with_capacity(external_count.min(MAX_INITIAL_ALLOCATION));
133    let count = reader.take(external_count as u64).read_to_end(&mut vec)?;
134    if count != external_count {
135        return Err(io::Error::new(
136            io::ErrorKind::UnexpectedEof,
137            "reader ended before external_count bytes were read",
138        )
139        .into());
140    }
141    // `read_to_end` grows by doubling, so drop the excess capacity on large fields.
142    vec.shrink_to_fit();
143    Ok(vec)
144}
145
146/// `zcash_deserialize_external_count`, specialised for [`String`].
147/// The external count is in bytes. (Not UTF-8 characters.)
148///
149/// This allows us to optimize the inner loop into a single call to `read_exact()`.
150///
151/// This function has a `zcash_` prefix to alert the reader that the
152/// serialization in use is consensus-critical serialization, rather than
153/// some other kind of serialization.
154pub fn zcash_deserialize_string_external_count<R: io::Read>(
155    external_byte_count: usize,
156    reader: R,
157) -> Result<String, SerializationError> {
158    let bytes = zcash_deserialize_bytes_external_count(external_byte_count, reader)?;
159
160    String::from_utf8(bytes).map_err(|_| SerializationError::Parse("invalid utf-8"))
161}
162
163/// Read a Bitcoin-encoded UTF-8 string.
164impl ZcashDeserialize for String {
165    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
166        let byte_count: CompactSizeMessage = (&mut reader).zcash_deserialize_into()?;
167        zcash_deserialize_string_external_count(byte_count.into(), reader)
168    }
169}
170
171// We don't impl ZcashDeserialize for Ipv4Addr or SocketAddrs,
172// because the IPv4 and port formats are different in addr (v1) and addrv2 messages.
173
174/// Read a Bitcoin-encoded IPv6 address.
175impl ZcashDeserialize for Ipv6Addr {
176    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
177        let mut ipv6_addr = [0u8; 16];
178        reader.read_exact(&mut ipv6_addr)?;
179
180        Ok(Ipv6Addr::from(ipv6_addr))
181    }
182}
183
184/// Consensus-critical deserialization with additional context.
185///
186/// Some types (e.g., `Transaction`, `Block`) require external context for
187/// deserialization that is not present in the byte stream itself. For example,
188/// `zcash_primitives::transaction::Transaction::read()` requires a `BranchId`
189/// which, for pre-V5 transactions, must be derived from the block height and
190/// network.
191///
192/// This trait extends `ZcashDeserialize` for types that need context without
193/// changing the signature of the context-free trait.
194pub trait ZcashDeserializeWithContext<C>: Sized {
195    /// Try to read `self` from the given `reader`, using the provided `context`.
196    fn zcash_deserialize_with_context<R: io::Read>(
197        reader: R,
198        context: &C,
199    ) -> Result<Self, SerializationError>;
200}
201
202/// Helper for deserializing more succinctly via type inference
203pub trait ZcashDeserializeInto {
204    /// Deserialize based on type inference
205    fn zcash_deserialize_into<T>(self) -> Result<T, SerializationError>
206    where
207        T: ZcashDeserialize;
208}
209
210impl<R: io::Read> ZcashDeserializeInto for R {
211    fn zcash_deserialize_into<T>(self) -> Result<T, SerializationError>
212    where
213        T: ZcashDeserialize,
214    {
215        T::zcash_deserialize(self)
216    }
217}
218
219/// Blind preallocation of a `Vec<T: TrustedPreallocate>` is based on a bounded length. This is in contrast
220/// to blind preallocation of a generic `Vec<T>`, which is a DOS vector.
221///
222/// The max_allocation() function provides a loose upper bound on the size of the `Vec<T: TrustedPreallocate>`
223/// which can possibly be received from an honest peer. If this limit is too low, Zebra may reject valid messages.
224/// In the worst case, setting the lower bound too low could cause Zebra to fall out of consensus by rejecting all messages containing a valid block.
225pub trait TrustedPreallocate {
226    /// Provides a ***loose upper bound*** on the size of the `Vec<T: TrustedPreallocate>`
227    /// which can possibly be received from an honest peer.
228    fn max_allocation() -> u64;
229}
230
231impl<T> TrustedPreallocate for Arc<T>
232where
233    T: TrustedPreallocate,
234{
235    fn max_allocation() -> u64 {
236        T::max_allocation()
237    }
238}
239
240/// The length of the longest valid `Vec<u8>` that can be received over the network
241///
242/// It takes 5 bytes to encode a CompactSize representing any number netween 2^16 and (2^32 - 1)
243/// MAX_PROTOCOL_MESSAGE_LEN is ~2^21, so the largest `Vec<u8>` that can be received from an honest peer is
244/// (MAX_PROTOCOL_MESSAGE_LEN - 5);
245pub(crate) const MAX_U8_ALLOCATION: usize = MAX_PROTOCOL_MESSAGE_LEN - 5;