Skip to main content

zcash_primitives/
block.rs

1//! Structs and methods for handling Zcash block headers.
2
3// MSRV lints do not recognize the `clippy::io_other_error` lint
4#![allow(unknown_lints)]
5// beta lints attempt to rewrite `corez::io::Error::new` calls to `std::io::Error::other`
6#![allow(clippy::io_other_error)]
7
8use alloc::string::ToString;
9use alloc::vec::Vec;
10use core::fmt;
11use core::ops::Deref;
12use corez::io::{self, ErrorKind, Read, Write};
13use transparent::bundle::OutPoint;
14use zcash_script::{Opcode, opcode::PossiblyBad};
15
16use memuse::DynamicUsage;
17use nonempty::NonEmpty;
18use sha2::{Digest, Sha256};
19
20use zcash_encoding::{Array, CompactSize, ReverseHex, ReverseHexError, Vector};
21use zcash_protocol::consensus::{self, BlockHeight};
22
23use crate::{
24    encoding::{ReadBytesExt, WriteBytesExt},
25    transaction::{Transaction, TxVersion, coinbase::is_coinbase},
26};
27
28pub use equihash;
29
30/// The identifier for a Zcash block.
31///
32/// This is the SHA-256d hash of the encoded [`BlockHeader`].
33#[derive(Clone, Copy, PartialEq, Eq, Hash)]
34pub struct BlockHash(pub [u8; 32]);
35
36memuse::impl_no_dynamic_usage!(BlockHash);
37
38impl fmt::Debug for BlockHash {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        // The (byte-flipped) hex string is more useful than the raw bytes, because we can
41        // look that up in RPC methods and block explorers.
42        let block_hash_str = self.to_string();
43        f.debug_tuple("BlockHash").field(&block_hash_str).finish()
44    }
45}
46
47impl fmt::Display for BlockHash {
48    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
49        formatter.write_str(&ReverseHex::encode(&self.0))
50    }
51}
52
53impl BlockHash {
54    /// Parses a block hash from its byte-reversed hexadecimal representation, as produced by
55    /// this type's [`Display`](fmt::Display) impl and by node RPCs.
56    ///
57    /// # Errors
58    ///
59    /// Returns a [`ReverseHexError`] if the input is not exactly 64 hexadecimal digits.
60    pub fn from_hex(s: &str) -> Result<Self, ReverseHexError> {
61        ReverseHex::decode(s).map(BlockHash)
62    }
63
64    /// Constructs a [`BlockHash`] from the given slice.
65    ///
66    /// # Panics
67    ///
68    /// This function will panic if the slice is not exactly 32 bytes.
69    pub fn from_slice(bytes: &[u8]) -> Self {
70        Self::try_from_slice(bytes).unwrap()
71    }
72
73    /// Constructs a [`BlockHash`] from the given slice.
74    ///
75    /// Returns `None` if `bytes` has any length other than 32
76    pub fn try_from_slice(bytes: &[u8]) -> Option<Self> {
77        if bytes.len() == 32 {
78            let mut hash = [0; 32];
79            hash.copy_from_slice(bytes);
80            Some(BlockHash(hash))
81        } else {
82            None
83        }
84    }
85}
86
87/// A Zcash block header.
88#[derive(Debug)]
89pub struct BlockHeader {
90    hash: BlockHash,
91    data: BlockHeaderData,
92}
93
94impl Deref for BlockHeader {
95    type Target = BlockHeaderData;
96
97    fn deref(&self) -> &BlockHeaderData {
98        &self.data
99    }
100}
101
102/// The information contained in a Zcash block header.
103#[derive(Debug)]
104pub struct BlockHeaderData {
105    pub version: i32,
106    pub prev_block: BlockHash,
107    pub merkle_root: [u8; 32],
108    pub final_sapling_root: [u8; 32],
109    pub time: u32,
110    pub bits: u32,
111    pub nonce: [u8; 32],
112    pub solution: Vec<u8>,
113}
114
115impl BlockHeaderData {
116    pub fn freeze(self) -> io::Result<BlockHeader> {
117        BlockHeader::from_data(self)
118    }
119}
120
121impl BlockHeader {
122    fn from_data(data: BlockHeaderData) -> io::Result<Self> {
123        let mut header = BlockHeader {
124            hash: BlockHash([0; 32]),
125            data,
126        };
127        let mut raw = vec![];
128        header.write(&mut raw)?;
129        header
130            .hash
131            .0
132            .copy_from_slice(&Sha256::digest(Sha256::digest(&raw)));
133        Ok(header)
134    }
135
136    /// Returns the hash of this header.
137    pub fn hash(&self) -> BlockHash {
138        self.hash
139    }
140
141    pub fn read<R: Read>(mut reader: R) -> io::Result<Self> {
142        let version = reader.read_i32_le()?;
143
144        let mut prev_block = BlockHash([0; 32]);
145        reader.read_exact(&mut prev_block.0)?;
146
147        let mut merkle_root = [0; 32];
148        reader.read_exact(&mut merkle_root)?;
149
150        let mut final_sapling_root = [0; 32];
151        reader.read_exact(&mut final_sapling_root)?;
152
153        let time = reader.read_u32_le()?;
154        let bits = reader.read_u32_le()?;
155
156        let mut nonce = [0; 32];
157        reader.read_exact(&mut nonce)?;
158
159        let solution = Vector::read_bytes(&mut reader)?;
160
161        BlockHeader::from_data(BlockHeaderData {
162            version,
163            prev_block,
164            merkle_root,
165            final_sapling_root,
166            time,
167            bits,
168            nonce,
169            solution,
170        })
171    }
172
173    pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> {
174        writer.write_i32_le(self.version)?;
175        writer.write_all(&self.prev_block.0)?;
176        writer.write_all(&self.merkle_root)?;
177        writer.write_all(&self.final_sapling_root)?;
178        writer.write_u32_le(self.time)?;
179        writer.write_u32_le(self.bits)?;
180        writer.write_all(&self.nonce)?;
181        Vector::write_bytes(&mut writer, &self.solution)?;
182
183        Ok(())
184    }
185}
186
187/// A Zcash block.
188#[derive(Debug)]
189pub struct Block {
190    header: BlockHeader,
191    vtx: NonEmpty<Transaction>,
192    claimed_height: BlockHeight,
193}
194
195impl Block {
196    /// Parses a block from bytes.
197    ///
198    /// Limitation: currently this method returns an error if given a genesis block.
199    pub fn read<R: Read, P: consensus::Parameters>(mut reader: R, params: &P) -> io::Result<Self> {
200        let header = BlockHeader::read(&mut reader)?;
201
202        // Instead of using `Vector::read`, we manually read the length, so we can then
203        // individually read the coinbase transaction before the rest.
204        let n_tx: usize = CompactSize::read_t(&mut reader)?;
205        if n_tx == 0 {
206            return Err(corez::io::Error::new(
207                ErrorKind::Other,
208                "block has no coinbase tx",
209            ));
210        }
211
212        // Parse with an arbitrary consensus branch ID initially; we will fix it later.
213        let coinbase = Transaction::read(&mut reader, consensus::BranchId::Sprout)?;
214
215        // Extract the claimed block height from the coinbase transaction.
216        let claimed_height = {
217            let coinbase_transparent = coinbase
218                .transparent_bundle()
219                .filter(|_| is_coinbase(&coinbase))
220                .ok_or_else(|| {
221                    corez::io::Error::new(ErrorKind::Other, "first tx of block is not coinbase")
222                })?;
223
224            // Verify some simple structural consensus rules on the coinbase transaction.
225            if coinbase.sprout_bundle().is_some() {
226                return Err(corez::io::Error::new(
227                    ErrorKind::Other,
228                    "coinbase tx has sprout data",
229                ));
230            }
231
232            let coinbase_txin = coinbase_transparent.vin.first().expect("checked above");
233
234            match coinbase_txin.script_sig().0.parse().next() {
235                Some(Ok(PossiblyBad::Good(Opcode::PushValue(height)))) => height
236                    .to_num()
237                    .map_err(|_| {
238                        corez::io::Error::new(
239                            ErrorKind::Other,
240                            "coinbase input specifies an invalid block height",
241                        )
242                    })
243                    .and_then(|h| {
244                        BlockHeight::try_from(h).map_err(|_| {
245                            corez::io::Error::new(
246                                ErrorKind::Other,
247                                "coinbase input specifies an invalid block height",
248                            )
249                        })
250                    }),
251                // TODO: Permit missing height in genesis blocks by matching their block
252                // hash against the provided params.
253                _ => Err(corez::io::Error::new(
254                    ErrorKind::Other,
255                    "coinbase scriptSig missing height",
256                )),
257            }?
258        };
259
260        // Fix the coinbase tx's consensus branch ID if necessary.
261        let consensus_branch_id = consensus::BranchId::for_height(params, claimed_height);
262        let coinbase = match coinbase.version() {
263            TxVersion::Sprout(_) | TxVersion::V3 | TxVersion::V4 => coinbase
264                .into_data()
265                .fix_consensus_branch_id(consensus_branch_id)
266                .freeze()
267                .expect("valid"),
268            // All later tx versions directly commit to the consensus branch ID.
269            _ => {
270                if coinbase.consensus_branch_id() != consensus_branch_id {
271                    return Err(corez::io::Error::new(
272                        ErrorKind::Other,
273                        "coinbase tx's claimed height doesn't match its consensus branch ID for given network parameters",
274                    ));
275                }
276                coinbase
277            }
278        };
279
280        // Now parse the rest of the transactions with the expected consensus branch ID.
281        let mut non_coinbase = Array::read(&mut reader, n_tx - 1, |r| {
282            Transaction::read(r, consensus_branch_id)
283        })?;
284
285        // Verify some simple structural consensus rules on the non-coinbase transactions.
286        if non_coinbase
287            .iter()
288            .flat_map(|tx| tx.transparent_bundle())
289            .flat_map(|b| &b.vin)
290            .any(|txin| txin.prevout() == &OutPoint::NULL)
291        {
292            return Err(corez::io::Error::new(
293                ErrorKind::Other,
294                "non-coinbase tx has null transparent input",
295            ));
296        }
297
298        let mut vtx = NonEmpty::singleton(coinbase);
299        vtx.append(&mut non_coinbase);
300
301        Ok(Self {
302            header,
303            vtx,
304            claimed_height,
305        })
306    }
307
308    /// Writes the block to the given writer.
309    pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> {
310        self.header.write(&mut writer)?;
311        Vector::write_nonempty(&mut writer, &self.vtx, |w, tx| tx.write(w))?;
312        Ok(())
313    }
314
315    /// Constructs a block from its component parts.
316    ///
317    /// This does not validate any consensus rules; in particular, `claimed_height` is not
318    /// checked against the height encoded in the coinbase transaction. It is intended for
319    /// use in constructing test blocks.
320    #[cfg(feature = "test-dependencies")]
321    pub fn from_parts(
322        header: BlockHeader,
323        vtx: NonEmpty<Transaction>,
324        claimed_height: BlockHeight,
325    ) -> Self {
326        Block {
327            header,
328            vtx,
329            claimed_height,
330        }
331    }
332
333    /// Breaks this block into its component parts for further processing.
334    pub fn into_parts(self) -> (BlockHeader, NonEmpty<Transaction>) {
335        (self.header, self.vtx)
336    }
337
338    /// Returns the block's header.
339    pub fn header(&self) -> &BlockHeader {
340        &self.header
341    }
342
343    /// Returns the block's transactions, in consensus order (the order they are encoded
344    /// in the block and applied to chain state).
345    ///
346    /// The first transaction is always the coinbase transaction.
347    pub fn vtx(&self) -> &NonEmpty<Transaction> {
348        &self.vtx
349    }
350
351    /// Returns the claimed height of this block.
352    ///
353    /// This is a "claimed height" for two reasons:
354    /// - It is the value recorded in the `scriptSig` of the coinbase transaction's null
355    ///   transparent input, and thus can only be trusted if the block has been fully
356    ///   validated in the context of a chain.
357    /// - Blocks not in the main chain **do not have heights** (because heights are by
358    ///   definition measured with respect to the longest chain). This value can only be
359    ///   used as a "height" if the block is verified to be currently in the main chain.
360    pub fn claimed_height(&self) -> BlockHeight {
361        self.claimed_height
362    }
363}
364
365#[cfg(any(test, feature = "test-dependencies"))]
366pub mod testing {
367    use proptest::prelude::*;
368
369    use super::BlockHash;
370
371    /// Generates arbitrary block hashes.
372    pub fn arb_block_hash() -> impl Strategy<Value = BlockHash> {
373        any::<[u8; 32]>().prop_map(BlockHash)
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use alloc::string::ToString;
380    use alloc::vec::Vec;
381
382    use proptest::prelude::*;
383    use zcash_protocol::consensus::MAIN_NETWORK;
384
385    use super::{Block, BlockHash, BlockHeader, testing::arb_block_hash};
386
387    const BLOCK_MAINNET_415000: [u8; 1640] = [
388        0x04, 0x00, 0x00, 0x00, 0x52, 0x74, 0xb4, 0x3b, 0x9e, 0x4a, 0xd8, 0xf4, 0x3e, 0x93, 0xf7,
389        0x84, 0x63, 0xd2, 0x4d, 0xcf, 0xe5, 0x31, 0xae, 0xb4, 0x71, 0x98, 0x19, 0xf4, 0xf9, 0x7f,
390        0x7e, 0x03, 0x00, 0x00, 0x00, 0x00, 0x66, 0x30, 0x73, 0xbc, 0x4b, 0xfa, 0x95, 0xc9, 0xbe,
391        0xc3, 0x6a, 0xad, 0x72, 0x68, 0xa5, 0x73, 0x04, 0x97, 0x97, 0xbd, 0xfc, 0x5a, 0xa4, 0xc7,
392        0x43, 0xfb, 0xe4, 0x82, 0x0a, 0xa3, 0x93, 0xce, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
393        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
394        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa8, 0xbe, 0xcc, 0x5b, 0xe1,
395        0xab, 0x03, 0x1c, 0xc2, 0xfd, 0x60, 0x7c, 0x77, 0x6a, 0x7a, 0x00, 0x00, 0x00, 0x00, 0x00,
396        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
397        0x00, 0x3e, 0xb2, 0x18, 0x19, 0xfd, 0x40, 0x05, 0x00, 0x94, 0x9d, 0x55, 0xde, 0x0c, 0xc6,
398        0x33, 0xe0, 0xcc, 0xe4, 0x1e, 0x46, 0x49, 0xef, 0x4a, 0xa3, 0x34, 0x9f, 0x01, 0x00, 0x29,
399        0x0f, 0xfe, 0x28, 0x1b, 0x94, 0x7b, 0x3b, 0x53, 0xfb, 0xd2, 0xf3, 0x5b, 0x1c, 0xe2, 0x92,
400        0x64, 0x9b, 0x96, 0xac, 0x6e, 0x08, 0x83, 0xaf, 0x3a, 0x68, 0x44, 0xb9, 0x55, 0x92, 0xe7,
401        0x45, 0x56, 0xda, 0x34, 0x4b, 0x47, 0x01, 0x96, 0x1c, 0xd4, 0x13, 0x0c, 0x68, 0x21, 0x9c,
402        0xfa, 0x13, 0x41, 0xd5, 0xaf, 0xb5, 0x04, 0x9e, 0xb0, 0xe8, 0xbe, 0x4a, 0x2d, 0x92, 0xd6,
403        0x78, 0xc4, 0x07, 0x85, 0xe3, 0x37, 0x05, 0x54, 0x8b, 0x5f, 0x3a, 0x54, 0xf0, 0xa4, 0xc3,
404        0x9a, 0x2f, 0x58, 0xee, 0x78, 0x4a, 0x24, 0x16, 0x3c, 0xd8, 0x6f, 0x54, 0x81, 0x23, 0x27,
405        0xdf, 0x55, 0xe1, 0xd5, 0x5c, 0xa8, 0x4b, 0x6e, 0x7b, 0x88, 0x7a, 0x7c, 0xbf, 0xb9, 0x09,
406        0x1a, 0x58, 0x5b, 0xdb, 0x8e, 0xa4, 0x75, 0x93, 0x07, 0xc5, 0x6c, 0x1b, 0x3d, 0xaf, 0xc6,
407        0x69, 0x24, 0x5a, 0x6f, 0x65, 0x4b, 0x6f, 0x73, 0x00, 0x52, 0x26, 0x6a, 0x01, 0xad, 0x4f,
408        0x9c, 0x0b, 0x59, 0xed, 0x4e, 0x17, 0x71, 0x2b, 0x3e, 0x72, 0xdf, 0x04, 0x98, 0xaa, 0x8d,
409        0xe4, 0x88, 0x8f, 0x99, 0x35, 0x31, 0xc6, 0x0a, 0xcd, 0xed, 0x1d, 0x4b, 0x66, 0xe8, 0x9d,
410        0xe0, 0xb6, 0x48, 0x2c, 0xcc, 0xd4, 0xa7, 0x12, 0xf5, 0xcf, 0x9d, 0x4c, 0xa8, 0x3b, 0xe0,
411        0xf9, 0x22, 0xde, 0x2c, 0x1d, 0xbb, 0x3a, 0x14, 0x07, 0x48, 0x0d, 0xbe, 0x87, 0x95, 0x99,
412        0x3d, 0x8b, 0xe6, 0x40, 0x98, 0x8a, 0xbf, 0xe7, 0xa8, 0xa1, 0xb3, 0x3a, 0x12, 0x13, 0x1c,
413        0x45, 0x1e, 0x1a, 0xbc, 0x0d, 0x83, 0xfb, 0x85, 0x18, 0x62, 0xc6, 0x37, 0xce, 0x72, 0x4d,
414        0x5f, 0xe9, 0x7a, 0xa9, 0xa8, 0x06, 0xcf, 0x34, 0xba, 0xb5, 0x09, 0xf4, 0x55, 0x4b, 0x0c,
415        0xd1, 0x0a, 0x7d, 0xdf, 0xd5, 0x82, 0x1b, 0x09, 0x1a, 0xd2, 0xc9, 0x0c, 0x1a, 0xa1, 0xd8,
416        0x1e, 0xb3, 0xd7, 0x2d, 0xb4, 0x19, 0x93, 0xb6, 0x48, 0xf4, 0x1e, 0x21, 0x38, 0xff, 0x95,
417        0x31, 0xa3, 0x0f, 0xf7, 0x3b, 0x22, 0x14, 0x0e, 0x4e, 0xbd, 0x7b, 0xaa, 0x33, 0x84, 0x8e,
418        0x51, 0x2d, 0x99, 0x30, 0x0c, 0x5c, 0x13, 0x1c, 0x6e, 0x75, 0xf5, 0x71, 0x4a, 0x5c, 0x6d,
419        0xcb, 0x17, 0x8b, 0x4a, 0x49, 0x78, 0xda, 0xc8, 0x3a, 0xd4, 0x12, 0xfb, 0xd6, 0x92, 0x01,
420        0x92, 0x50, 0xc5, 0x53, 0x04, 0x9a, 0xad, 0x45, 0x79, 0x84, 0xbe, 0xdf, 0xc9, 0x6a, 0xe7,
421        0x01, 0xc6, 0x59, 0xbc, 0x70, 0x07, 0xa9, 0x7d, 0x0a, 0x90, 0x02, 0xb9, 0x45, 0xbd, 0xec,
422        0x45, 0xa9, 0x45, 0xef, 0x62, 0x85, 0xb2, 0xcd, 0x55, 0x3b, 0x4c, 0x09, 0xd9, 0x07, 0xc6,
423        0x27, 0x86, 0x3f, 0x03, 0x99, 0xe8, 0x72, 0x5b, 0x4f, 0xf7, 0xfc, 0x59, 0x79, 0xe3, 0xcf,
424        0xf2, 0x28, 0x14, 0x50, 0x84, 0x48, 0xef, 0x8b, 0x98, 0x31, 0xc2, 0x85, 0x95, 0x93, 0x33,
425        0x39, 0x6a, 0xa3, 0x62, 0xa5, 0x1c, 0xf2, 0x05, 0x09, 0x7a, 0xfa, 0xbe, 0xc1, 0x5e, 0x41,
426        0xfb, 0x6e, 0x30, 0xb6, 0x22, 0x37, 0x4b, 0xf5, 0x8b, 0x37, 0xef, 0x9d, 0x1b, 0x24, 0x1e,
427        0xad, 0x5a, 0x68, 0x2b, 0x98, 0xb6, 0x57, 0x49, 0xa5, 0x75, 0x68, 0xe2, 0x38, 0xd5, 0x0a,
428        0xfd, 0x41, 0x7e, 0x1e, 0x96, 0x0e, 0x7b, 0x5a, 0x06, 0x4f, 0xd9, 0xf6, 0x94, 0xd7, 0x83,
429        0xa2, 0xcb, 0xcd, 0x58, 0x55, 0x2d, 0xed, 0xbb, 0x9e, 0x5e, 0x11, 0x23, 0x67, 0x4e, 0xf7,
430        0x3a, 0x52, 0x41, 0x96, 0xcf, 0x05, 0xd3, 0xe5, 0x24, 0x66, 0x05, 0x49, 0xff, 0xe7, 0xbd,
431        0x65, 0x68, 0x05, 0x71, 0x35, 0xff, 0xd5, 0xaf, 0xd9, 0x43, 0xf6, 0xda, 0x11, 0xcb, 0xb5,
432        0x97, 0xe8, 0xcc, 0xec, 0xd7, 0x7e, 0xcb, 0xe9, 0x09, 0xde, 0x06, 0x31, 0xbf, 0xa2, 0x9c,
433        0xd3, 0xe3, 0xd5, 0x54, 0x46, 0x71, 0xba, 0x80, 0x25, 0x61, 0x53, 0xd6, 0xe9, 0x99, 0x0b,
434        0x88, 0xad, 0x8e, 0x0c, 0xf4, 0x98, 0x9b, 0xef, 0x4b, 0xe4, 0x57, 0xf9, 0xc7, 0xb0, 0xf1,
435        0xaa, 0xcd, 0x6e, 0x0e, 0xf3, 0x20, 0x60, 0x5c, 0x29, 0xed, 0x0c, 0xd2, 0xeb, 0x6c, 0xfc,
436        0xe2, 0x16, 0xc5, 0x2a, 0x31, 0x75, 0x80, 0x20, 0x1c, 0xad, 0x7a, 0x09, 0x43, 0xd2, 0x4b,
437        0x7b, 0x06, 0xd5, 0xbf, 0x75, 0x87, 0x61, 0xdd, 0x96, 0xe1, 0x19, 0x70, 0xb5, 0xde, 0xd6,
438        0x97, 0x22, 0x2b, 0x2c, 0x77, 0xe7, 0xf2, 0x56, 0xa6, 0x05, 0xac, 0x75, 0x55, 0x49, 0xc1,
439        0x65, 0x1f, 0x25, 0xad, 0xfc, 0x9d, 0x53, 0xd9, 0x11, 0x7e, 0x3a, 0x0b, 0xb4, 0x09, 0xee,
440        0xe4, 0xa6, 0x00, 0x12, 0x04, 0x72, 0x94, 0x9c, 0x7d, 0xda, 0x1c, 0x2e, 0xdb, 0x3c, 0x33,
441        0x0c, 0x7f, 0x96, 0x17, 0x99, 0x82, 0x91, 0x64, 0x57, 0xd3, 0x31, 0xe9, 0x63, 0x09, 0xdd,
442        0x24, 0xdf, 0x74, 0xee, 0xdd, 0x00, 0xe7, 0xdb, 0x49, 0x7e, 0xe1, 0x30, 0xf7, 0x7d, 0xe6,
443        0x66, 0xeb, 0x55, 0x7f, 0xb3, 0x16, 0xe8, 0x7a, 0xda, 0xf1, 0x81, 0x3c, 0xe4, 0x26, 0xa4,
444        0x58, 0xa6, 0xee, 0xe3, 0xa8, 0x5b, 0x2a, 0xb8, 0x8f, 0x65, 0x53, 0xaa, 0xda, 0xe8, 0xde,
445        0x65, 0x2e, 0x21, 0x1a, 0x1d, 0x9f, 0x33, 0x4d, 0x59, 0x6b, 0x5e, 0xb6, 0x17, 0x34, 0x07,
446        0xef, 0xcc, 0x2e, 0x81, 0x54, 0xbb, 0x9c, 0xa1, 0x21, 0x2a, 0xa9, 0xa1, 0xa1, 0x12, 0x1d,
447        0x2f, 0x5a, 0x77, 0x12, 0xcf, 0x25, 0xcc, 0x81, 0x48, 0xb8, 0x05, 0x2e, 0x0d, 0x2e, 0x09,
448        0xf2, 0x0e, 0x5b, 0xa2, 0xa9, 0x82, 0x77, 0xe9, 0x75, 0xb0, 0xee, 0xd9, 0xa8, 0x92, 0x06,
449        0x96, 0x63, 0x37, 0x16, 0x3f, 0x21, 0x5c, 0x9d, 0x04, 0xa6, 0x59, 0x8b, 0x09, 0x58, 0xd3,
450        0x33, 0xd8, 0x46, 0x77, 0x3c, 0x69, 0xe5, 0xab, 0xfd, 0x0a, 0x04, 0x27, 0xf3, 0x66, 0x06,
451        0x14, 0xdd, 0x82, 0xb7, 0x9a, 0xdb, 0x85, 0x1a, 0x0d, 0x58, 0xb6, 0x2d, 0xf5, 0xf0, 0xb3,
452        0xac, 0x83, 0x6e, 0x6e, 0x25, 0xf3, 0xa5, 0x1f, 0x49, 0xa9, 0x9a, 0xde, 0x57, 0x79, 0x6f,
453        0xe9, 0xfc, 0xc2, 0x6f, 0x0a, 0x1f, 0x94, 0xff, 0x08, 0x19, 0xfe, 0x52, 0xb7, 0x50, 0x87,
454        0xed, 0xbe, 0xd3, 0xa8, 0x16, 0x26, 0xeb, 0x54, 0x16, 0xc6, 0x65, 0x57, 0xf1, 0x1c, 0x0f,
455        0xce, 0xdf, 0xf2, 0x23, 0xd6, 0xaa, 0x8c, 0xd5, 0xc3, 0x53, 0x86, 0xe5, 0xb4, 0xb9, 0x5a,
456        0x0f, 0x03, 0x92, 0xca, 0x30, 0x1a, 0x38, 0xb3, 0x68, 0x7d, 0x09, 0x44, 0x93, 0xb9, 0xe9,
457        0xd2, 0x64, 0xd0, 0x7a, 0x19, 0x0c, 0xe5, 0x7d, 0x11, 0x68, 0x04, 0x38, 0x2a, 0x3f, 0xab,
458        0xe1, 0x5a, 0xf4, 0xdf, 0x4f, 0xa0, 0x43, 0xf0, 0x28, 0x7a, 0xa1, 0xed, 0x55, 0x68, 0xd9,
459        0xef, 0x5d, 0x12, 0x51, 0x0d, 0x01, 0x0c, 0xcd, 0xab, 0x4e, 0xb6, 0x16, 0xf6, 0xdf, 0x13,
460        0xbb, 0x31, 0x26, 0xef, 0x43, 0xd9, 0xd6, 0x57, 0x35, 0xe4, 0xe4, 0xc0, 0x4b, 0x57, 0x63,
461        0x48, 0xd0, 0x40, 0xb5, 0x35, 0x05, 0x5a, 0x3d, 0x5a, 0xe1, 0x91, 0xb7, 0x5f, 0x06, 0x12,
462        0xf3, 0xb2, 0x40, 0x66, 0xa0, 0x52, 0x45, 0xf2, 0x7f, 0xe5, 0x7b, 0xda, 0x66, 0xbd, 0x6d,
463        0xec, 0x7e, 0x4f, 0xc9, 0xcb, 0x23, 0x68, 0x02, 0x06, 0x2a, 0xdd, 0xe3, 0xcd, 0x0e, 0x31,
464        0x34, 0x82, 0xc9, 0x2a, 0x0c, 0x72, 0x11, 0x02, 0xb1, 0xf3, 0x8b, 0x01, 0x5a, 0xb8, 0xd0,
465        0x15, 0x59, 0xcb, 0xcb, 0x40, 0xf6, 0x74, 0xe9, 0xef, 0xad, 0x5e, 0xe9, 0xc2, 0xfe, 0x13,
466        0x3f, 0xaa, 0x55, 0xca, 0x1d, 0xd0, 0xff, 0x26, 0x71, 0x0f, 0x9d, 0xa8, 0x19, 0xcc, 0x14,
467        0x59, 0xcb, 0x7e, 0xd2, 0x60, 0xda, 0xd3, 0xdb, 0x05, 0x96, 0x25, 0x8d, 0x47, 0xc7, 0x4c,
468        0x32, 0xa8, 0xb8, 0x52, 0xb6, 0x71, 0xc5, 0xa0, 0xca, 0xa2, 0x00, 0x16, 0x03, 0xd9, 0x0c,
469        0x91, 0xa7, 0xdf, 0x2e, 0x2d, 0x4e, 0xe9, 0xae, 0x9b, 0xf1, 0xa6, 0xb1, 0xec, 0x88, 0x15,
470        0x1c, 0x62, 0x36, 0x0d, 0x03, 0x02, 0x4d, 0x2e, 0x2d, 0x01, 0x14, 0x08, 0x4f, 0x6b, 0x88,
471        0xc5, 0xbb, 0xa2, 0x4a, 0xa7, 0xce, 0xcf, 0xac, 0x16, 0xe9, 0x1e, 0x0b, 0xaf, 0x3d, 0x86,
472        0x53, 0xe2, 0x18, 0x09, 0x3e, 0x81, 0xd2, 0xa6, 0x3c, 0x32, 0xef, 0xf1, 0xd9, 0x03, 0x0f,
473        0x9e, 0x14, 0x14, 0xec, 0xe4, 0x20, 0xda, 0xa2, 0x4e, 0x0d, 0xd5, 0xb8, 0x45, 0xb3, 0x27,
474        0x4b, 0xb8, 0x39, 0xca, 0x1c, 0x53, 0xbc, 0xc0, 0x19, 0x42, 0x42, 0xd7, 0x4b, 0x26, 0x31,
475        0xb9, 0x49, 0x5a, 0x65, 0x4f, 0xbb, 0xdc, 0xbf, 0xad, 0x77, 0x9f, 0x73, 0x22, 0xb6, 0x07,
476        0x36, 0x24, 0x98, 0x80, 0x60, 0x48, 0x21, 0xd9, 0x69, 0x24, 0xe3, 0xfa, 0x39, 0x7f, 0x35,
477        0x4a, 0x5e, 0xcc, 0xa3, 0x4f, 0x61, 0x4d, 0xa5, 0x45, 0x6f, 0x9b, 0x36, 0x33, 0x8c, 0x37,
478        0xd8, 0xf6, 0xfb, 0xf6, 0x26, 0xbe, 0x98, 0x34, 0x77, 0x76, 0x60, 0x22, 0x87, 0x27, 0x46,
479        0xda, 0x10, 0xa1, 0x77, 0x1c, 0xeb, 0x02, 0xdd, 0x8a, 0xac, 0x01, 0xba, 0x18, 0x6b, 0xf1,
480        0x48, 0x86, 0x30, 0x47, 0x9e, 0x12, 0x84, 0xda, 0x01, 0x90, 0xfc, 0xe8, 0xb5, 0x9a, 0xc6,
481        0xb0, 0xfd, 0x41, 0x6b, 0xee, 0x56, 0xb7, 0x2f, 0x0a, 0x58, 0x45, 0x15, 0x35, 0x57, 0xff,
482        0x0f, 0x49, 0x50, 0xa0, 0xdc, 0x5b, 0xe6, 0x5c, 0xe9, 0x42, 0xd2, 0x2e, 0x18, 0x53, 0x4c,
483        0x4e, 0x0e, 0xfa, 0xbb, 0x2d, 0x15, 0x25, 0xdc, 0x48, 0x58, 0xb9, 0xb0, 0xf7, 0x7d, 0x47,
484        0x4a, 0x12, 0x5e, 0xbc, 0x25, 0x0e, 0x08, 0xfe, 0xdb, 0xfa, 0xa6, 0x6f, 0x45, 0x3d, 0x90,
485        0x93, 0x2c, 0xab, 0x3f, 0xf4, 0x52, 0x21, 0x90, 0x99, 0x68, 0xe5, 0x1e, 0x6b, 0xc2, 0x54,
486        0xd5, 0x09, 0xad, 0xeb, 0x75, 0xcb, 0xa7, 0x6d, 0x48, 0xfe, 0x02, 0x4e, 0x3e, 0x66, 0xd8,
487        0xdf, 0x5e, 0x01, 0x03, 0x00, 0x00, 0x80, 0x70, 0x82, 0xc4, 0x03, 0x01, 0x00, 0x00, 0x00,
488        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
489        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff,
490        0xff, 0xff, 0xff, 0x1a, 0x03, 0x18, 0x55, 0x06, 0x15, 0x2f, 0x56, 0x69, 0x61, 0x42, 0x54,
491        0x43, 0x2f, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21, 0x2f,
492        0xff, 0xff, 0xff, 0xff, 0x02, 0x00, 0xca, 0x9a, 0x3b, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76,
493        0xa9, 0x14, 0xfb, 0x8a, 0x6a, 0x4c, 0x11, 0xcb, 0x21, 0x6c, 0xe2, 0x1f, 0x9f, 0x37, 0x1d,
494        0xfc, 0x92, 0x71, 0xa4, 0x69, 0xbd, 0x6d, 0x88, 0xac, 0x80, 0xb2, 0xe6, 0x0e, 0x00, 0x00,
495        0x00, 0x00, 0x17, 0xa9, 0x14, 0xe0, 0xa5, 0xea, 0x13, 0x40, 0xcc, 0x6b, 0x1d, 0x6a, 0x82,
496        0xc0, 0x6c, 0x0a, 0x9c, 0x60, 0xb9, 0x89, 0x8b, 0x6a, 0xe9, 0x87, 0x00, 0x00, 0x00, 0x00,
497        0x00, 0x00, 0x00, 0x00, 0x00,
498    ];
499
500    #[test]
501    fn header_read_write() {
502        let header_mainnet_415000 = &BLOCK_MAINNET_415000[..1487];
503
504        let header = BlockHeader::read(header_mainnet_415000).unwrap();
505        assert_eq!(
506            format!("{}", header.hash()),
507            "0000000001ab37793ce771262b2ffa082519aa3fe891250a1adb43baaf856168"
508        );
509        let mut encoded = Vec::with_capacity(header_mainnet_415000.len());
510        header.write(&mut encoded).unwrap();
511        assert_eq!(header_mainnet_415000, &encoded[..]);
512    }
513
514    #[test]
515    fn block_read_write() {
516        let block = Block::read(&BLOCK_MAINNET_415000[..], &MAIN_NETWORK).unwrap();
517        assert_eq!(
518            format!("{}", block.header().hash()),
519            "0000000001ab37793ce771262b2ffa082519aa3fe891250a1adb43baaf856168"
520        );
521        assert_eq!(block.claimed_height(), 415000.into());
522        assert_eq!(block.vtx().len(), 1);
523
524        let mut encoded = Vec::with_capacity(BLOCK_MAINNET_415000.len());
525        block.write(&mut encoded).unwrap();
526        assert_eq!(&BLOCK_MAINNET_415000[..], &encoded[..]);
527    }
528
529    #[test]
530    fn block_hash_from_hex() {
531        /// The byte-reversed hex hash of [`BLOCK_MAINNET_415000`], as reported by node RPCs.
532        const BLOCK_MAINNET_415000_HASH_HEX: &str =
533            "0000000001ab37793ce771262b2ffa082519aa3fe891250a1adb43baaf856168";
534
535        let header = BlockHeader::read(&BLOCK_MAINNET_415000[..]).unwrap();
536        assert_eq!(
537            BlockHash::from_hex(BLOCK_MAINNET_415000_HASH_HEX),
538            Ok(header.hash())
539        );
540        assert_eq!(
541            BlockHash::from_hex(&BLOCK_MAINNET_415000_HASH_HEX.to_uppercase()),
542            Ok(header.hash())
543        );
544        assert!(BlockHash::from_hex(&BLOCK_MAINNET_415000_HASH_HEX[1..]).is_err());
545        assert!(BlockHash::from_hex(&"zz".repeat(32)).is_err());
546    }
547
548    proptest! {
549        #[test]
550        fn block_hash_from_hex_inverts_display(hash in arb_block_hash()) {
551            prop_assert_eq!(BlockHash::from_hex(&hash.to_string()), Ok(hash));
552        }
553    }
554}