zebra_chain/block/
serialize.rs1use 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
19pub const MAX_BLOCK_BYTES: u64 = 2_000_000;
26
27fn check_version(version: u32) -> Result<(), &'static str> {
38 match version {
39 version if version >> 31 != 0 => Err("high bit was set in version field"),
53
54 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 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 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 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 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 let limited_reader = &mut reader.take(MAX_BLOCK_BYTES);
160 Ok(Block {
161 header: limited_reader.zcash_deserialize_into()?,
162 transactions: zcash_deserialize_block_transactions(limited_reader)?,
167 })
168 }
169}
170
171fn 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#[derive(Clone, Debug, Eq, Hash, PartialEq)]
204pub struct SerializedBlock {
205 bytes: Vec<u8>,
206}
207
208impl<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
220impl 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}