Skip to main content

zebra_chain/block/
serialize.rs

1//! Serialization and deserialization for Zcash blocks.
2
3use std::{borrow::Borrow, io, sync::Arc};
4
5use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
6use chrono::{TimeZone, Utc};
7use hex::{FromHex, FromHexError};
8
9use crate::{
10    block::{header::ZCASH_BLOCK_VERSION, merkle, Block, CountedHeader, Hash, Header},
11    serialization::{
12        CompactSizeMessage, ReadZcashExt, SerializationError, TrustedPreallocate, ZcashDeserialize,
13        ZcashDeserializeInto, ZcashSerialize,
14    },
15    transaction::{Transaction, MIN_TRANSPARENT_TX_SIZE},
16    work::{difficulty::CompactDifficulty, equihash},
17};
18
19/// The maximum size of a Zcash block, in bytes.
20///
21/// Post-Sapling, this is also the maximum size of a transaction
22/// in the Zcash specification. (But since blocks also contain a
23/// block header and transaction count, the maximum size of a
24/// transaction in the chain is approximately 1.5 kB smaller.)
25pub const MAX_BLOCK_BYTES: u64 = 2_000_000;
26
27/// Checks if a block header version is valid.
28///
29/// Zebra could encounter a [`Header`] with an invalid version when serializing a block header constructed
30/// in memory with the wrong version in tests or the getblocktemplate RPC.
31///
32/// The getblocktemplate RPC generates a template with version 4. The miner generates the actual block,
33/// and then we deserialize it and do this check.
34///
35/// All other blocks are deserialized when we receive them, and never modified,
36/// so the deserialisation would pick up any errors.
37fn check_version(version: u32) -> Result<(), &'static str> {
38    match version {
39        // The Zcash specification says that:
40        // "The current and only defined block version number for Zcash is 4."
41        // but this is not actually part of the consensus rules, and in fact
42        // broken mining software created blocks that do not have version 4.
43        // There are approximately 4,000 blocks with version 536870912; this
44        // is the bit-reversal of the value 4, indicating that mining pool
45        // reversed bit-ordering of the version field. Because the version field
46        // was not properly validated, these blocks were added to the chain.
47        //
48        // The only possible way to work around this is to do a similar hack
49        // as the overwintered field in transaction parsing, which we do here:
50        // treat the high bit (which zcashd interprets as a sign bit) as an
51        // indicator that the version field is meaningful.
52        version if version >> 31 != 0 => Err("high bit was set in version field"),
53
54        // # Consensus
55        //
56        // > The block version number MUST be greater than or equal to 4.
57        //
58        // https://zips.z.cash/protocol/protocol.pdf#blockheader
59        version if version < ZCASH_BLOCK_VERSION => Err("version must be at least 4"),
60
61        _ => Ok(()),
62    }
63}
64
65impl ZcashSerialize for Header {
66    #[allow(clippy::unwrap_in_result)]
67    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
68        check_version(self.version).map_err(io::Error::other)?;
69
70        writer.write_u32::<LittleEndian>(self.version)?;
71        self.previous_block_hash.zcash_serialize(&mut writer)?;
72        writer.write_all(&self.merkle_root.0[..])?;
73        writer.write_all(&self.commitment_bytes[..])?;
74        writer.write_u32::<LittleEndian>(
75            self.time
76                .timestamp()
77                .try_into()
78                .expect("deserialized and generated timestamps are u32 values"),
79        )?;
80        writer.write_u32::<LittleEndian>(self.difficulty_threshold.0)?;
81        writer.write_all(&self.nonce[..])?;
82        self.solution.zcash_serialize(&mut writer)?;
83        Ok(())
84    }
85}
86
87impl ZcashDeserialize for Header {
88    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
89        let version = reader.read_u32::<LittleEndian>()?;
90        check_version(version).map_err(SerializationError::Parse)?;
91
92        Ok(Header {
93            version,
94            previous_block_hash: Hash::zcash_deserialize(&mut reader)?,
95            merkle_root: merkle::Root(reader.read_32_bytes()?),
96            commitment_bytes: reader.read_32_bytes()?.into(),
97            // This can't panic, because all u32 values are valid `Utc.timestamp`s
98            time: Utc
99                .timestamp_opt(reader.read_u32::<LittleEndian>()?.into(), 0)
100                .single()
101                .ok_or(SerializationError::Parse(
102                    "out-of-range number of seconds and/or invalid nanosecond",
103                ))?,
104            difficulty_threshold: CompactDifficulty(reader.read_u32::<LittleEndian>()?),
105            nonce: reader.read_32_bytes()?.into(),
106            solution: equihash::Solution::zcash_deserialize(reader)?,
107        })
108    }
109}
110
111impl ZcashSerialize for CountedHeader {
112    #[allow(clippy::unwrap_in_result)]
113    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
114        self.header.zcash_serialize(&mut writer)?;
115
116        // A header-only message has zero transactions in it.
117        let transaction_count =
118            CompactSizeMessage::try_from(0).expect("0 is below the message size limit");
119        transaction_count.zcash_serialize(&mut writer)?;
120
121        Ok(())
122    }
123}
124
125impl ZcashDeserialize for CountedHeader {
126    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
127        let header = CountedHeader {
128            header: (&mut reader).zcash_deserialize_into()?,
129        };
130
131        // We ignore the number of transactions in a header-only message,
132        // it should always be zero.
133        let _transaction_count: CompactSizeMessage = (&mut reader).zcash_deserialize_into()?;
134
135        Ok(header)
136    }
137}
138
139impl ZcashSerialize for Block {
140    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
141        // All block structs are validated when they are parsed.
142        // So we don't need to check MAX_BLOCK_BYTES here, until
143        // we start generating our own blocks (see #483).
144        self.header.zcash_serialize(&mut writer)?;
145        self.transactions.zcash_serialize(&mut writer)?;
146        Ok(())
147    }
148}
149
150impl ZcashDeserialize for Block {
151    fn zcash_deserialize<R: io::Read>(reader: R) -> Result<Self, SerializationError> {
152        // # Consensus
153        //
154        // > The size of a block MUST be less than or equal to 2000000 bytes.
155        //
156        // https://zips.z.cash/protocol/protocol.pdf#blockheader
157        //
158        // If the limit is reached, we'll get an UnexpectedEof error
159        let limited_reader = &mut reader.take(MAX_BLOCK_BYTES);
160        Ok(Block {
161            header: limited_reader.zcash_deserialize_into()?,
162            // Note: transactions are parsed with a default `BranchId::Canopy` for V1-V4.
163            // The stored `consensus_branch_id` may be wrong for pre-Canopy transactions.
164            // This field is not used in production (sighash computation provides the
165            // correct branch ID explicitly via the NetworkUpgrade parameter).
166            transactions: zcash_deserialize_block_transactions(limited_reader)?,
167        })
168    }
169}
170
171/// Deserializes a block's transactions, rejecting them once they average fewer than
172/// [`MIN_TRANSPARENT_TX_SIZE`] bytes, so a small message can't parse into many transactions.
173fn zcash_deserialize_block_transactions<R: io::Read>(
174    reader: &mut io::Take<R>,
175) -> Result<Vec<Arc<Transaction>>, SerializationError> {
176    let count: CompactSizeMessage = (&mut *reader).zcash_deserialize_into()?;
177    let count = u64::try_from(usize::from(count))
178        .map_err(|_| SerializationError::Parse("transaction count doesn't fit in a u64"))?;
179    if count > Transaction::max_allocation() {
180        return Err(SerializationError::Parse(
181            "Vector longer than max_allocation",
182        ));
183    }
184
185    let start = reader.limit();
186    let mut transactions = Vec::new();
187    for parsed in 1..=count {
188        transactions.push((&mut *reader).zcash_deserialize_into()?);
189
190        if start - reader.limit() < parsed * MIN_TRANSPARENT_TX_SIZE {
191            return Err(SerializationError::Parse(
192                "block transactions are smaller than the smallest valid transaction",
193            ));
194        }
195    }
196
197    Ok(transactions)
198}
199
200/// A serialized block.
201///
202/// Stores bytes that are guaranteed to be deserializable into a [`Block`].
203#[derive(Clone, Debug, Eq, Hash, PartialEq)]
204pub struct SerializedBlock {
205    bytes: Vec<u8>,
206}
207
208/// Build a [`SerializedBlock`] by serializing a block.
209impl<B: Borrow<Block>> From<B> for SerializedBlock {
210    fn from(block: B) -> Self {
211        SerializedBlock {
212            bytes: block
213                .borrow()
214                .zcash_serialize_to_vec()
215                .expect("Writing to a `Vec` should never fail"),
216        }
217    }
218}
219
220/// Access the serialized bytes of a [`SerializedBlock`].
221impl AsRef<[u8]> for SerializedBlock {
222    fn as_ref(&self) -> &[u8] {
223        self.bytes.as_ref()
224    }
225}
226
227impl From<Vec<u8>> for SerializedBlock {
228    fn from(bytes: Vec<u8>) -> Self {
229        Self { bytes }
230    }
231}
232
233impl FromHex for SerializedBlock {
234    type Error = FromHexError;
235
236    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
237        let bytes = Vec::from_hex(hex)?;
238        Ok(SerializedBlock { bytes })
239    }
240}