bc/
block.rs

1// Bitcoin protocol consensus library.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Written in 2019-2024 by
6//     Dr Maxim Orlovsky <orlovsky@lnp-bp.org>
7//
8// Copyright (C) 2019-2024 LNP/BP Standards Association. All rights reserved.
9//
10// Licensed under the Apache License, Version 2.0 (the "License");
11// you may not use this file except in compliance with the License.
12// You may obtain a copy of the License at
13//
14//     http://www.apache.org/licenses/LICENSE-2.0
15//
16// Unless required by applicable law or agreed to in writing, software
17// distributed under the License is distributed on an "AS IS" BASIS,
18// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19// See the License for the specific language governing permissions and
20// limitations under the License.
21
22use 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    /// Block version, now repurposed for soft fork signalling.
61    pub version: i32,
62    /// Reference to the previous block in the chain.
63    pub prev_block_hash: BlockHash,
64    /// The root hash of the merkle tree of transactions in the block.
65    pub merkle_root: BlockMerkleRoot,
66    /// The timestamp of the block, as claimed by the miner.
67    pub time: u32,
68    /// The target value below which the blockhash must lie.
69    pub bits: u32,
70    /// The nonce, selected to obtain a low enough blockhash.
71    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    // block height 835056
105    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}