zebra_chain/block/
header.rs

1//! The block header.
2
3use std::sync::Arc;
4
5use chrono::{DateTime, Duration, Utc};
6use thiserror::Error;
7
8use crate::{
9    fmt::HexDebug,
10    parameters::Network,
11    serialization::{TrustedPreallocate, MAX_PROTOCOL_MESSAGE_LEN},
12    work::{difficulty::CompactDifficulty, equihash::Solution},
13};
14
15use super::{merkle, Commitment, CommitmentError, Hash, Height};
16
17#[cfg(any(test, feature = "proptest-impl"))]
18use proptest_derive::Arbitrary;
19
20/// A block header, containing metadata about a block.
21///
22/// How are blocks chained together? They are chained together via the
23/// backwards reference (previous header hash) present in the block
24/// header. Each block points backwards to its parent, all the way
25/// back to the genesis block (the first block in the blockchain).
26#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
27pub struct Header {
28    /// The block's version field. This is supposed to be `4`:
29    ///
30    /// > The current and only defined block version number for Zcash is 4.
31    ///
32    /// but this was not enforced by the consensus rules, and defective mining
33    /// software created blocks with other versions, so instead it's effectively
34    /// a free field. The only constraint is that it must be at least `4` when
35    /// interpreted as an `i32`.
36    pub version: u32,
37
38    /// The hash of the previous block, used to create a chain of blocks back to
39    /// the genesis block.
40    ///
41    /// This ensures no previous block can be changed without also changing this
42    /// block's header.
43    pub previous_block_hash: Hash,
44
45    /// The root of the Bitcoin-inherited transaction Merkle tree, binding the
46    /// block header to the transactions in the block.
47    ///
48    /// Note that because of a flaw in Bitcoin's design, the `merkle_root` does
49    /// not always precisely bind the contents of the block (CVE-2012-2459). It
50    /// is sometimes possible for an attacker to create multiple distinct sets of
51    /// transactions with the same Merkle root, although only one set will be
52    /// valid.
53    pub merkle_root: merkle::Root,
54
55    /// Zcash blocks contain different kinds of commitments to their contents,
56    /// depending on the network and height.
57    ///
58    /// The interpretation of this field has been changed multiple times,
59    /// without incrementing the block [`version`](Self::version). Therefore,
60    /// this field cannot be parsed without the network and height. Use
61    /// [`Block::commitment`](super::Block::commitment) to get the parsed
62    /// [`Commitment`].
63    pub commitment_bytes: HexDebug<[u8; 32]>,
64
65    /// The block timestamp is a Unix epoch time (UTC) when the miner
66    /// started hashing the header (according to the miner).
67    pub time: DateTime<Utc>,
68
69    /// An encoded version of the target threshold this block's header
70    /// hash must be less than or equal to, in the same nBits format
71    /// used by Bitcoin.
72    ///
73    /// For a block at block height `height`, bits MUST be equal to
74    /// `ThresholdBits(height)`.
75    ///
76    /// [Bitcoin-nBits](https://bitcoin.org/en/developer-reference#target-nbits)
77    pub difficulty_threshold: CompactDifficulty,
78
79    /// An arbitrary field that miners can change to modify the header
80    /// hash in order to produce a hash less than or equal to the
81    /// target threshold.
82    pub nonce: HexDebug<[u8; 32]>,
83
84    /// The Equihash solution.
85    pub solution: Solution,
86}
87
88/// TODO: Use this error as the source for zebra_consensus::error::BlockError::Time,
89/// and make `BlockError::Time` add additional context.
90/// See <https://github.com/ZcashFoundation/zebra/issues/1021> for more details.
91#[allow(missing_docs)]
92#[derive(Error, Debug)]
93pub enum BlockTimeError {
94    #[error("invalid time {0:?} in block header {1:?} {2:?}: block time is more than 2 hours in the future ({3:?}). Hint: check your machine's date, time, and time zone.")]
95    InvalidBlockTime(
96        DateTime<Utc>,
97        crate::block::Height,
98        crate::block::Hash,
99        DateTime<Utc>,
100    ),
101}
102
103impl Header {
104    /// TODO: Inline this function into zebra_consensus::block::check::time_is_valid_at.
105    /// See <https://github.com/ZcashFoundation/zebra/issues/1021> for more details.
106    #[allow(clippy::unwrap_in_result)]
107    pub fn time_is_valid_at(
108        &self,
109        now: DateTime<Utc>,
110        height: &Height,
111        hash: &Hash,
112    ) -> Result<(), BlockTimeError> {
113        let two_hours_in_the_future = now
114            .checked_add_signed(Duration::hours(2))
115            .expect("calculating 2 hours in the future does not overflow");
116        if self.time <= two_hours_in_the_future {
117            Ok(())
118        } else {
119            Err(BlockTimeError::InvalidBlockTime(
120                self.time,
121                *height,
122                *hash,
123                two_hours_in_the_future,
124            ))?
125        }
126    }
127
128    /// Get the parsed block [`Commitment`] for this header.
129    /// Its interpretation depends on the given `network` and block `height`.
130    pub fn commitment(
131        &self,
132        network: &Network,
133        height: Height,
134    ) -> Result<Commitment, CommitmentError> {
135        Commitment::from_bytes(*self.commitment_bytes, network, height)
136    }
137
138    /// Compute the hash of this header.
139    pub fn hash(&self) -> Hash {
140        Hash::from(self)
141    }
142}
143
144/// A header with a count of the number of transactions in its block.
145/// This structure is used in the Bitcoin network protocol.
146///
147/// The transaction count field is always zero, so we don't store it in the struct.
148#[derive(Clone, Debug, Eq, PartialEq)]
149#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
150pub struct CountedHeader {
151    /// The header for a block
152    pub header: Arc<Header>,
153}
154
155/// The serialized size of a Zcash block header.
156///
157/// Includes the equihash input, 32-byte nonce, 3-byte equihash length field, and equihash solution.
158const BLOCK_HEADER_LENGTH: usize =
159    crate::work::equihash::Solution::INPUT_LENGTH + 32 + 3 + crate::work::equihash::SOLUTION_SIZE;
160
161/// The minimum size for a serialized CountedHeader.
162///
163/// A CountedHeader has BLOCK_HEADER_LENGTH bytes + 1 or more bytes for the transaction count
164pub(crate) const MIN_COUNTED_HEADER_LEN: usize = BLOCK_HEADER_LENGTH + 1;
165
166/// The Zcash accepted block version.
167///
168/// The consensus rules do not force the block version to be this value but just equal or greater than it.
169/// However, it is suggested that submitted block versions to be of this exact value.
170pub const ZCASH_BLOCK_VERSION: u32 = 4;
171
172impl TrustedPreallocate for CountedHeader {
173    fn max_allocation() -> u64 {
174        // Every vector type requires a length field of at least one byte for de/serialization.
175        // Therefore, we can never receive more than (MAX_PROTOCOL_MESSAGE_LEN - 1) / MIN_COUNTED_HEADER_LEN counted headers in a single message
176        ((MAX_PROTOCOL_MESSAGE_LEN - 1) / MIN_COUNTED_HEADER_LEN) as u64
177    }
178}