1use std::{
9 collections::{hash_map::Entry, HashMap, HashSet},
10 fmt,
11 hash::Hasher,
12 io::{self, Read, Write},
13 sync::Arc,
14};
15
16use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
17use sha2::{Digest, Sha256};
18use siphasher::sip::SipHasher24;
19use zebra_chain::{
20 block::{self, Block, MAX_BLOCK_BYTES},
21 serialization::{
22 CompactSizeMessage, FakeWriter, SerializationError, TrustedPreallocate, ZcashDeserialize,
23 ZcashSerialize, MAX_PROTOCOL_MESSAGE_LEN,
24 },
25 transaction::{Transaction, UnminedTx, UnminedTxId, MIN_TRANSPARENT_TX_SIZE},
26};
27
28#[cfg(test)]
29pub(crate) mod tests;
30
31#[derive(Clone, Debug, Eq, PartialEq)]
33pub struct CompactBlock {
34 pub header: Arc<block::Header>,
36 pub nonce: u64,
38 pub short_ids: Vec<[u8; 6]>,
40 pub prefilled: Vec<(usize, Arc<Transaction>)>,
42}
43
44#[derive(Clone, Debug, Eq, PartialEq)]
46pub struct BlockTransactionsRequest {
47 pub block_hash: block::Hash,
49 pub indexes: Vec<usize>,
51}
52
53#[derive(Clone, Debug, Eq, PartialEq)]
55pub struct BlockTransactions {
56 pub block_hash: block::Hash,
58 pub transactions: Vec<Arc<Transaction>>,
60}
61
62#[derive(Clone, Copy, Debug, Eq, PartialEq)]
64pub(crate) struct ExpectedBlockTransactions {
65 pub(crate) block_hash: block::Hash,
67
68 pub(crate) count: usize,
70
71 pub(crate) deadline: tokio::time::Instant,
73}
74
75impl ExpectedBlockTransactions {
76 pub(crate) fn matches(&self, mut body: &[u8]) -> bool {
81 tokio::time::Instant::now() < self.deadline
82 && block::Hash::zcash_deserialize(&mut body).ok() == Some(self.block_hash)
83 && CompactSizeMessage::zcash_deserialize(&mut body)
84 .ok()
85 .map(usize::from)
86 == Some(self.count)
87 }
88}
89
90pub struct Reconstruction {
92 compact: Arc<CompactBlock>,
93 transactions: Vec<Option<Arc<Transaction>>>,
94}
95
96impl fmt::Debug for Reconstruction {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 f.debug_struct("Reconstruction")
101 .field("transactions", &self.transactions.len())
102 .field("missing", &self.missing_count())
103 .finish()
104 }
105}
106
107impl CompactBlock {
108 pub fn from_block(block: &Block, nonce: u64) -> Result<Self, SerializationError> {
114 check_count(block.transactions.len())?;
115 let mut block_bytes = FakeWriter(0);
116 block.zcash_serialize(&mut block_bytes)?;
117 check_bytes(block_bytes.0)?;
118 let coinbase = block
119 .transactions
120 .first()
121 .filter(|tx| tx.is_coinbase())
122 .ok_or(SerializationError::Parse("compact block requires coinbase"))?;
123 let mut compact = Self {
124 header: block.header.clone(),
125 nonce,
126 short_ids: Vec::with_capacity(block.transactions.len() - 1),
127 prefilled: vec![(0, coinbase.clone())],
128 };
129 let keys = compact.keys();
130 compact.short_ids.extend(
131 block
132 .transactions
133 .iter()
134 .skip(1)
135 .map(|tx| short_id(keys, tx.as_ref().into())),
136 );
137 compact.validate()?;
138 Ok(compact)
139 }
140
141 pub fn validate(&self) -> Result<(), SerializationError> {
143 let count = self
144 .short_ids
145 .len()
146 .checked_add(self.prefilled.len())
147 .ok_or(SerializationError::Parse(
148 "compact transaction count overflow",
149 ))?;
150 check_count(count)?;
151 if !self
152 .prefilled
153 .first()
154 .is_some_and(|(index, tx)| *index == 0 && tx.is_coinbase())
155 {
156 return Err(SerializationError::Parse(
157 "compact block requires prefilled coinbase at zero",
158 ));
159 }
160 let mut next = 0;
161 let mut bytes = self.header.zcash_serialized_size()
162 + CompactSizeMessage::try_from(count)?.zcash_serialized_size()
163 + self.short_ids.len() * usize::try_from(MIN_TRANSPARENT_TX_SIZE)?;
164 for (index, tx) in &self.prefilled {
165 if *index < next || *index >= count || (*index != 0 && tx.is_coinbase()) {
166 return Err(SerializationError::Parse(
167 "invalid compact prefilled index or coinbase",
168 ));
169 }
170 next = index + 1;
171 bytes = add_bytes(bytes, tx.zcash_serialized_size())?;
172 }
173 check_bytes(bytes)
174 }
175
176 pub fn block_hash(&self) -> block::Hash {
178 self.header.hash()
179 }
180
181 pub fn matching_ids(&self, ids: impl IntoIterator<Item = UnminedTxId>) -> HashSet<UnminedTxId> {
184 let keys = self.keys();
185 self.matching_short_ids(ids.into_iter().map(|id| (short_id(keys, id), id)))
186 }
187
188 fn matching_short_ids(
189 &self,
190 ids: impl Iterator<Item = ([u8; 6], UnminedTxId)>,
191 ) -> HashSet<UnminedTxId> {
192 enum Match {
193 Missing,
194 Unique(UnminedTxId),
195 Ambiguous,
196 }
197 let mut matches = HashMap::with_capacity(self.short_ids.len());
198 for id in &self.short_ids {
199 match matches.entry(*id) {
200 Entry::Vacant(entry) => {
201 entry.insert(Match::Missing);
202 }
203 Entry::Occupied(mut entry) => {
204 entry.insert(Match::Ambiguous);
205 }
206 }
207 }
208 for (short, id) in ids {
209 if let Some(matched) = matches.get_mut(&short) {
210 match matched {
211 Match::Missing => *matched = Match::Unique(id),
212 Match::Unique(previous) if *previous != id => *matched = Match::Ambiguous,
213 _ => {}
214 }
215 }
216 }
217 matches
218 .into_values()
219 .filter_map(|matched| match matched {
220 Match::Unique(id) => Some(id),
221 _ => None,
222 })
223 .collect()
224 }
225
226 #[allow(clippy::unwrap_in_result)]
229 pub fn reconstruct(
230 self: Arc<Self>,
231 candidates: Vec<UnminedTx>,
232 ) -> Result<Reconstruction, SerializationError> {
233 self.validate()?;
234 check_count(candidates.len())?;
235 candidates
236 .iter()
237 .try_fold(0, |bytes, tx| add_bytes(bytes, tx.size))?;
238 let keys = self.keys();
239 let mut matching =
240 self.matching_short_ids(candidates.iter().map(|tx| (short_id(keys, tx.id), tx.id)));
241 let mut bodies: HashMap<_, _> = candidates
242 .into_iter()
243 .filter(|tx| matching.remove(&tx.id))
244 .map(|tx| (short_id(keys, tx.id), tx.transaction))
245 .collect();
246 let mut transactions = vec![None; self.short_ids.len() + self.prefilled.len()];
247 for (index, tx) in &self.prefilled {
248 transactions[*index] = Some(tx.clone());
249 }
250 let mut short_ids = self.short_ids.iter();
251 for slot in &mut transactions {
252 if slot.is_none() {
253 *slot = bodies.remove(
254 short_ids
255 .next()
256 .expect("each non-prefilled slot has a short ID"),
257 );
258 }
259 }
260 let bytes = self.header.zcash_serialized_size()
261 + CompactSizeMessage::try_from(transactions.len())?.zcash_serialized_size();
262 transactions.iter().flatten().try_fold(bytes, |bytes, tx| {
263 add_bytes(bytes, tx.zcash_serialized_size())
264 })?;
265 Ok(Reconstruction {
266 compact: self,
267 transactions,
268 })
269 }
270
271 fn keys(&self) -> (u64, u64) {
272 let mut hash = Sha256::new();
273 self.header
274 .zcash_serialize(&mut hash)
275 .expect("SHA256 writer cannot fail");
276 hash.update(self.nonce.to_le_bytes());
277 let digest = hash.finalize();
278 (
279 u64::from_le_bytes(digest[..8].try_into().expect("eight-byte key")),
280 u64::from_le_bytes(digest[8..16].try_into().expect("eight-byte key")),
281 )
282 }
283}
284
285impl Reconstruction {
286 pub fn transaction_count(&self) -> usize {
288 self.transactions.len()
289 }
290
291 pub fn missing_count(&self) -> usize {
293 self.transactions.iter().filter(|tx| tx.is_none()).count()
294 }
295
296 pub fn missing_indexes(&self) -> Vec<usize> {
298 self.transactions
299 .iter()
300 .enumerate()
301 .filter_map(|(index, tx)| tx.is_none().then_some(index))
302 .collect()
303 }
304
305 pub fn block_hash(&self) -> block::Hash {
307 self.compact.block_hash()
308 }
309
310 #[allow(clippy::unwrap_in_result)]
314 pub fn finish(mut self, response: BlockTransactions) -> Result<Arc<Block>, SerializationError> {
315 if response.block_hash != self.block_hash()
316 || response.transactions.len()
317 != self.transactions.iter().filter(|tx| tx.is_none()).count()
318 {
319 return Err(SerializationError::Parse(
320 "compact recovery hash or count mismatch",
321 ));
322 }
323 let bytes = self.compact.header.zcash_serialized_size()
324 + CompactSizeMessage::try_from(self.transactions.len())?.zcash_serialized_size();
325 self.transactions
326 .iter()
327 .flatten()
328 .chain(response.transactions.iter())
329 .try_fold(bytes, |bytes, tx| {
330 add_bytes(bytes, tx.zcash_serialized_size())
331 })?;
332 let keys = self.compact.keys();
333 let mut recovered = response.transactions.into_iter();
334 let mut prefilled = self.compact.prefilled.iter().peekable();
335 let mut short_ids = self.compact.short_ids.iter();
336 for (index, slot) in self.transactions.iter_mut().enumerate() {
337 if prefilled
338 .peek()
339 .is_some_and(|(position, _)| *position == index)
340 {
341 prefilled.next();
342 continue;
343 }
344 let expected = short_ids
345 .next()
346 .expect("each non-prefilled slot has a short ID");
347 if slot.is_none() {
348 let tx = recovered
349 .next()
350 .expect("response count equals missing slot count");
351 if short_id(keys, tx.as_ref().into()) != *expected {
352 return Err(SerializationError::Parse(
353 "compact recovery identity or order mismatch",
354 ));
355 }
356 *slot = Some(tx);
357 }
358 }
359 let block = Arc::new(Block {
360 header: self.compact.header.clone(),
361 transactions: self
362 .transactions
363 .into_iter()
364 .map(|tx| tx.expect("every missing slot was filled by the exact response count"))
365 .collect(),
366 });
367 let mut seen = HashSet::with_capacity(block.transactions.len());
368 if block.transactions.iter().any(|tx| !seen.insert(tx.hash()))
369 || block.transactions.iter().collect::<block::merkle::Root>()
370 != block.header.merkle_root
371 {
372 return Err(SerializationError::Parse(
373 "compact block duplicate transaction or Merkle mismatch",
374 ));
375 }
376 Ok(block)
377 }
378}
379
380fn short_id(keys: (u64, u64), id: UnminedTxId) -> [u8; 6] {
381 let mut hash = SipHasher24::new_with_keys(keys.0, keys.1);
382 match id {
383 UnminedTxId::Legacy(id) => hash.write(&id.0),
384 UnminedTxId::Witnessed(id) => hash.write(&<[u8; 64]>::from(id)),
385 }
386 hash.finish().to_le_bytes()[..6]
387 .try_into()
388 .expect("six-byte short ID")
389}
390
391fn check_count(count: usize) -> Result<(), SerializationError> {
392 if u64::try_from(count)? > Transaction::max_allocation() {
393 return Err(SerializationError::Parse(
394 "compact transaction count exceeds block limit",
395 ));
396 }
397 Ok(())
398}
399
400fn check_bytes(bytes: usize) -> Result<(), SerializationError> {
401 if u64::try_from(bytes)? > MAX_BLOCK_BYTES {
402 return Err(SerializationError::Parse(
403 "compact transaction bytes exceed block limit",
404 ));
405 }
406 Ok(())
407}
408
409fn check_transactions_size(parsed: usize, bytes: u64) -> Result<(), SerializationError> {
413 if bytes < u64::try_from(parsed)?.saturating_mul(MIN_TRANSPARENT_TX_SIZE) {
414 return Err(SerializationError::Parse(
415 "compact transactions are smaller than the smallest valid transaction",
416 ));
417 }
418
419 Ok(())
420}
421
422fn add_bytes(bytes: usize, extra: usize) -> Result<usize, SerializationError> {
423 let bytes = bytes.checked_add(extra).ok_or(SerializationError::Parse(
424 "compact transaction size overflow",
425 ))?;
426 check_bytes(bytes)?;
427 Ok(bytes)
428}
429
430fn read_count(reader: &mut impl Read) -> Result<usize, SerializationError> {
431 let count = usize::from(CompactSizeMessage::zcash_deserialize(reader)?);
432 check_count(count)?;
433 Ok(count)
434}
435
436const MAX_INITIAL_ALLOCATION: usize = 1024;
441
442fn vec_for_count<T>(count: usize) -> Vec<T> {
444 Vec::with_capacity(count.min(MAX_INITIAL_ALLOCATION))
445}
446
447fn read_index(
448 reader: &mut impl Read,
449 next: &mut usize,
450 count: usize,
451) -> Result<usize, SerializationError> {
452 let delta = usize::from(CompactSizeMessage::zcash_deserialize(reader)?);
453 let index = next
454 .checked_add(delta)
455 .filter(|index| *index < count)
456 .ok_or(SerializationError::Parse(
457 "compact differential index exceeds block limit",
458 ))?;
459 *next = index + 1;
460 Ok(index)
461}
462
463fn write_count(writer: &mut impl Write, count: usize) -> io::Result<()> {
464 CompactSizeMessage::try_from(count)
465 .map_err(io::Error::other)?
466 .zcash_serialize(writer)
467}
468
469fn write_index(writer: &mut impl Write, index: usize, next: &mut usize) -> io::Result<()> {
470 let delta = index
471 .checked_sub(*next)
472 .ok_or_else(|| io::Error::other("unordered compact indexes"))?;
473 *next = index
474 .checked_add(1)
475 .ok_or_else(|| io::Error::other("compact index overflow"))?;
476 write_count(writer, delta)
477}
478
479impl ZcashSerialize for CompactBlock {
480 fn zcash_serialize<W: Write>(&self, mut writer: W) -> io::Result<()> {
481 self.validate().map_err(io::Error::other)?;
482 self.header.zcash_serialize(&mut writer)?;
483 writer.write_u64::<LittleEndian>(self.nonce)?;
484 write_count(&mut writer, self.short_ids.len())?;
485 for id in &self.short_ids {
486 writer.write_all(id)?;
487 }
488 write_count(&mut writer, self.prefilled.len())?;
489 let mut next = 0;
490 for (index, tx) in &self.prefilled {
491 write_index(&mut writer, *index, &mut next)?;
492 tx.zcash_serialize(&mut writer)?;
493 }
494 Ok(())
495 }
496}
497
498impl ZcashDeserialize for CompactBlock {
499 fn zcash_deserialize<R: Read>(reader: R) -> Result<Self, SerializationError> {
500 let mut reader = reader.take(u64::try_from(MAX_PROTOCOL_MESSAGE_LEN)?);
501 let header = Arc::new(block::Header::zcash_deserialize(&mut reader)?);
502 let nonce = reader.read_u64::<LittleEndian>()?;
503 let count = read_count(&mut reader)?;
504 let mut short_ids = vec_for_count(count);
505 for _ in 0..count {
506 let mut id = [0; 6];
507 reader.read_exact(&mut id)?;
508 short_ids.push(id);
509 }
510 let prefilled_count = read_count(&mut reader)?;
511 let count = count
512 .checked_add(prefilled_count)
513 .ok_or(SerializationError::Parse(
514 "compact transaction count overflow",
515 ))?;
516 check_count(count)?;
517 let mut prefilled = vec_for_count(prefilled_count);
518 let mut next = 0;
519 let mut transaction_bytes = 0;
520 for _ in 0..prefilled_count {
521 let index = read_index(&mut reader, &mut next, count)?;
522 let start = reader.limit();
523 prefilled.push((
524 index,
525 Arc::new(Transaction::zcash_deserialize(&mut reader)?),
526 ));
527 transaction_bytes += start - reader.limit();
528 check_transactions_size(prefilled.len(), transaction_bytes)?;
529 }
530 let compact = Self {
531 header,
532 nonce,
533 short_ids,
534 prefilled,
535 };
536 compact.validate()?;
537 Ok(compact)
538 }
539}
540
541impl ZcashSerialize for BlockTransactionsRequest {
542 fn zcash_serialize<W: Write>(&self, mut writer: W) -> io::Result<()> {
543 check_count(self.indexes.len()).map_err(io::Error::other)?;
544 self.block_hash.zcash_serialize(&mut writer)?;
545 write_count(&mut writer, self.indexes.len())?;
546 let mut next = 0;
547 for index in &self.indexes {
548 check_count(index.saturating_add(1)).map_err(io::Error::other)?;
549 write_index(&mut writer, *index, &mut next)?;
550 }
551 Ok(())
552 }
553}
554
555impl ZcashDeserialize for BlockTransactionsRequest {
556 fn zcash_deserialize<R: Read>(mut reader: R) -> Result<Self, SerializationError> {
557 let block_hash = block::Hash::zcash_deserialize(&mut reader)?;
558 let count = read_count(&mut reader)?;
559 let mut indexes = vec_for_count(count);
560 let mut next = 0;
561 for _ in 0..count {
562 indexes.push(read_index(
563 &mut reader,
564 &mut next,
565 usize::try_from(Transaction::max_allocation())?,
566 )?);
567 }
568 Ok(Self {
569 block_hash,
570 indexes,
571 })
572 }
573}
574
575impl ZcashSerialize for BlockTransactions {
576 fn zcash_serialize<W: Write>(&self, mut writer: W) -> io::Result<()> {
577 check_count(self.transactions.len()).map_err(io::Error::other)?;
578 self.transactions
579 .iter()
580 .try_fold(0, |bytes, tx| add_bytes(bytes, tx.zcash_serialized_size()))
581 .map_err(io::Error::other)?;
582 self.block_hash.zcash_serialize(&mut writer)?;
583 self.transactions.zcash_serialize(&mut writer)
584 }
585}
586
587impl ZcashDeserialize for BlockTransactions {
588 fn zcash_deserialize<R: Read>(mut reader: R) -> Result<Self, SerializationError> {
589 let block_hash = block::Hash::zcash_deserialize(&mut reader)?;
590 let count = read_count(&mut reader)?;
591 let mut reader = reader.take(MAX_BLOCK_BYTES);
592 let mut transactions = vec_for_count(count);
593 for _ in 0..count {
594 transactions.push(Arc::new(Transaction::zcash_deserialize(&mut reader)?));
595 check_transactions_size(transactions.len(), MAX_BLOCK_BYTES - reader.limit())?;
596 }
597 Ok(Self {
598 block_hash,
599 transactions,
600 })
601 }
602}