Skip to main content

zebra_consensus/block/
check.rs

1//! Consensus check functions
2
3use std::{collections::HashSet, sync::Arc};
4
5use chrono::{DateTime, Utc};
6
7use zebra_chain::{
8    amount::{Amount, DeferredPoolBalanceChange, NonNegative},
9    block::{Block, Hash, Header, Height},
10    parameters::{
11        subsidy::{self, CoinbaseTransactionError},
12        Network, NetworkUpgrade,
13    },
14    transaction::{self, Transaction},
15    work::{
16        difficulty::{ExpandedDifficulty, ParameterDifficulty as _},
17        equihash,
18    },
19};
20
21use crate::{block::ShieldedActionCounts, error::*};
22
23/// Checks if there is exactly one coinbase transaction in `Block`,
24/// and if that coinbase transaction is the first transaction in the block.
25/// Returns the coinbase transaction is successful.
26///
27/// > A transaction that has a single transparent input with a null prevout field,
28/// > is called a coinbase transaction. Every block has a single coinbase
29/// > transaction as the first transaction in the block.
30///
31/// <https://zips.z.cash/protocol/protocol.pdf#coinbasetransactions>
32pub fn coinbase_is_first(block: &Block) -> Result<Arc<transaction::Transaction>, BlockError> {
33    // # Consensus
34    //
35    // > A block MUST have at least one transaction
36    //
37    // <https://zips.z.cash/protocol/protocol.pdf#blockheader>
38    let first = block
39        .transactions
40        .first()
41        .ok_or(BlockError::NoTransactions)?;
42    // > The first transaction in a block MUST be a coinbase transaction,
43    // > and subsequent transactions MUST NOT be coinbase transactions.
44    //
45    // <https://zips.z.cash/protocol/protocol.pdf#blockheader>
46    //
47    // > A transaction that has a single transparent input with a null prevout
48    // > field, is called a coinbase transaction.
49    //
50    // <https://zips.z.cash/protocol/protocol.pdf#coinbasetransactions>
51    let mut rest = block.transactions.iter().skip(1);
52    if !first.is_coinbase() {
53        Err(TransactionError::CoinbasePosition)?;
54    }
55    // > A transparent input in a non-coinbase transaction MUST NOT have a null prevout
56    //
57    // <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
58    if !rest.all(|tx| tx.is_valid_non_coinbase()) {
59        Err(TransactionError::CoinbaseAfterFirst)?;
60    }
61
62    Ok(first.clone())
63}
64
65/// Returns `Ok(ExpandedDifficulty)` if the`difficulty_threshold` of `header` is at least as difficult as
66/// the target difficulty limit for `network` (PoWLimit)
67///
68/// If the header difficulty threshold is invalid, returns an error containing `height` and `hash`.
69pub fn difficulty_threshold_is_valid(
70    header: &Header,
71    network: &Network,
72    height: &Height,
73    hash: &Hash,
74) -> Result<ExpandedDifficulty, BlockError> {
75    let difficulty_threshold = header
76        .difficulty_threshold
77        .to_expanded()
78        .ok_or(BlockError::InvalidDifficulty(*height, *hash))?;
79
80    // Note: the comparison in this function is a u256 integer comparison, like
81    // zcashd and bitcoin. Greater values represent *less* work.
82
83    // The PowLimit check is part of `Threshold()` in the spec, but it doesn't
84    // actually depend on any previous blocks.
85    if difficulty_threshold > network.target_difficulty_limit() {
86        Err(BlockError::TargetDifficultyLimit(
87            *height,
88            *hash,
89            difficulty_threshold,
90            network.clone(),
91            network.target_difficulty_limit(),
92        ))?;
93    }
94
95    Ok(difficulty_threshold)
96}
97
98/// Returns `Ok(())` if `hash` passes:
99///   - the target difficulty limit for `network` (PoWLimit), and
100///   - the difficulty filter,
101///
102/// based on the fields in `header`.
103///
104/// If the block is invalid, returns an error containing `height` and `hash`.
105pub fn difficulty_is_valid(
106    header: &Header,
107    network: &Network,
108    height: &Height,
109    hash: &Hash,
110) -> Result<(), BlockError> {
111    let difficulty_threshold = difficulty_threshold_is_valid(header, network, height, hash)?;
112
113    // Note: the comparison in this function is a u256 integer comparison, like
114    // zcashd and bitcoin. Greater values represent *less* work.
115
116    // # Consensus
117    //
118    // > The block MUST pass the difficulty filter.
119    //
120    // https://zips.z.cash/protocol/protocol.pdf#blockheader
121    //
122    // The difficulty filter is also context-free.
123    if hash > &difficulty_threshold {
124        Err(BlockError::DifficultyFilter(
125            *height,
126            *hash,
127            difficulty_threshold,
128            network.clone(),
129        ))?;
130    }
131
132    Ok(())
133}
134
135/// Returns `Ok(())` if the `EquihashSolution` is valid for `header`
136pub fn equihash_solution_is_valid(header: &Header) -> Result<(), equihash::Error> {
137    // # Consensus
138    //
139    // > `solution` MUST represent a valid Equihash solution.
140    //
141    // https://zips.z.cash/protocol/protocol.pdf#blockheader
142    header.solution.check(header)
143}
144
145/// Returns `Ok()` with the deferred pool balance change of the coinbase transaction if the block
146/// subsidy in `block` is valid for `network`
147///
148/// See [`zebra_chain::parameters::subsidy::subsidy_is_valid`].
149pub fn subsidy_is_valid(
150    block: &Block,
151    net: &Network,
152    expected_block_subsidy: Amount<NonNegative>,
153) -> Result<DeferredPoolBalanceChange, BlockError> {
154    subsidy::subsidy_is_valid(block, net, expected_block_subsidy).map_err(subsidy_block_error)
155}
156
157/// Returns `Ok(())` if the miner fees consensus rule is valid.
158///
159/// See [`zebra_chain::parameters::subsidy::miner_fees_are_valid`].
160pub fn miner_fees_are_valid(
161    coinbase_tx: &Transaction,
162    height: Height,
163    block_miner_fees: Amount<NonNegative>,
164    expected_block_subsidy: Amount<NonNegative>,
165    expected_deferred_pool_balance_change: DeferredPoolBalanceChange,
166    network: &Network,
167) -> Result<(), BlockError> {
168    subsidy::miner_fees_are_valid(
169        coinbase_tx,
170        height,
171        block_miner_fees,
172        expected_block_subsidy,
173        expected_deferred_pool_balance_change,
174        network,
175    )
176    .map_err(subsidy_block_error)
177}
178
179/// Converts a [`CoinbaseTransactionError`] from the subsidy checks into the [`BlockError`] the
180/// block verifier reports for it.
181fn subsidy_block_error(error: CoinbaseTransactionError) -> BlockError {
182    match error {
183        CoinbaseTransactionError::Subsidy(error) => error.into(),
184        error => BlockError::Other(error.to_string()),
185    }
186}
187
188/// Returns `Ok(())` if `header.time` is less than or equal to
189/// 2 hours in the future, according to the node's local clock (`now`).
190///
191/// This is a non-deterministic rule, as clocks vary over time, and
192/// between different nodes.
193///
194/// "In addition, a full validator MUST NOT accept blocks with nTime
195/// more than two hours in the future according to its clock. This
196/// is not strictly a consensus rule because it is nondeterministic,
197/// and clock time varies between nodes. Also note that a block that
198/// is rejected by this rule at a given point in time may later be
199/// accepted." [ยง7.5][7.5]
200///
201/// [7.5]: https://zips.z.cash/protocol/protocol.pdf#blockheader
202///
203/// If the header time is invalid, returns an error containing `height` and `hash`.
204pub fn time_is_valid_at(
205    header: &Header,
206    now: DateTime<Utc>,
207    height: &Height,
208    hash: &Hash,
209) -> Result<(), zebra_chain::block::BlockTimeError> {
210    header.time_is_valid_at(now, height, hash)
211}
212
213/// Check Merkle root validity.
214///
215/// `transaction_hashes` is a precomputed list of transaction hashes.
216///
217/// # Consensus rules:
218///
219/// - A SHA-256d hash in internal byte order. The merkle root is derived from the
220///   hashes of all transactions included in this block, ensuring that none of
221///   those transactions can be modified without modifying the header. [7.6]
222///
223/// # Panics
224///
225/// - If block does not have a coinbase transaction.
226///
227/// [ZIP-244]: https://zips.z.cash/zip-0244
228/// [7.1]: https://zips.z.cash/protocol/nu5.pdf#txnencodingandconsensus
229/// [7.6]: https://zips.z.cash/protocol/nu5.pdf#blockheader
230pub fn merkle_root_validity(
231    network: &Network,
232    block: &Block,
233    transaction_hashes: &[transaction::Hash],
234) -> Result<(), BlockError> {
235    let merkle_root = transaction_hashes.iter().cloned().collect();
236
237    if block.header.merkle_root != merkle_root {
238        return Err(BlockError::BadMerkleRoot {
239            actual: merkle_root,
240            expected: block.header.merkle_root,
241        });
242    }
243
244    // Bitcoin's transaction Merkle trees are malleable, allowing blocks with
245    // duplicate transactions to have the same Merkle root as blocks without
246    // duplicate transactions.
247    //
248    // Collecting into a HashSet deduplicates, so this checks that there are no
249    // duplicate transaction hashes, preventing Merkle root malleability.
250    //
251    // ## Full Block Validation
252    //
253    // Duplicate transactions should cause a block to be
254    // rejected, as duplicate transactions imply that the block contains a
255    // double-spend. As a defense-in-depth, however, we also check that there
256    // are no duplicate transaction hashes.
257    //
258    // ## Checkpoint Validation
259    //
260    // To prevent malleability (CVE-2012-2459), we also need to check
261    // whether the transaction hashes are unique.
262    if transaction_hashes.len() != transaction_hashes.iter().collect::<HashSet<_>>().len() {
263        return Err(BlockError::DuplicateTransaction);
264    }
265
266    // # Security
267    //
268    // The block's network upgrade comes from its coinbase height, which a peer can rewrite. Check
269    // that the transactions are the ones the header commits to first, so a body that doesn't match
270    // its header is reported as a mismatch, whatever height it claims.
271    //
272    // TODO: deduplicate zebra-chain and zebra-consensus errors (#2908)
273    block
274        .check_transaction_network_upgrade_consistency(network)
275        .map_err(|_| BlockError::WrongTransactionConsensusBranchId)?;
276
277    Ok(())
278}
279
280/// Returns `Ok(())` if `block`'s header commits to `height`, the height in its coinbase input.
281///
282/// The block hash commits to the header, and the header commits to the transaction IDs through
283/// its Merkle root, so callers must also check [`merkle_root_validity()`] before trusting `height`.
284///
285/// Before V5, the coinbase input script that holds the height is part of the transaction ID. From
286/// V5 onward it is authorizing data, which the transaction ID doesn't commit to ([ZIP 244]), so a
287/// peer can rewrite the height without changing the block hash. But a V5 or later transaction ID
288/// commits to the expiry height, which must equal the block height in every valid coinbase that
289/// can have that version:
290///
291/// > [NU5 onward] The nExpiryHeight field of a coinbase transaction MUST be equal to its block
292/// > height.
293///
294/// <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
295///
296/// # Security
297///
298/// This checks every V5 or later coinbase, whatever `height` is. The consensus check in
299/// [`crate::transaction::check::coinbase_expiry_height()`] decides whether the rule applies from
300/// the block height, so it can't check that height. A rewritten NU5 coinbase that claims a pre-NU5
301/// height would skip it, and only be rejected later for its consensus branch ID, an error that
302/// doesn't show the body was forged.
303///
304/// [ZIP 244]: https://zips.z.cash/zip-0244
305pub fn coinbase_height_is_committed(block: &Block, height: Height) -> Result<(), BlockError> {
306    let coinbase = block
307        .transactions
308        .first()
309        .ok_or(BlockError::NoTransactions)?;
310
311    if coinbase.version() < 5 {
312        return Ok(());
313    }
314
315    let expiry_height = coinbase.expiry_height();
316    if expiry_height != Some(height) {
317        return Err(TransactionError::CoinbaseExpiryBlockHeight {
318            expiry_height,
319            block_height: height,
320            transaction_hash: coinbase.hash(),
321        }
322        .into());
323    }
324
325    Ok(())
326}
327
328/// Returns `Ok(())` if `block`'s header commits to its transaction IDs, and to the height in its
329/// coinbase input, if it has one.
330///
331/// A peer that serves a requested block hash can send any body with the header. This shows
332/// whether the body's coinbase height is the block's real height, without any state, so it works
333/// for a block whose parent isn't known. It catches every change to a transaction ID, and a
334/// rewritten height in a V5 or later coinbase. It doesn't check that the block is valid, or catch
335/// other changes to V5 authorizing data, or duplicated transactions, which keep the coinbase.
336///
337/// It hashes the transaction IDs into a Merkle root. The IDs are computed when the block is
338/// deserialized, so this costs much less than deserializing the block. But the block verifiers
339/// compute the same root, so only call it before using a block's height without verifying the
340/// block.
341pub fn body_matches_header(block: &Block) -> Result<(), BlockError> {
342    // A peer can send a body without transactions, which has no Merkle root, so no header can
343    // commit to it.
344    if block.transactions.is_empty() {
345        return Err(BlockError::NoTransactions);
346    }
347
348    let merkle_root = block.transactions.iter().map(|tx| tx.hash()).collect();
349
350    if block.header.merkle_root != merkle_root {
351        return Err(BlockError::BadMerkleRoot {
352            actual: merkle_root,
353            expected: block.header.merkle_root,
354        });
355    }
356
357    match block.coinbase_height() {
358        Some(height) => coinbase_height_is_committed(block, height),
359        None => Ok(()),
360    }
361}
362
363/// Checks the [ZIP 218] per-pool and global shielded action limits for `block`.
364///
365/// # Consensus
366///
367/// > For each block at height `height` where `IsNU7Activated(height)`, the following limits MUST
368/// > be satisfied:
369/// >
370/// > - The total number of Orchard actions across all transactions in the block MUST NOT exceed
371/// >   `OrchardProtocolBlockActionLimit`.
372/// > - The total number of Ironwood actions across all transactions in the block MUST NOT exceed
373/// >   `OrchardProtocolBlockActionLimit`.
374/// > - The total number of Sapling inputs and outputs across all transactions in the block MUST
375/// >   NOT exceed `SaplingBlockIOLimit`.
376/// > - The total number of Sprout JoinSplits across all transactions in the block MUST NOT exceed
377/// >   `SproutBlockJoinSplitLimit`.
378/// >
379/// > In addition to the per-pool limits, the total shielded cost across all pools in a block MUST
380/// > NOT exceed `GlobalShieldedBudget`.
381///
382/// The global shielded cost counts each Sprout JoinSplit twice, because each JoinSplit produces
383/// two shielded outputs.
384///
385/// These limits bound the worst-case block verification time and the worst-case compact sync
386/// bandwidth that lightweight wallets must download, so they are checked before the block's
387/// proofs are queued for verification.
388///
389/// [ZIP 218]: https://zips.z.cash/zip-0218
390pub fn shielded_action_limits_are_valid(
391    block: &Block,
392    network: &Network,
393    height: Height,
394    hash: Hash,
395) -> Result<(), BlockError> {
396    if NetworkUpgrade::current(network, height) < NetworkUpgrade::Nu7 {
397        return Ok(());
398    }
399
400    let counts = block
401        .transactions
402        .iter()
403        .map(|transaction| ShieldedActionCounts::from_transaction(transaction))
404        .fold(ShieldedActionCounts::default(), |acc, counts| {
405            acc.saturating_add(counts)
406        });
407
408    if let Some((pool, count, limit)) = counts.exceeded_limit() {
409        Err(BlockError::TooManyShieldedActions {
410            height,
411            hash,
412            pool,
413            count,
414            limit,
415        })?;
416    }
417
418    Ok(())
419}