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(
36    feature = "serde",
37    derive(Serialize, Deserialize),
38    serde(crate = "serde_crate", transparent)
39)]
40#[wrapper(BorrowSlice, Index, RangeOps, Debug, Hex, Display, FromStr)]
41pub struct BlockHash(
42    #[from]
43    #[from([u8; 32])]
44    Bytes32StrRev,
45);
46
47#[derive(Wrapper, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, From)]
48#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
49#[strict_type(lib = LIB_NAME_BITCOIN)]
50#[cfg_attr(
51    feature = "serde",
52    derive(Serialize, Deserialize),
53    serde(crate = "serde_crate", transparent)
54)]
55#[wrapper(BorrowSlice, Index, RangeOps, Debug, Hex, Display, FromStr)]
56pub struct BlockMerkleRoot(
57    #[from]
58    #[from([u8; 32])]
59    Bytes32StrRev,
60);
61
62#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display)]
63#[display(LowerHex)]
64#[derive(StrictType, StrictEncode, StrictDecode, StrictDumb)]
65#[strict_type(lib = LIB_NAME_BITCOIN)]
66#[cfg_attr(
67    feature = "serde",
68    derive(Serialize, Deserialize),
69    serde(crate = "serde_crate", rename_all = "camelCase")
70)]
71pub struct BlockHeader {
72    /// Block version, now repurposed for soft fork signalling.
73    pub version: i32,
74    /// Reference to the previous block in the chain.
75    pub prev_block_hash: BlockHash,
76    /// The root hash of the merkle tree of transactions in the block.
77    pub merkle_root: BlockMerkleRoot,
78    /// The timestamp of the block, as claimed by the miner.
79    pub time: u32,
80    /// The target value below which the blockhash must lie.
81    pub bits: u32,
82    /// The nonce, selected to obtain a low enough blockhash.
83    pub nonce: u32,
84}
85
86impl LowerHex for BlockHeader {
87    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
88        f.write_str(&self.consensus_serialize().to_hex())
89    }
90}
91
92impl FromStr for BlockHeader {
93    type Err = BlockDataParseError;
94
95    fn from_str(s: &str) -> Result<Self, Self::Err> {
96        let data = Vec::<u8>::from_hex(s)?;
97        BlockHeader::consensus_deserialize(data).map_err(BlockDataParseError::from)
98    }
99}
100
101impl BlockHeader {
102    pub fn block_hash(&self) -> BlockHash {
103        let mut enc = Sha256::default();
104        self.consensus_encode(&mut enc).expect("engines don't error");
105        let mut double = Sha256::default();
106        double.input_raw(&enc.finish());
107        BlockHash::from_byte_array(double.finish())
108    }
109}
110
111#[cfg(test)]
112mod test {
113    use super::*;
114
115    #[test]
116    // block height 835056
117    fn modern_block_header() {
118        let header_str = "00006020333eaffe61bc29a9a387aa56bd424b3c73ebb536cc4a03000000000000000000\
119        af225b062c7acf90aac833cc4e0789f17b13ef53564cdd3b748e7897d7df20ff25bcf665595a03170bcd54ad";
120        let header = BlockHeader::from_str(header_str).unwrap();
121        assert_eq!(header.version, 0x20600000);
122        assert_eq!(
123            header.merkle_root.to_string(),
124            "ff20dfd797788e743bdd4c5653ef137bf189074ecc33c8aa90cf7a2c065b22af"
125        );
126        assert_eq!(
127            header.prev_block_hash.to_string(),
128            "000000000000000000034acc36b5eb733c4b42bd56aa87a3a929bc61feaf3e33"
129        );
130        assert_eq!(header.bits, 0x17035a59);
131        assert_eq!(header.nonce, 0xad54cd0b);
132        assert_eq!(header.time, 1710668837);
133        assert_eq!(header.to_string(), header_str);
134        assert_eq!(
135            header.block_hash().to_string(),
136            "00000000000000000000a885d748631afdf2408d2db66e616e963d08c31a65df"
137        );
138    }
139}