zebra_chain/block/
merkle.rs1use std::{fmt, io::Write};
4
5use hex::{FromHex, ToHex};
6use rayon::prelude::*;
7
8use crate::{
9 serialization::{sha256d, BytesInDisplayOrder},
10 transaction::{self, Transaction, UnminedTx, UnminedTxId, VerifiedUnminedTx},
11};
12
13#[cfg(any(test, feature = "proptest-impl"))]
14use proptest_derive::Arbitrary;
15
16pub(crate) const PARALLEL_MERKLE_THRESHOLD: usize = 1_024;
18
19const MERKLE_PAIRS_PER_CHUNK: usize = 128;
21
22#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
80#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary, Default))]
81pub struct Root(pub [u8; 32]);
82
83impl fmt::Debug for Root {
84 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85 f.debug_tuple("Root").field(&hex::encode(self.0)).finish()
86 }
87}
88
89impl From<[u8; 32]> for Root {
90 fn from(hash: [u8; 32]) -> Self {
91 Root(hash)
92 }
93}
94
95impl From<Root> for [u8; 32] {
96 fn from(hash: Root) -> Self {
97 hash.0
98 }
99}
100
101impl BytesInDisplayOrder<true> for Root {
102 fn bytes_in_serialized_order(&self) -> [u8; 32] {
103 self.0
104 }
105
106 fn from_bytes_in_serialized_order(bytes: [u8; 32]) -> Self {
107 Root(bytes)
108 }
109}
110
111impl ToHex for &Root {
112 fn encode_hex<T: FromIterator<char>>(&self) -> T {
113 self.bytes_in_display_order().encode_hex()
114 }
115
116 fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
117 self.bytes_in_display_order().encode_hex_upper()
118 }
119}
120
121impl ToHex for Root {
122 fn encode_hex<T: FromIterator<char>>(&self) -> T {
123 (&self).encode_hex()
124 }
125
126 fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
127 (&self).encode_hex_upper()
128 }
129}
130
131impl FromHex for Root {
132 type Error = <[u8; 32] as FromHex>::Error;
133
134 fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
135 let mut hash = <[u8; 32]>::from_hex(hex)?;
136 hash.reverse();
137
138 Ok(hash.into())
139 }
140}
141
142fn hash(h1: &[u8; 32], h2: &[u8; 32]) -> [u8; 32] {
143 let mut w = sha256d::Writer::default();
144 w.write_all(h1).unwrap();
145 w.write_all(h2).unwrap();
146 w.finish()
147}
148
149fn auth_data_hash(h1: &[u8; 32], h2: &[u8; 32]) -> [u8; 32] {
150 blake2b_simd::Params::new()
154 .hash_length(32)
155 .personal(b"ZcashAuthDatHash")
156 .to_state()
157 .update(h1)
158 .update(h2)
159 .finalize()
160 .as_bytes()
161 .try_into()
162 .expect("32 byte array")
163}
164
165fn reduce_merkle_root(
170 mut hashes: Vec<[u8; 32]>,
171 hash_pair: impl Fn(&[u8; 32], &[u8; 32]) -> [u8; 32] + Sync,
172) -> [u8; 32] {
173 let mut next = Vec::new();
174 while hashes.len() > 1 {
175 next.resize(hashes.len().div_ceil(2), [0; 32]);
176 let reduce_chunk = |(output, input): (&mut [[u8; 32]], &[[u8; 32]])| {
177 for (parent, pair) in output.iter_mut().zip(input.chunks(2)) {
178 *parent = hash_pair(&pair[0], pair.get(1).unwrap_or(&pair[0]));
179 }
180 };
181
182 if hashes.len() >= PARALLEL_MERKLE_THRESHOLD {
183 next.par_chunks_mut(MERKLE_PAIRS_PER_CHUNK)
184 .zip(hashes.par_chunks(2 * MERKLE_PAIRS_PER_CHUNK))
185 .for_each(reduce_chunk);
186 } else {
187 reduce_chunk((&mut next, &hashes));
188 }
189 std::mem::swap(&mut hashes, &mut next);
190 }
191 hashes[0]
192}
193
194impl<T> std::iter::FromIterator<T> for Root
195where
196 T: std::convert::AsRef<Transaction>,
197{
198 fn from_iter<I>(transactions: I) -> Self
199 where
200 I: IntoIterator<Item = T>,
201 {
202 transactions
203 .into_iter()
204 .map(|tx| tx.as_ref().hash())
205 .collect()
206 }
207}
208
209impl std::iter::FromIterator<UnminedTx> for Root {
210 fn from_iter<I>(transactions: I) -> Self
211 where
212 I: IntoIterator<Item = UnminedTx>,
213 {
214 transactions
215 .into_iter()
216 .map(|tx| tx.id.mined_id())
217 .collect()
218 }
219}
220
221impl std::iter::FromIterator<UnminedTxId> for Root {
222 fn from_iter<I>(tx_ids: I) -> Self
223 where
224 I: IntoIterator<Item = UnminedTxId>,
225 {
226 tx_ids.into_iter().map(|tx_id| tx_id.mined_id()).collect()
227 }
228}
229
230impl std::iter::FromIterator<VerifiedUnminedTx> for Root {
231 fn from_iter<I>(transactions: I) -> Self
232 where
233 I: IntoIterator<Item = VerifiedUnminedTx>,
234 {
235 transactions
236 .into_iter()
237 .map(|tx| tx.transaction.id.mined_id())
238 .collect()
239 }
240}
241
242impl std::iter::FromIterator<transaction::Hash> for Root {
243 fn from_iter<I>(hashes: I) -> Self
248 where
249 I: IntoIterator<Item = transaction::Hash>,
250 {
251 let hashes = hashes.into_iter().map(|hash| hash.0).collect::<Vec<_>>();
252 Self(reduce_merkle_root(hashes, hash))
253 }
254}
255
256#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
264#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
265pub struct AuthDataRoot(pub(crate) [u8; 32]);
266
267impl fmt::Debug for AuthDataRoot {
268 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
269 f.debug_tuple("AuthRoot")
270 .field(&hex::encode(self.0))
271 .finish()
272 }
273}
274
275impl From<[u8; 32]> for AuthDataRoot {
276 fn from(hash: [u8; 32]) -> Self {
277 AuthDataRoot(hash)
278 }
279}
280
281impl From<AuthDataRoot> for [u8; 32] {
282 fn from(hash: AuthDataRoot) -> Self {
283 hash.0
284 }
285}
286
287impl BytesInDisplayOrder<true> for AuthDataRoot {
288 fn bytes_in_serialized_order(&self) -> [u8; 32] {
289 self.0
290 }
291
292 fn from_bytes_in_serialized_order(bytes: [u8; 32]) -> Self {
293 AuthDataRoot(bytes)
294 }
295}
296
297impl ToHex for &AuthDataRoot {
298 fn encode_hex<T: FromIterator<char>>(&self) -> T {
299 self.bytes_in_display_order().encode_hex()
300 }
301
302 fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
303 self.bytes_in_display_order().encode_hex_upper()
304 }
305}
306
307impl ToHex for AuthDataRoot {
308 fn encode_hex<T: FromIterator<char>>(&self) -> T {
309 (&self).encode_hex()
310 }
311
312 fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
313 (&self).encode_hex_upper()
314 }
315}
316
317impl FromHex for AuthDataRoot {
318 type Error = <[u8; 32] as FromHex>::Error;
319
320 fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
321 let mut hash = <[u8; 32]>::from_hex(hex)?;
322 hash.reverse();
323
324 Ok(hash.into())
325 }
326}
327
328pub const AUTH_DIGEST_PLACEHOLDER: transaction::AuthDigest = transaction::AuthDigest([0xFF; 32]);
338
339impl<T> std::iter::FromIterator<T> for AuthDataRoot
340where
341 T: std::convert::AsRef<Transaction>,
342{
343 fn from_iter<I>(transactions: I) -> Self
344 where
345 I: IntoIterator<Item = T>,
346 {
347 transactions
348 .into_iter()
349 .map(|tx| tx.as_ref().auth_digest().unwrap_or(AUTH_DIGEST_PLACEHOLDER))
350 .collect()
351 }
352}
353
354impl std::iter::FromIterator<UnminedTx> for AuthDataRoot {
355 fn from_iter<I>(transactions: I) -> Self
356 where
357 I: IntoIterator<Item = UnminedTx>,
358 {
359 transactions
360 .into_iter()
361 .map(|tx| tx.id.auth_digest().unwrap_or(AUTH_DIGEST_PLACEHOLDER))
362 .collect()
363 }
364}
365
366impl std::iter::FromIterator<VerifiedUnminedTx> for AuthDataRoot {
367 fn from_iter<I>(transactions: I) -> Self
368 where
369 I: IntoIterator<Item = VerifiedUnminedTx>,
370 {
371 transactions
372 .into_iter()
373 .map(|tx| {
374 tx.transaction
375 .id
376 .auth_digest()
377 .unwrap_or(AUTH_DIGEST_PLACEHOLDER)
378 })
379 .collect()
380 }
381}
382
383impl std::iter::FromIterator<UnminedTxId> for AuthDataRoot {
384 fn from_iter<I>(tx_ids: I) -> Self
385 where
386 I: IntoIterator<Item = UnminedTxId>,
387 {
388 tx_ids
389 .into_iter()
390 .map(|tx_id| tx_id.auth_digest().unwrap_or(AUTH_DIGEST_PLACEHOLDER))
391 .collect()
392 }
393}
394
395impl std::iter::FromIterator<transaction::AuthDigest> for AuthDataRoot {
396 fn from_iter<I>(hashes: I) -> Self
397 where
398 I: IntoIterator<Item = transaction::AuthDigest>,
399 {
400 let mut hashes = hashes.into_iter().map(|hash| hash.0).collect::<Vec<_>>();
401 let pad_count = hashes.len().next_power_of_two() - hashes.len();
407 hashes.extend(std::iter::repeat_n([0u8; 32], pad_count));
408 assert!(hashes.len().is_power_of_two());
409
410 Self(reduce_merkle_root(hashes, auth_data_hash))
411 }
412}
413
414#[cfg(test)]
415mod tests {
416 use super::*;
417
418 use crate::{block::Block, serialization::ZcashDeserialize, transaction::AuthDigest};
419
420 #[test]
421 fn block_test_vectors() {
422 for block_bytes in zebra_test::vectors::BLOCKS.iter() {
423 let block = Block::zcash_deserialize(&**block_bytes).unwrap();
424 let merkle_root = block.transactions.iter().collect::<Root>();
425 assert_eq!(
426 merkle_root,
427 block.header.merkle_root,
428 "block: {:?} {:?} transaction hashes: {:?}",
429 block.coinbase_height().unwrap(),
430 block.hash(),
431 block
432 .transactions
433 .iter()
434 .map(|tx| tx.hash())
435 .collect::<Vec<_>>()
436 );
437 }
438 }
439
440 #[test]
441 fn auth_digest() {
442 for block_bytes in zebra_test::vectors::BLOCKS.iter() {
443 let block = Block::zcash_deserialize(&**block_bytes).unwrap();
444 let _auth_root = block.transactions.iter().collect::<AuthDataRoot>();
445 }
447 }
448
449 #[test]
450 fn auth_data_padding() {
451 let mut v = vec![
453 AuthDigest([0x42; 32]),
454 AuthDigest([0xAA; 32]),
455 AuthDigest([0x77; 32]),
456 ];
457 let root_3 = v.iter().copied().collect::<AuthDataRoot>();
458
459 v.push(AuthDigest([0x00; 32]));
464 let root_4 = v.iter().copied().collect::<AuthDataRoot>();
465
466 assert_eq!(root_3, root_4);
467 }
468
469 #[test]
470 fn auth_data_pre_v5() {
471 let block =
473 Block::zcash_deserialize(&**zebra_test::vectors::BLOCK_MAINNET_1046400_BYTES).unwrap();
474 let auth_root = block.transactions.iter().take(1).collect::<AuthDataRoot>();
475
476 let expect_auth_root = [AuthDigest([0xFF; 32])]
480 .iter()
481 .copied()
482 .collect::<AuthDataRoot>();
483
484 assert_eq!(auth_root, expect_auth_root);
485 }
486}