1use std::fmt;
23use std::fmt::{Formatter, LowerHex};
24use std::str::FromStr;
25
26use amplify::hex::{FromHex, ToHex};
27use amplify::{ByteArray, Bytes32StrRev, Wrapper};
28use commit_verify::{DigestExt, Sha256};
29
30use crate::{BlockDataParseError, ConsensusDecode, ConsensusEncode, LIB_NAME_BITCOIN};
31
32#[derive(Wrapper, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, From)]
33#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
34#[strict_type(lib = LIB_NAME_BITCOIN)]
35#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(transparent))]
36#[wrapper(BorrowSlice, Index, RangeOps, Debug, Hex, Display, FromStr)]
37pub struct BlockHash(
38 #[from]
39 #[from([u8; 32])]
40 Bytes32StrRev,
41);
42
43#[derive(Wrapper, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, From)]
44#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
45#[strict_type(lib = LIB_NAME_BITCOIN)]
46#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(transparent))]
47#[wrapper(BorrowSlice, Index, RangeOps, Debug, Hex, Display, FromStr)]
48pub struct BlockMerkleRoot(
49 #[from]
50 #[from([u8; 32])]
51 Bytes32StrRev,
52);
53
54#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display)]
55#[display(LowerHex)]
56#[derive(StrictType, StrictEncode, StrictDecode, StrictDumb)]
57#[strict_type(lib = LIB_NAME_BITCOIN)]
58#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(rename_all = "camelCase"))]
59pub struct BlockHeader {
60 pub version: i32,
62 pub prev_block_hash: BlockHash,
64 pub merkle_root: BlockMerkleRoot,
66 pub time: u32,
68 pub bits: u32,
70 pub nonce: u32,
72}
73
74impl LowerHex for BlockHeader {
75 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
76 f.write_str(&self.consensus_serialize().to_hex())
77 }
78}
79
80impl FromStr for BlockHeader {
81 type Err = BlockDataParseError;
82
83 fn from_str(s: &str) -> Result<Self, Self::Err> {
84 let data = Vec::<u8>::from_hex(s)?;
85 BlockHeader::consensus_deserialize(data).map_err(BlockDataParseError::from)
86 }
87}
88
89impl BlockHeader {
90 pub fn block_hash(&self) -> BlockHash {
91 let mut enc = Sha256::default();
92 self.consensus_encode(&mut enc).expect("engines don't error");
93 let mut double = Sha256::default();
94 double.input_raw(&enc.finish());
95 BlockHash::from_byte_array(double.finish())
96 }
97}
98
99#[cfg(test)]
100mod test {
101 use super::*;
102
103 #[test]
104 fn modern_block_header() {
106 let header_str = "00006020333eaffe61bc29a9a387aa56bd424b3c73ebb536cc4a03000000000000000000\
107 af225b062c7acf90aac833cc4e0789f17b13ef53564cdd3b748e7897d7df20ff25bcf665595a03170bcd54ad";
108 let header = BlockHeader::from_str(header_str).unwrap();
109 assert_eq!(header.version, 0x20600000);
110 assert_eq!(
111 header.merkle_root.to_string(),
112 "ff20dfd797788e743bdd4c5653ef137bf189074ecc33c8aa90cf7a2c065b22af"
113 );
114 assert_eq!(
115 header.prev_block_hash.to_string(),
116 "000000000000000000034acc36b5eb733c4b42bd56aa87a3a929bc61feaf3e33"
117 );
118 assert_eq!(header.bits, 0x17035a59);
119 assert_eq!(header.nonce, 0xad54cd0b);
120 assert_eq!(header.time, 1710668837);
121 assert_eq!(header.to_string(), header_str);
122 assert_eq!(
123 header.block_hash().to_string(),
124 "00000000000000000000a885d748631afdf2408d2db66e616e963d08c31a65df"
125 );
126 }
127}