Skip to main content

zebra_chain/block/
merkle.rs

1//! The Bitcoin-inherited Merkle tree of transactions.
2
3use 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
16/// Keep levels below 1,024 input nodes serial to amortize Rayon scheduling over enough hashes.
17pub(crate) const PARALLEL_MERKLE_THRESHOLD: usize = 1_024;
18
19/// Each parallel task hashes up to 128 contiguous pairs into its own contiguous output slice.
20const MERKLE_PAIRS_PER_CHUNK: usize = 128;
21
22/// The root of the Bitcoin-inherited transaction Merkle tree, binding the
23/// block header to the transactions in the block.
24///
25/// Note: for V5-onward transactions it does not bind to authorizing data
26/// (signature and proofs) which makes it non-malleable [ZIP-244].
27///
28/// Note that because of a flaw in Bitcoin's design, the `merkle_root` does
29/// not always precisely bind the contents of the block (CVE-2012-2459). It
30/// is sometimes possible for an attacker to create multiple distinct sets of
31/// transactions with the same Merkle root, although only one set will be
32/// valid.
33///
34/// # Malleability
35///
36/// The Bitcoin source code contains the following note:
37///
38/// > WARNING! If you're reading this because you're learning about crypto
39/// > and/or designing a new system that will use merkle trees, keep in mind
40/// > that the following merkle tree algorithm has a serious flaw related to
41/// > duplicate txids, resulting in a vulnerability (CVE-2012-2459).
42/// > The reason is that if the number of hashes in the list at a given time
43/// > is odd, the last one is duplicated before computing the next level (which
44/// > is unusual in Merkle trees). This results in certain sequences of
45/// > transactions leading to the same merkle root. For example, these two
46/// > trees:
47/// >
48/// > ```ascii
49/// >              A               A
50/// >            /  \            /   \
51/// >          B     C         B       C
52/// >         / \    |        / \     / \
53/// >        D   E   F       D   E   F   F
54/// >       / \ / \ / \     / \ / \ / \ / \
55/// >       1 2 3 4 5 6     1 2 3 4 5 6 5 6
56/// > ```
57/// >
58/// > for transaction lists \[1,2,3,4,5,6\] and \[1,2,3,4,5,6,5,6\] (where 5 and
59/// > 6 are repeated) result in the same root hash A (because the hash of both
60/// > of (F) and (F,F) is C).
61/// >
62/// > The vulnerability results from being able to send a block with such a
63/// > transaction list, with the same merkle root, and the same block hash as
64/// > the original without duplication, resulting in failed validation. If the
65/// > receiving node proceeds to mark that block as permanently invalid
66/// > however, it will fail to accept further unmodified (and thus potentially
67/// > valid) versions of the same block. We defend against this by detecting
68/// > the case where we would hash two identical hashes at the end of the list
69/// > together, and treating that identically to the block having an invalid
70/// > merkle root. Assuming no double-SHA256 collisions, this will detect all
71/// > known ways of changing the transactions without affecting the merkle
72/// > root.
73///
74/// This vulnerability does not apply to Zebra, because it does not store invalid
75/// data on disk, and because it does not permanently fail blocks or use an
76/// aggressive anti-DoS mechanism.
77///
78/// [ZIP-244]: https://zips.z.cash/zip-0244
79#[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    // > Non-leaf hashes in this tree are BLAKE2b-256 hashes personalized by
151    // > the string "ZcashAuthDatHash".
152    // https://zips.z.cash/zip-0244#block-header-changes
153    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
165/// Reduce ordered leaves, duplicating an unpaired final node at each level.
166///
167/// Auth-data trees are padded before calling this helper, so their levels always contain pairs.
168/// Reuse two buffers across levels, with disjoint output chunks preserving left/right order.
169fn 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    /// # Panics
244    ///
245    /// When there are no transactions in the iterator.
246    /// This is impossible, because every block must have a coinbase transaction.
247    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/// The root of the authorizing data Merkle tree, binding the
257/// block header to the authorizing data of the block (signatures, proofs)
258/// as defined in [ZIP-244].
259///
260/// See [`Root`] for an important disclaimer.
261///
262/// [ZIP-244]: https://zips.z.cash/zip-0244
263#[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
328/// The placeholder used for the [`AuthDigest`](transaction::AuthDigest) of pre-v5 transactions.
329///
330/// # Consensus
331///
332/// > For transaction versions before v5, a placeholder value consisting
333/// > of 32 bytes of 0xFF is used in place of the authorizing data commitment.
334/// > This is only used in the tree committed to by hashAuthDataRoot.
335///
336/// <https://zips.z.cash/zip-0244#authorizing-data-commitment>
337pub 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        // > This new commitment is named hashAuthDataRoot and is the root of a
402        // > binary Merkle tree of transaction authorizing data commitments [...]
403        // > padded with leaves having the "null" hash value [0u8; 32].
404        // https://zips.z.cash/zip-0244#block-header-changes
405        // Pad with enough leaves to make the tree full (a power of 2).
406        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            // No test vectors for now, so just check it computes without panicking
446        }
447    }
448
449    #[test]
450    fn auth_data_padding() {
451        // Compute the root of a 3-leaf tree with arbitrary leaves
452        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        // Compute the root a 4-leaf tree with the same leaves as before and
460        // an additional all-zeroes leaf.
461        // Since this is the same leaf used as padding in the previous tree,
462        // then both trees must have the same root.
463        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        // Compute the AuthDataRoot for a single transaction of an arbitrary pre-V5 block
472        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        // Compute the AuthDataRoot with a single [0xFF; 32] digest.
477        // Since ZIP-244 specifies that this value must be used as the auth digest of
478        // pre-V5 transactions, then the roots must match.
479        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}