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_HEADERS_PER_MESSAGE},
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 /// The serialized size of a block header on Mainnet and Testnet (except Regtest), in bytes:
144 /// the fields before the nonce, the 32-byte nonce, and the length-prefixed solution.
145 pub const SERIALIZED_SIZE: usize = Solution::INPUT_LENGTH + 32 + Solution::SERIALIZED_SIZE;
146
147 /// The serialized size of a block header on Regtest, in bytes:
148 /// the fields before the nonce, the 32-byte nonce, and the length-prefixed solution.
149 pub const REGTEST_SERIALIZED_SIZE: usize =
150 Solution::INPUT_LENGTH + 32 + Solution::REGTEST_SERIALIZED_SIZE;
151
152 /// Returns the size of a serialized block header on `network`, in bytes.
153 ///
154 /// Every header field has a fixed size, except the Equihash solution,
155 /// whose size is constant per network, so this is also constant per network:
156 /// [`Self::REGTEST_SERIALIZED_SIZE`] on Regtest, [`Self::SERIALIZED_SIZE`] everywhere else.
157 pub fn serialized_size(network: &Network) -> usize {
158 if network.is_regtest() {
159 Self::REGTEST_SERIALIZED_SIZE
160 } else {
161 Self::SERIALIZED_SIZE
162 }
163 }
164}
165
166/// A header with a count of the number of transactions in its block.
167/// This structure is used in the Bitcoin network protocol.
168///
169/// The transaction count field is always zero, so we don't store it in the struct.
170#[derive(Clone, Debug, Eq, PartialEq)]
171#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
172pub struct CountedHeader {
173 /// The header for a block
174 pub header: Arc<Header>,
175}
176
177/// The Zcash accepted block version.
178///
179/// The consensus rules do not force the block version to be this value but just equal or greater than it.
180/// However, it is suggested that submitted block versions to be of this exact value.
181pub const ZCASH_BLOCK_VERSION: u32 = 4;
182
183impl TrustedPreallocate for CountedHeader {
184 /// Cap `CountedHeader` preallocation at the existing protocol-level
185 /// constant `MAX_HEADERS_PER_MESSAGE = 160`. The previous return value was
186 /// derived from `MAX_PROTOCOL_MESSAGE_LEN`, allowing peer-controlled
187 /// preallocation amplification — same shape as GHSA-xr93-pcq3-pxf8 for
188 /// `AddrV1`/`AddrV2` (PR #10494).
189 fn max_allocation() -> u64 {
190 // Cast safe: MAX_HEADERS_PER_MESSAGE is the constant 160, which fits
191 // trivially in u64 on every platform.
192 MAX_HEADERS_PER_MESSAGE as u64
193 }
194}