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::{
31    BlockDataParseError, ConsensusDecode, ConsensusEncode, Tx, VarIntArray, LIB_NAME_BITCOIN,
32};
33
34#[derive(Wrapper, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, From)]
35#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
36#[strict_type(lib = LIB_NAME_BITCOIN)]
37#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(transparent))]
38#[wrapper(BorrowSlice, Index, RangeOps, Debug, Hex, Display, FromStr)]
39pub struct BlockHash(
40    #[from]
41    #[from([u8; 32])]
42    Bytes32StrRev,
43);
44
45impl BlockHash {
46    pub const GENESIS_MAINNET: BlockHash = BlockHash::from_u64_be_array([
47        0x00000000_0019d668,
48        0x9c085ae1_65831e93,
49        0x4ff763ae_46a2a6c1,
50        0x72b3f1b6_0a8ce26f,
51    ]);
52    pub const GENESIS_TESTNET3: BlockHash = BlockHash::from_u64_be_array([
53        0x00000000_0933ea01,
54        0xad0ee984_209779ba,
55        0xaec3ced9_0fa3f408,
56        0x719526f8_d77f4943,
57    ]);
58    pub const GENESIS_TESTNET4: BlockHash = BlockHash::from_u64_be_array([
59        0x00000000_da84f2ba,
60        0xfbbc53de_e25a72ae,
61        0x507ff491_4b867c56,
62        0x5be350b0_da8bf043,
63    ]);
64    pub const GENESIS_SIGNET: BlockHash = BlockHash::from_u64_be_array([
65        0x00000008_819873e9,
66        0x25422c1f_f0f99f7c,
67        0xc9bbb232_af63a077,
68        0xa480a363_3bee1ef6,
69    ]);
70    pub const GENESIS_REGTEST: BlockHash = BlockHash::from_u64_be_array([
71        0x0f9188f1_3cb7b2c7,
72        0x1f2a335e_3a4fc328,
73        0xbf5beb43_6012afca,
74        0x590b1a11_466e2206,
75    ]);
76
77    pub const fn from_u64_be_array(array: [u64; 4]) -> Self {
78        let mut buf = [0u8; 32];
79        let x = array[0].to_be_bytes();
80        buf[31] = x[0];
81        buf[30] = x[1];
82        buf[29] = x[2];
83        buf[28] = x[3];
84        buf[27] = x[4];
85        buf[26] = x[5];
86        buf[25] = x[6];
87        buf[24] = x[7];
88        let x = array[1].to_be_bytes();
89        buf[23] = x[0];
90        buf[22] = x[1];
91        buf[21] = x[2];
92        buf[20] = x[3];
93        buf[19] = x[4];
94        buf[18] = x[5];
95        buf[17] = x[6];
96        buf[16] = x[7];
97        let x = array[2].to_be_bytes();
98        buf[15] = x[0];
99        buf[14] = x[1];
100        buf[13] = x[2];
101        buf[12] = x[3];
102        buf[11] = x[4];
103        buf[10] = x[5];
104        buf[9] = x[6];
105        buf[8] = x[7];
106        let x = array[3].to_be_bytes();
107        buf[7] = x[0];
108        buf[6] = x[1];
109        buf[5] = x[2];
110        buf[4] = x[3];
111        buf[3] = x[4];
112        buf[2] = x[5];
113        buf[1] = x[6];
114        buf[0] = x[7];
115        Self(Bytes32StrRev::from_array(buf))
116    }
117}
118
119#[derive(Wrapper, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, From)]
120#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
121#[strict_type(lib = LIB_NAME_BITCOIN)]
122#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(transparent))]
123#[wrapper(BorrowSlice, Index, RangeOps, Debug, Hex, Display, FromStr)]
124pub struct BlockMerkleRoot(
125    #[from]
126    #[from([u8; 32])]
127    Bytes32StrRev,
128);
129
130#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display)]
131#[display(LowerHex)]
132#[derive(StrictType, StrictEncode, StrictDecode, StrictDumb)]
133#[strict_type(lib = LIB_NAME_BITCOIN)]
134#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(rename_all = "camelCase"))]
135pub struct BlockHeader {
136    /// Block version, now repurposed for soft fork signalling.
137    pub version: i32,
138    /// Reference to the previous block in the chain.
139    pub prev_block_hash: BlockHash,
140    /// The root hash of the merkle tree of transactions in the block.
141    pub merkle_root: BlockMerkleRoot,
142    /// The timestamp of the block, as claimed by the miner.
143    pub time: u32,
144    /// The target value below which the blockhash must lie.
145    pub bits: u32,
146    /// The nonce, selected to obtain a low enough blockhash.
147    pub nonce: u32,
148}
149
150impl LowerHex for BlockHeader {
151    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
152        f.write_str(&self.consensus_serialize().to_hex())
153    }
154}
155
156impl FromStr for BlockHeader {
157    type Err = BlockDataParseError;
158
159    fn from_str(s: &str) -> Result<Self, Self::Err> {
160        let data = Vec::<u8>::from_hex(s)?;
161        BlockHeader::consensus_deserialize(data).map_err(BlockDataParseError::from)
162    }
163}
164
165impl BlockHeader {
166    pub fn block_hash(&self) -> BlockHash {
167        let mut enc = Sha256::default();
168        self.consensus_encode(&mut enc).expect("engines don't error");
169        let mut double = Sha256::default();
170        double.input_raw(&enc.finish());
171        BlockHash::from_byte_array(double.finish())
172    }
173}
174
175#[derive(Clone, PartialEq, Eq, Hash, Debug, Display)]
176#[display(LowerHex)]
177#[derive(StrictType, StrictEncode, StrictDecode, StrictDumb)]
178#[strict_type(lib = LIB_NAME_BITCOIN)]
179#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
180pub struct Block {
181    pub header: BlockHeader,
182    pub transactions: VarIntArray<Tx>,
183}
184
185impl LowerHex for Block {
186    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
187        f.write_str(&self.consensus_serialize().to_hex())
188    }
189}
190
191impl FromStr for Block {
192    type Err = BlockDataParseError;
193
194    fn from_str(s: &str) -> Result<Self, Self::Err> {
195        let data = Vec::<u8>::from_hex(s)?;
196        Block::consensus_deserialize(data).map_err(BlockDataParseError::from)
197    }
198}
199
200impl Block {
201    pub fn block_hash(&self) -> BlockHash { self.header.block_hash() }
202}
203
204#[cfg(test)]
205mod test {
206    #![cfg_attr(coverage_nightly, coverage(off))]
207
208    use super::*;
209
210    #[test]
211    // block height 835056
212    fn modern_block_header() {
213        let header_str = "00006020333eaffe61bc29a9a387aa56bd424b3c73ebb536cc4a03000000000000000000\
214        af225b062c7acf90aac833cc4e0789f17b13ef53564cdd3b748e7897d7df20ff25bcf665595a03170bcd54ad";
215        let header = BlockHeader::from_str(header_str).unwrap();
216        assert_eq!(header.version, 0x20600000);
217        assert_eq!(
218            header.merkle_root.to_string(),
219            "ff20dfd797788e743bdd4c5653ef137bf189074ecc33c8aa90cf7a2c065b22af"
220        );
221        assert_eq!(
222            header.prev_block_hash.to_string(),
223            "000000000000000000034acc36b5eb733c4b42bd56aa87a3a929bc61feaf3e33"
224        );
225        assert_eq!(header.bits, 0x17035a59);
226        assert_eq!(header.nonce, 0xad54cd0b);
227        assert_eq!(header.time, 1710668837);
228        assert_eq!(header.to_string(), header_str);
229        assert_eq!(
230            header.block_hash().to_string(),
231            "00000000000000000000a885d748631afdf2408d2db66e616e963d08c31a65df"
232        );
233    }
234
235    #[test]
236    fn genesis_hashes() {
237        assert_eq!(
238            &BlockHash::GENESIS_MAINNET.to_string(),
239            "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"
240        );
241        assert_eq!(
242            &BlockHash::GENESIS_TESTNET3.to_string(),
243            "000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943"
244        );
245        assert_eq!(
246            &BlockHash::GENESIS_TESTNET4.to_string(),
247            "00000000da84f2bafbbc53dee25a72ae507ff4914b867c565be350b0da8bf043"
248        );
249        assert_eq!(
250            &BlockHash::GENESIS_SIGNET.to_string(),
251            "00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6"
252        );
253        assert_eq!(
254            &BlockHash::GENESIS_REGTEST.to_string(),
255            "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"
256        );
257    }
258}