use std::{
borrow::Borrow,
io,
sync::{
atomic::{AtomicBool, AtomicUsize, Ordering},
Arc,
},
};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use chrono::{TimeZone, Utc};
use hex::{FromHex, FromHexError};
use rayon::prelude::*;
use zcash_primitives::transaction::TxVersion;
use crate::{
block::{header::ZCASH_BLOCK_VERSION, merkle, Block, CountedHeader, Hash, Header},
serialization::{
CompactSizeMessage, ReadZcashExt, SerializationError, TrustedPreallocate, ZcashDeserialize,
ZcashDeserializeInto, ZcashSerialize,
},
transaction::{Transaction, MIN_TRANSPARENT_TX_SIZE},
work::{difficulty::CompactDifficulty, equihash},
};
pub const MAX_BLOCK_BYTES: u64 = 2_000_000;
fn check_version(version: u32) -> Result<(), &'static str> {
match version {
version if version >> 31 != 0 => Err("high bit was set in version field"),
version if version < ZCASH_BLOCK_VERSION => Err("version must be at least 4"),
_ => Ok(()),
}
}
impl ZcashSerialize for Header {
#[allow(clippy::unwrap_in_result)]
fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
check_version(self.version).map_err(io::Error::other)?;
writer.write_u32::<LittleEndian>(self.version)?;
self.previous_block_hash.zcash_serialize(&mut writer)?;
writer.write_all(&self.merkle_root.0[..])?;
writer.write_all(&self.commitment_bytes[..])?;
writer.write_u32::<LittleEndian>(
self.time
.timestamp()
.try_into()
.expect("deserialized and generated timestamps are u32 values"),
)?;
writer.write_u32::<LittleEndian>(self.difficulty_threshold.0)?;
writer.write_all(&self.nonce[..])?;
self.solution.zcash_serialize(&mut writer)?;
Ok(())
}
}
impl ZcashDeserialize for Header {
fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
let version = reader.read_u32::<LittleEndian>()?;
check_version(version).map_err(SerializationError::Parse)?;
Ok(Header {
version,
previous_block_hash: Hash::zcash_deserialize(&mut reader)?,
merkle_root: merkle::Root(reader.read_32_bytes()?),
commitment_bytes: reader.read_32_bytes()?.into(),
time: Utc
.timestamp_opt(reader.read_u32::<LittleEndian>()?.into(), 0)
.single()
.ok_or(SerializationError::Parse(
"out-of-range number of seconds and/or invalid nanosecond",
))?,
difficulty_threshold: CompactDifficulty(reader.read_u32::<LittleEndian>()?),
nonce: reader.read_32_bytes()?.into(),
solution: equihash::Solution::zcash_deserialize(reader)?,
})
}
}
impl ZcashSerialize for CountedHeader {
#[allow(clippy::unwrap_in_result)]
fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
self.header.zcash_serialize(&mut writer)?;
let transaction_count =
CompactSizeMessage::try_from(0).expect("0 is below the message size limit");
transaction_count.zcash_serialize(&mut writer)?;
Ok(())
}
}
impl ZcashDeserialize for CountedHeader {
fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
let header = CountedHeader {
header: (&mut reader).zcash_deserialize_into()?,
};
let _transaction_count: CompactSizeMessage = (&mut reader).zcash_deserialize_into()?;
Ok(header)
}
}
impl ZcashSerialize for Block {
fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
self.header.zcash_serialize(&mut writer)?;
self.transactions.zcash_serialize(&mut writer)?;
Ok(())
}
}
impl ZcashDeserialize for Block {
fn zcash_deserialize<R: io::Read>(reader: R) -> Result<Self, SerializationError> {
let limited_reader = &mut reader.take(MAX_BLOCK_BYTES);
Ok(Block {
header: limited_reader.zcash_deserialize_into()?,
transactions: zcash_deserialize_block_transactions(limited_reader)?,
})
}
}
fn zcash_deserialize_block_transactions<R: io::Read>(
reader: &mut io::Take<R>,
) -> Result<Vec<Arc<Transaction>>, SerializationError> {
let count: CompactSizeMessage = (&mut *reader).zcash_deserialize_into()?;
let count = u64::try_from(usize::from(count))
.map_err(|_| SerializationError::Parse("transaction count doesn't fit in a u64"))?;
if count > Transaction::max_allocation() {
return Err(SerializationError::Parse(
"Vector longer than max_allocation",
));
}
let start = reader.limit();
let mut transactions = Vec::new();
for parsed in 1..=count {
transactions.push((&mut *reader).zcash_deserialize_into()?);
check_transactions_size(parsed, start - reader.limit())?;
}
Ok(transactions)
}
fn check_transactions_size(parsed: u64, bytes: u64) -> Result<(), SerializationError> {
if bytes < parsed * MIN_TRANSPARENT_TX_SIZE {
return Err(SerializationError::Parse(
"block transactions are smaller than the smallest valid transaction",
));
}
Ok(())
}
pub(super) static PARALLEL_DECODE: AtomicBool = AtomicBool::new(false);
pub(super) struct ParallelDecode<'a>(&'a AtomicBool);
impl<'a> ParallelDecode<'a> {
pub(super) fn try_start(decoding: &'a AtomicBool) -> Option<Self> {
decoding
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.ok()
.map(|_| Self(decoding))
}
}
impl Drop for ParallelDecode<'_> {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
impl Block {
pub fn zcash_deserialize_parallel(bytes: &mut &[u8]) -> Result<Self, SerializationError> {
let decoded =
ParallelDecode::try_start(&PARALLEL_DECODE).and_then(|_decoding| parallel_block(bytes));
if let Some((block, consumed)) = decoded {
*bytes = &bytes[consumed..];
block
} else {
Self::zcash_deserialize(bytes)
}
}
}
pub(super) const PARALLEL_DECODE_TASK_BYTES: usize = 32 * 1024;
pub(super) const PARALLEL_DECODE_BATCH_BYTES: usize = 64 * 1024;
const PARALLEL_DECODE_THRESHOLD: usize = 64;
pub(super) fn serial_decode_prefix_is_complete(transactions: usize, bytes: usize) -> bool {
transactions >= PARALLEL_DECODE_THRESHOLD || bytes >= PARALLEL_DECODE_BATCH_BYTES
}
fn check_accepted_size(transactions: usize, bytes: usize) -> Result<(), SerializationError> {
check_transactions_size(u64::try_from(transactions)?, u64::try_from(bytes)?)
}
pub(super) fn parallel_block(bytes: &[u8]) -> Option<(Result<Block, SerializationError>, usize)> {
let limit = usize::try_from(MAX_BLOCK_BYTES).expect("block limit fits in usize");
let bounded = &bytes[..bytes.len().min(limit)];
let mut remaining = bounded.get(equihash::Solution::INPUT_LENGTH + 32..)?;
scan_fixed_vector(&mut remaining, 1)?;
let count = scan_count(&mut remaining)?;
if count < PARALLEL_DECODE_THRESHOLD
|| u64::try_from(count).ok()? > Transaction::max_allocation()
{
return None;
}
let header = bounded.zcash_deserialize_into().ok()?;
let body_start = bounded.len() - remaining.len();
let mut consumed = body_start;
let block = (|| {
let mut transactions = Vec::new();
let mut ranges = Vec::new();
let mut parsed = Vec::new();
let mut serial = false;
while transactions.len() < count {
if serial
|| !serial_decode_prefix_is_complete(transactions.len(), consumed - body_start)
{
let mut reader = &bounded[consumed..];
let transaction = Transaction::zcash_deserialize(&mut reader);
consumed = bounded.len() - reader.len();
transactions.push(Arc::new(transaction?));
check_accepted_size(transactions.len(), consumed - body_start)?;
continue;
}
let start = consumed;
let budget_end = bounded.len().min(start + (consumed - body_start));
scan_batch(
&bounded[start..budget_end],
(count - transactions.len()).min(transactions.len()),
&mut ranges,
);
let Some(last) = ranges.last() else {
let mut reader = &bounded[consumed..];
let transaction = Transaction::zcash_deserialize(&mut reader);
consumed = bounded.len() - reader.len();
transactions.push(Arc::new(transaction?));
check_accepted_size(transactions.len(), consumed - body_start)?;
continue;
};
let task_len = PARALLEL_DECODE_TASK_BYTES
.saturating_mul(ranges.len())
.div_ceil(last.end)
.max(1);
let first_miss = AtomicUsize::new(usize::MAX);
ranges
.par_iter()
.enumerate()
.with_min_len(task_len)
.map(|(index, range)| {
if index > first_miss.load(Ordering::Relaxed) {
return None;
}
let mut reader = &bounded[start + range.start..start + range.end];
let transaction = Transaction::zcash_deserialize(&mut reader)
.ok()
.filter(|_| reader.is_empty());
if transaction.is_none() {
first_miss.fetch_min(index, Ordering::Relaxed);
}
Some(transaction.map(Arc::new))
})
.collect_into_vec(&mut parsed);
for (result, range) in parsed.drain(..).zip(&ranges) {
let transaction = result.expect(
"only transactions after a miss are skipped, and the loop stops at misses",
);
let Some(transaction) = transaction else {
serial = true;
break;
};
consumed = start + range.end;
transactions.push(transaction);
check_accepted_size(transactions.len(), consumed - body_start)?;
}
}
Ok(Block {
header,
transactions,
})
})();
Some((block, consumed))
}
pub(super) fn scan_batch(bytes: &[u8], count: usize, ranges: &mut Vec<std::ops::Range<usize>>) {
ranges.clear();
let mut remaining = bytes;
while ranges.len() < count {
let start = bytes.len() - remaining.len();
if scan_transaction(&mut remaining).is_none() {
break;
}
ranges.push(start..bytes.len() - remaining.len());
}
}
fn skip(bytes: &mut &[u8], count: usize) -> Option<()> {
*bytes = bytes.get(count..)?;
Some(())
}
fn scan_count(bytes: &mut &[u8]) -> Option<usize> {
CompactSizeMessage::zcash_deserialize(bytes)
.ok()
.map(usize::from)
}
fn scan_fixed_vector(bytes: &mut &[u8], item_size: usize) -> Option<usize> {
let count = scan_count(bytes)?;
skip(bytes, count.checked_mul(item_size)?)?;
Some(count)
}
pub(super) fn scan_transaction(bytes: &mut &[u8]) -> Option<()> {
let version = TxVersion::read(&mut *bytes).ok()?;
if version.has_orchard() {
skip(bytes, 12)?;
}
for _ in 0..scan_count(bytes)? {
skip(bytes, 36)?; let script_len = scan_count(bytes)?;
skip(bytes, script_len)?;
skip(bytes, 4)?; }
for _ in 0..scan_count(bytes)? {
skip(bytes, 8)?; let script_len = scan_count(bytes)?;
skip(bytes, script_len)?;
}
if !version.has_orchard() {
skip(bytes, 4)?; if version.has_overwinter() {
skip(bytes, 4)?; }
let mut has_sapling = false;
if version.has_sapling() {
skip(bytes, 8)?; let spends = scan_fixed_vector(bytes, 384)?;
let outputs = scan_fixed_vector(bytes, 948)?;
has_sapling = spends != 0 || outputs != 0;
}
if version.has_sprout() {
let size = if version.has_sapling() { 1698 } else { 1802 };
if scan_fixed_vector(bytes, size)? != 0 {
skip(bytes, 96)?; }
}
if has_sapling {
skip(bytes, 64)?; }
} else {
let spends = scan_fixed_vector(bytes, 96)?;
let outputs = scan_fixed_vector(bytes, 756)?;
if spends != 0 || outputs != 0 {
skip(bytes, 8)?; if spends != 0 {
skip(bytes, 32)?; }
skip(bytes, spends.checked_mul(192 + 64)?)?;
skip(bytes, outputs.checked_mul(192)?)?;
skip(bytes, 64)?; }
for _ in 0..if version.has_ironwood() { 2 } else { 1 } {
let actions = scan_fixed_vector(bytes, 820)?;
if actions != 0 {
skip(bytes, 1 + 8 + 32)?; let proof_len = scan_count(bytes)?;
skip(bytes, proof_len)?;
skip(bytes, actions.checked_mul(64)?)?;
skip(bytes, 64)?; }
}
}
Some(())
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct SerializedBlock {
bytes: Vec<u8>,
}
impl<B: Borrow<Block>> From<B> for SerializedBlock {
fn from(block: B) -> Self {
SerializedBlock {
bytes: block
.borrow()
.zcash_serialize_to_vec()
.expect("Writing to a `Vec` should never fail"),
}
}
}
impl AsRef<[u8]> for SerializedBlock {
fn as_ref(&self) -> &[u8] {
self.bytes.as_ref()
}
}
impl From<Vec<u8>> for SerializedBlock {
fn from(bytes: Vec<u8>) -> Self {
Self { bytes }
}
}
impl FromHex for SerializedBlock {
type Error = FromHexError;
fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
let bytes = Vec::from_hex(hex)?;
Ok(SerializedBlock { bytes })
}
}