Skip to main content

zebra_chain/
block.rs

1//! Blocks and block-related structures (heights, headers, etc.)
2
3use std::{collections::HashMap, fmt, ops::Neg, sync::Arc};
4
5use halo2::pasta::{group::ff::PrimeField, pallas};
6
7use crate::{
8    amount::{Amount, DeferredPoolBalanceChange, NegativeAllowed, NonNegative},
9    block::merkle::AuthDataRoot,
10    fmt::DisplayToDebug,
11    ironwood, orchard,
12    parameters::{subsidy, Network, NetworkUpgrade},
13    sapling,
14    serialization::TrustedPreallocate,
15    sprout,
16    transaction::Transaction,
17    transparent,
18    value_balance::{ValueBalance, ValueBalanceError},
19};
20
21mod commitment;
22mod error;
23mod hash;
24mod header;
25mod height;
26mod serialize;
27
28pub mod genesis;
29pub mod merkle;
30
31#[cfg(any(test, feature = "proptest-impl"))]
32pub mod arbitrary;
33#[cfg(any(test, feature = "bench", feature = "proptest-impl"))]
34pub mod tests;
35
36pub use commitment::{
37    ChainHistoryBlockTxAuthCommitmentHash, ChainHistoryMmrRootHash, Commitment, CommitmentError,
38    CHAIN_HISTORY_ACTIVATION_RESERVED,
39};
40pub use hash::Hash;
41pub use header::{BlockTimeError, CountedHeader, Header, ZCASH_BLOCK_VERSION};
42pub use height::{Height, HeightDiff, TryIntoHeight};
43pub use serialize::{SerializedBlock, MAX_BLOCK_BYTES};
44
45#[cfg(any(test, feature = "proptest-impl"))]
46pub use arbitrary::LedgerState;
47
48/// A Zcash block, containing a header and a list of transactions.
49#[derive(Clone, Debug, Eq, PartialEq)]
50#[cfg_attr(any(test, feature = "proptest-impl"), derive(Serialize))]
51pub struct Block {
52    /// The block header, containing block metadata.
53    pub header: Arc<Header>,
54    /// The block transactions.
55    pub transactions: Vec<Arc<Transaction>>,
56}
57
58impl fmt::Display for Block {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        let mut fmter = f.debug_struct("Block");
61
62        if let Some(height) = self.coinbase_height() {
63            fmter.field("height", &height);
64        }
65        fmter.field("transactions", &self.transactions.len());
66        fmter.field("hash", &DisplayToDebug(self.hash()));
67
68        fmter.finish()
69    }
70}
71
72impl Block {
73    /// Return the block height reported in the coinbase transaction, if any.
74    ///
75    /// Note
76    ///
77    /// Verified blocks have a valid height.
78    pub fn coinbase_height(&self) -> Option<Height> {
79        self.transactions
80            .first()
81            .and_then(|tx| {
82                let inputs = tx.inputs();
83                inputs.into_iter().next()
84            })
85            .and_then(|input| match input {
86                transparent::Input::Coinbase { height, .. } => Some(height),
87                _ => None,
88            })
89    }
90
91    /// Compute the hash of this block.
92    pub fn hash(&self) -> Hash {
93        Hash::from(self)
94    }
95
96    /// Get the parsed block [`Commitment`] for this block.
97    ///
98    /// The interpretation of the commitment depends on the
99    /// configured `network`, and this block's height.
100    ///
101    /// Returns an error if this block does not have a block height,
102    /// or if the commitment value is structurally invalid.
103    pub fn commitment(&self, network: &Network) -> Result<Commitment, CommitmentError> {
104        match self.coinbase_height() {
105            None => Err(CommitmentError::MissingBlockHeight {
106                block_hash: self.hash(),
107            }),
108            Some(height) => Commitment::from_bytes(*self.header.commitment_bytes, network, height),
109        }
110    }
111
112    /// Check if the `network_upgrade` fields from each transaction in the block matches
113    /// the network upgrade calculated from the `network` and block height.
114    ///
115    /// # Consensus
116    ///
117    /// > [NU5 onward] The nConsensusBranchId field MUST match the consensus branch ID used
118    /// > for SIGHASH transaction hashes, as specified in [ZIP-244].
119    ///
120    /// <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
121    ///
122    /// [ZIP-244]: https://zips.z.cash/zip-0244
123    #[allow(clippy::unwrap_in_result)]
124    pub fn check_transaction_network_upgrade_consistency(
125        &self,
126        network: &Network,
127    ) -> Result<(), error::BlockError> {
128        let block_nu =
129            NetworkUpgrade::current(network, self.coinbase_height().expect("a valid height"));
130
131        if self
132            .transactions
133            .iter()
134            .filter_map(|trans| trans.as_ref().network_upgrade())
135            .any(|trans_nu| trans_nu != block_nu)
136        {
137            return Err(error::BlockError::WrongTransactionConsensusBranchId);
138        }
139
140        Ok(())
141    }
142
143    /// Access the sprout nullifiers from all transactions in this block.
144    pub fn sprout_nullifiers(&self) -> impl Iterator<Item = sprout::Nullifier> + '_ {
145        self.transactions
146            .iter()
147            .flat_map(|transaction| transaction.sprout_nullifiers().collect::<Vec<_>>())
148    }
149
150    /// Access the sapling nullifiers from all transactions in this block.
151    pub fn sapling_nullifiers(&self) -> impl Iterator<Item = sapling::Nullifier> + '_ {
152        self.transactions
153            .iter()
154            .flat_map(|transaction| transaction.sapling_nullifiers().collect::<Vec<_>>())
155    }
156
157    /// Access the orchard nullifiers from all transactions in this block.
158    pub fn orchard_nullifiers(&self) -> impl Iterator<Item = orchard::Nullifier> + '_ {
159        self.transactions
160            .iter()
161            .flat_map(|transaction| transaction.orchard_nullifiers().collect::<Vec<_>>())
162    }
163
164    /// Access the ironwood nullifiers from all transactions in this block.
165    pub fn ironwood_nullifiers(&self) -> impl Iterator<Item = ironwood::Nullifier> + '_ {
166        self.transactions
167            .iter()
168            .flat_map(|transaction| transaction.ironwood_nullifiers().collect::<Vec<_>>())
169    }
170
171    /// Access the sprout note commitments from all transactions in this block.
172    pub fn sprout_note_commitments(
173        &self,
174    ) -> impl Iterator<Item = sprout::commitment::NoteCommitment> + '_ {
175        self.transactions
176            .iter()
177            .flat_map(|transaction| transaction.sprout_note_commitments().collect::<Vec<_>>())
178    }
179
180    /// Access the sapling note commitments from all transactions in this block.
181    pub fn sapling_note_commitments(
182        &self,
183    ) -> impl Iterator<Item = sapling_crypto::note::ExtractedNoteCommitment> + '_ {
184        self.transactions
185            .iter()
186            .flat_map(|transaction| transaction.sapling_note_commitments().collect::<Vec<_>>())
187    }
188
189    /// Access the orchard note commitments from all transactions in this block,
190    /// as `pallas::Base` values for the note commitment tree.
191    pub fn orchard_note_commitments(&self) -> impl Iterator<Item = pallas::Base> + '_ {
192        self.transactions.iter().flat_map(|transaction| {
193            transaction
194                .orchard_note_commitments()
195                .map(|cmx| {
196                    let bytes = cmx.to_bytes();
197                    pallas::Base::from_repr(bytes)
198                        .expect("orchard note commitment is a valid pallas::Base")
199                })
200                .collect::<Vec<_>>()
201        })
202    }
203
204    /// Access the ironwood note commitments from all transactions in this block,
205    /// as `pallas::Base` values for the note commitment tree.
206    pub fn ironwood_note_commitments(&self) -> impl Iterator<Item = pallas::Base> + '_ {
207        self.transactions.iter().flat_map(|transaction| {
208            transaction
209                .ironwood_note_commitments()
210                .map(|cmx| {
211                    let bytes = cmx.to_bytes();
212                    pallas::Base::from_repr(bytes)
213                        .expect("ironwood note commitment is a valid pallas::Base")
214                })
215                .collect::<Vec<_>>()
216        })
217    }
218
219    /// Count how many Sapling transactions exist in a block,
220    /// i.e. transactions "where either of vSpendsSapling or vOutputsSapling is non-empty"
221    /// <https://zips.z.cash/zip-0221#tree-node-specification>.
222    pub fn sapling_transactions_count(&self) -> u64 {
223        self.transactions
224            .iter()
225            .filter(|tx| tx.has_sapling_shielded_data())
226            .count()
227            .try_into()
228            .expect("number of transactions must fit u64")
229    }
230
231    /// Count how many Orchard transactions exist in a block,
232    /// i.e. transactions "where vActionsOrchard is non-empty."
233    /// <https://zips.z.cash/zip-0221#tree-node-specification>.
234    pub fn orchard_transactions_count(&self) -> u64 {
235        self.transactions
236            .iter()
237            .filter(|tx| tx.has_orchard_shielded_data())
238            .count()
239            .try_into()
240            .expect("number of transactions must fit u64")
241    }
242
243    /// Count how many Ironwood transactions exist in a block,
244    /// i.e. transactions where the Ironwood bundle is non-empty (NU6.3 onward).
245    pub fn ironwood_transactions_count(&self) -> u64 {
246        self.transactions
247            .iter()
248            .filter(|tx| tx.has_ironwood_shielded_data())
249            .count()
250            .try_into()
251            .expect("number of transactions must fit u64")
252    }
253
254    /// Returns the overall chain value pool change in this block---the negative sum of the
255    /// transaction value balances in this block.
256    ///
257    /// These are the changes in the transparent, Sprout, Sapling, Orchard, Ironwood and
258    /// Deferred chain value pools, and in the NSM reserve, as a result of this block.
259    ///
260    /// Positive values are added to the corresponding chain value pool and negative values are
261    /// removed from the corresponding pool.
262    ///
263    /// <https://zebra.zfnd.org/dev/rfcs/0012-value-pools.html#definitions>
264    ///
265    /// The given `utxos` must contain the [`transparent::Utxo`]s of every input in this block,
266    /// including UTXOs created by earlier transactions in this block. It can also contain unrelated
267    /// UTXOs, which are ignored.
268    ///
269    /// `previous_value_pools` must be the exact parent's balances.
270    /// Genesis transparent outputs are permanently unspendable, so they do not enter the pool.
271    /// Custom networks with nonzero genesis outputs must rebuild state created before this rule;
272    /// public-network genesis outputs are zero, so their historical balances are unchanged.
273    ///
274    /// This calculation does not validate coinbase payouts or funding outputs. Callers must
275    /// validate them separately with [`subsidy::subsidy_is_valid`] and
276    /// [`subsidy::miner_fees_are_valid`], using the exact parent's reserve-funded subsidy.
277    /// `deferred_pool_balance_change` must also be calculated from that same parent.
278    ///
279    /// Note that the chain value pool has the opposite sign to the transaction value pool.
280    pub fn chain_value_pool_change<U: AsRef<transparent::Utxo>>(
281        &self,
282        utxos: &HashMap<transparent::OutPoint, U>,
283        deferred_pool_balance_change: DeferredPoolBalanceChange,
284        network: &Network,
285        previous_value_pools: ValueBalance<NonNegative>,
286    ) -> Result<ValueBalance<NegativeAllowed>, ValueBalanceError> {
287        self.chain_value_pool_change_and_fees(
288            utxos,
289            deferred_pool_balance_change,
290            network,
291            previous_value_pools,
292        )
293        .map(|(change, _)| change)
294    }
295
296    /// Returns the pool change and gross non-coinbase fees in a single transaction traversal.
297    ///
298    /// The arguments have the same requirements as [`Self::chain_value_pool_change`].
299    /// Fees are `None` before NU7, preserving pre-NU7 accounting without fee validation,
300    /// and `Some`, including zero, from NU7 onward. This does not validate coinbase payouts.
301    pub fn chain_value_pool_change_and_fees<U: AsRef<transparent::Utxo>>(
302        &self,
303        utxos: &HashMap<transparent::OutPoint, U>,
304        deferred_pool_balance_change: DeferredPoolBalanceChange,
305        network: &Network,
306        previous_value_pools: ValueBalance<NonNegative>,
307    ) -> Result<(ValueBalance<NegativeAllowed>, Option<Amount<NonNegative>>), ValueBalanceError>
308    {
309        // `Result<T, E>` implements `IntoIterator`, so a `flat_map(|t| t.value_balance(utxos))`
310        // would silently drop transactions whose value balance returns `Err`. Use `try_fold`
311        // to propagate the first error instead.
312        //
313        // The transaction fees are accumulated in the same pass, because the NSM reserve
314        // contribution is calculated from them: `value_balance()` walks every input's UTXO, so a
315        // second pass would double the work on the state's block commit path.
316        //
317        // The fees are only accumulated once NU7 is active, so that this stays byte-for-byte the
318        // same calculation as before NU7 everywhere else. A transaction's fee is its remaining
319        // value, which is only guaranteed to be non-negative for semantically verified
320        // transactions, and this method is also called on blocks that have not been through the
321        // transaction verifier.
322        let height = self.coinbase_height();
323        let needs_fees =
324            height.is_some_and(|height| subsidy::nsm_value_balance_is_tracked(height, network));
325
326        let (tx_pool_sum, transaction_fees) = self.transactions.iter().try_fold(
327            (
328                ValueBalance::<NegativeAllowed>::zero(),
329                Amount::<NonNegative>::zero(),
330            ),
331            |(pool_sum, fees), tx| {
332                let value_balance = tx.value_balance(utxos)?;
333
334                // The coinbase transaction consumes the fees rather than paying them, so it is
335                // excluded from the total, exactly as in the block verifier's miner fee sum.
336                let fees = if needs_fees && !tx.is_coinbase() {
337                    let fee = value_balance
338                        .remaining_transaction_value()
339                        .map_err(ValueBalanceError::Total)?;
340
341                    (fees + fee).map_err(ValueBalanceError::Total)?
342                } else {
343                    fees
344                };
345
346                Ok::<_, ValueBalanceError>(((pool_sum + value_balance)?, fees))
347            },
348        )?;
349
350        let mut chain_value_pool_change = tx_pool_sum.neg();
351        chain_value_pool_change.set_deferred_amount(deferred_pool_balance_change.value());
352        if height == Some(Height::MIN) {
353            chain_value_pool_change.set_transparent_value_balance(ValueBalance::zero());
354        }
355
356        if let Some(height) = height {
357            chain_value_pool_change.set_nsm_amount(
358                subsidy::nsm_value_balance_change(
359                    height,
360                    network,
361                    previous_value_pools,
362                    transaction_fees,
363                )
364                .map_err(ValueBalanceError::Nsm)?,
365            );
366        }
367
368        Ok((
369            chain_value_pool_change,
370            needs_fees.then_some(transaction_fees),
371        ))
372    }
373
374    /// Returns the total transaction fees paid by the non-coinbase transactions in this block,
375    /// `TransactionFees(height)` in the [NU7 deployment ZIP][nu7].
376    ///
377    /// From NU7 activation the miner only receives part of them, see
378    /// [`nsm_fee_contribution`](crate::parameters::subsidy::nsm_fee_contribution).
379    ///
380    /// [nu7]: https://github.com/zcash/zips/pull/1363
381    ///
382    /// `utxos` has the same requirements as in [`Block::chain_value_pool_change`].
383    pub fn transaction_fees<U: AsRef<transparent::Utxo>>(
384        &self,
385        utxos: &HashMap<transparent::OutPoint, U>,
386    ) -> Result<Amount<NonNegative>, ValueBalanceError> {
387        self.transactions
388            .iter()
389            .filter(|tx| !tx.is_coinbase())
390            .try_fold(Amount::zero(), |fees, tx| {
391                let fee = tx
392                    .value_balance(utxos)?
393                    .remaining_transaction_value()
394                    .map_err(ValueBalanceError::Total)?;
395
396                (fees + fee).map_err(ValueBalanceError::Total)
397            })
398    }
399
400    /// Compute the root of the authorizing data Merkle tree,
401    /// as defined in [ZIP-244].
402    ///
403    /// [ZIP-244]: https://zips.z.cash/zip-0244
404    pub fn auth_data_root(&self) -> AuthDataRoot {
405        self.transactions.iter().collect::<AuthDataRoot>()
406    }
407}
408
409impl<'a> From<&'a Block> for Hash {
410    fn from(block: &'a Block) -> Hash {
411        block.header.as_ref().into()
412    }
413}
414
415/// The maximum number of `block::Hash` entries Zebra will preallocate for in
416/// a single peer-deserialized vector.
417///
418/// In the P2P protocol, `Vec<block::Hash>` appears as the `known_blocks` block
419/// locator in `getblocks` and `getheaders` messages. The Bitcoin/Zcash
420/// convention encodes locators with exponentially-spaced heights (1, 2, 3, …,
421/// 10, 20, 40, …, genesis), giving `~log2(N) + 10` entries for chain length N.
422/// For current Zcash chain heights (~3M blocks) a legitimate locator has ~32
423/// entries.
424///
425/// We cap at 101 to match Bitcoin Core's `MAX_LOCATOR_SZ` constant
426/// (`net_processing.cpp`), which zcashd inherits. This avoids any risk of
427/// rejecting legitimate locators sent by compatible nodes that follow the
428/// existing Bitcoin/Zcash protocol convention.
429///
430/// Without this cap, `Hash::max_allocation` was previously derived from
431/// `MAX_PROTOCOL_MESSAGE_LEN / 32 = 65,535`, which allowed a remote peer to
432/// force ~2 MiB heap preallocation per crafted `getblocks`/`getheaders` message
433/// before any payload was read. This is the same class as
434/// GHSA-xr93-pcq3-pxf8 (`addr_limit`), fixed for AddrV1/V2 in PR #10494.
435pub const MAX_BLOCK_LOCATOR_LENGTH: u64 = 101;
436
437impl TrustedPreallocate for Hash {
438    fn max_allocation() -> u64 {
439        MAX_BLOCK_LOCATOR_LENGTH
440    }
441}