bitcoin/blockdata/
block.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Bitcoin blocks.
4//!
5//! A block is a bundle of transactions with a proof-of-work attached,
6//! which commits to an earlier block to form the blockchain. This
7//! module describes structures and functions needed to describe
8//! these blocks and the blockchain.
9//!
10
11use core::fmt;
12
13use hashes::{sha256d, Hash, HashEngine};
14use io::{Read, Write};
15
16use super::Weight;
17use crate::blockdata::script;
18use crate::blockdata::transaction::{Transaction, Txid, Wtxid};
19use crate::consensus::{encode, Decodable, Encodable, Params};
20use crate::internal_macros::{impl_consensus_encoding, impl_hashencode};
21use crate::pow::{CompactTarget, Target, Work};
22use crate::prelude::*;
23use crate::{merkle_tree, VarInt};
24
25hashes::hash_newtype! {
26    /// A bitcoin block hash.
27    pub struct BlockHash(sha256d::Hash);
28    /// A hash of the Merkle tree branch or root for transactions.
29    pub struct TxMerkleNode(sha256d::Hash);
30    /// A hash corresponding to the Merkle tree root for witness data.
31    pub struct WitnessMerkleNode(sha256d::Hash);
32    /// A hash corresponding to the witness structure commitment in the coinbase transaction.
33    pub struct WitnessCommitment(sha256d::Hash);
34}
35impl_hashencode!(BlockHash);
36impl_hashencode!(TxMerkleNode);
37impl_hashencode!(WitnessMerkleNode);
38
39impl From<Txid> for TxMerkleNode {
40    fn from(txid: Txid) -> Self { Self::from_byte_array(txid.to_byte_array()) }
41}
42
43impl From<Wtxid> for WitnessMerkleNode {
44    fn from(wtxid: Wtxid) -> Self { Self::from_byte_array(wtxid.to_byte_array()) }
45}
46
47/// Bitcoin block header.
48///
49/// Contains all the block's information except the actual transactions, but
50/// including a root of a [merkle tree] committing to all transactions in the block.
51///
52/// [merkle tree]: https://en.wikipedia.org/wiki/Merkle_tree
53///
54/// ### Bitcoin Core References
55///
56/// * [CBlockHeader definition](https://github.com/bitcoin/bitcoin/blob/345457b542b6a980ccfbc868af0970a6f91d1b82/src/primitives/block.h#L20)
57#[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
58#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
59#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
60pub struct Header {
61    /// Block version, now repurposed for soft fork signalling.
62    pub version: Version,
63    /// Reference to the previous block in the chain.
64    pub prev_blockhash: BlockHash,
65    /// The root hash of the merkle tree of transactions in the block.
66    pub merkle_root: TxMerkleNode,
67    /// The timestamp of the block, as claimed by the miner.
68    pub time: u32,
69    /// The target value below which the blockhash must lie.
70    pub bits: CompactTarget,
71    /// The nonce, selected to obtain a low enough blockhash.
72    pub nonce: u32,
73}
74
75impl_consensus_encoding!(Header, version, prev_blockhash, merkle_root, time, bits, nonce);
76
77impl Header {
78    /// The number of bytes that the block header contributes to the size of a block.
79    // Serialized length of fields (version, prev_blockhash, merkle_root, time, bits, nonce)
80    pub const SIZE: usize = 4 + 32 + 32 + 4 + 4 + 4; // 80
81
82    /// Returns the block hash.
83    pub fn block_hash(&self) -> BlockHash {
84        let mut engine = BlockHash::engine();
85        self.consensus_encode(&mut engine).expect("engines don't error");
86        BlockHash::from_engine(engine)
87    }
88
89    /// Computes the target (range [0, T] inclusive) that a blockhash must land in to be valid.
90    pub fn target(&self) -> Target { self.bits.into() }
91
92    /// Computes the popular "difficulty" measure for mining.
93    ///
94    /// Difficulty represents how difficult the current target makes it to find a block, relative to
95    /// how difficult it would be at the highest possible target (highest target == lowest difficulty).
96    pub fn difficulty(&self, params: impl AsRef<Params>) -> u128 {
97        self.target().difficulty(params)
98    }
99
100    /// Computes the popular "difficulty" measure for mining and returns a float value of f64.
101    pub fn difficulty_float(&self) -> f64 { self.target().difficulty_float() }
102
103    /// Checks that the proof-of-work for the block is valid, returning the block hash.
104    pub fn validate_pow(&self, required_target: Target) -> Result<BlockHash, ValidationError> {
105        let target = self.target();
106        if target != required_target {
107            return Err(ValidationError::BadTarget);
108        }
109        let block_hash = self.block_hash();
110        if target.is_met_by(block_hash) {
111            Ok(block_hash)
112        } else {
113            Err(ValidationError::BadProofOfWork)
114        }
115    }
116
117    /// Returns the total work of the block.
118    pub fn work(&self) -> Work { self.target().to_work() }
119}
120
121impl fmt::Debug for Header {
122    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
123        f.debug_struct("Header")
124            .field("block_hash", &self.block_hash())
125            .field("version", &self.version)
126            .field("prev_blockhash", &self.prev_blockhash)
127            .field("merkle_root", &self.merkle_root)
128            .field("time", &self.time)
129            .field("bits", &self.bits)
130            .field("nonce", &self.nonce)
131            .finish()
132    }
133}
134
135/// Bitcoin block version number.
136///
137/// Originally used as a protocol version, but repurposed for soft-fork signaling.
138///
139/// The inner value is a signed integer in Bitcoin Core for historical reasons, if version bits is
140/// being used the top three bits must be 001, this gives us a useful range of [0x20000000...0x3FFFFFFF].
141///
142/// > When a block nVersion does not have top bits 001, it is treated as if all bits are 0 for the purposes of deployments.
143///
144/// ### Relevant BIPs
145///
146/// * [BIP9 - Version bits with timeout and delay](https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki) (current usage)
147/// * [BIP34 - Block v2, Height in Coinbase](https://github.com/bitcoin/bips/blob/master/bip-0034.mediawiki)
148#[derive(Copy, PartialEq, Eq, Clone, Debug, PartialOrd, Ord, Hash)]
149#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
150#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
151pub struct Version(i32);
152
153impl Version {
154    /// The original Bitcoin Block v1.
155    pub const ONE: Self = Self(1);
156
157    /// BIP-34 Block v2.
158    pub const TWO: Self = Self(2);
159
160    /// BIP-9 compatible version number that does not signal for any softforks.
161    pub const NO_SOFT_FORK_SIGNALLING: Self = Self(Self::USE_VERSION_BITS as i32);
162
163    /// BIP-9 soft fork signal bits mask.
164    const VERSION_BITS_MASK: u32 = 0x1FFF_FFFF;
165
166    /// 32bit value starting with `001` to use version bits.
167    ///
168    /// The value has the top three bits `001` which enables the use of version bits to signal for soft forks.
169    const USE_VERSION_BITS: u32 = 0x2000_0000;
170
171    /// Creates a [`Version`] from a signed 32 bit integer value.
172    ///
173    /// This is the data type used in consensus code in Bitcoin Core.
174    #[inline]
175    pub const fn from_consensus(v: i32) -> Self { Version(v) }
176
177    /// Returns the inner `i32` value.
178    ///
179    /// This is the data type used in consensus code in Bitcoin Core.
180    pub fn to_consensus(self) -> i32 { self.0 }
181
182    /// Checks whether the version number is signalling a soft fork at the given bit.
183    ///
184    /// A block is signalling for a soft fork under BIP-9 if the first 3 bits are `001` and
185    /// the version bit for the specific soft fork is toggled on.
186    pub fn is_signalling_soft_fork(&self, bit: u8) -> bool {
187        // Only bits [0, 28] inclusive are used for signalling.
188        if bit > 28 {
189            return false;
190        }
191
192        // To signal using version bits, the first three bits must be `001`.
193        if (self.0 as u32) & !Self::VERSION_BITS_MASK != Self::USE_VERSION_BITS {
194            return false;
195        }
196
197        // The bit is set if signalling a soft fork.
198        (self.0 as u32 & Self::VERSION_BITS_MASK) & (1 << bit) > 0
199    }
200}
201
202impl Default for Version {
203    fn default() -> Version { Self::NO_SOFT_FORK_SIGNALLING }
204}
205
206impl Encodable for Version {
207    fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
208        self.0.consensus_encode(w)
209    }
210}
211
212impl Decodable for Version {
213    fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
214        Decodable::consensus_decode(r).map(Version)
215    }
216}
217
218/// Bitcoin block.
219///
220/// A collection of transactions with an attached proof of work.
221///
222/// See [Bitcoin Wiki: Block][wiki-block] for more information.
223///
224/// [wiki-block]: https://en.bitcoin.it/wiki/Block
225///
226/// ### Bitcoin Core References
227///
228/// * [CBlock definition](https://github.com/bitcoin/bitcoin/blob/345457b542b6a980ccfbc868af0970a6f91d1b82/src/primitives/block.h#L62)
229#[derive(PartialEq, Eq, Clone, Debug)]
230#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
231#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
232pub struct Block {
233    /// The block header
234    pub header: Header,
235    /// List of transactions contained in the block
236    pub txdata: Vec<Transaction>,
237}
238
239impl_consensus_encoding!(Block, header, txdata);
240
241impl Block {
242    /// Returns the block hash.
243    pub fn block_hash(&self) -> BlockHash { self.header.block_hash() }
244
245    /// Checks if merkle root of header matches merkle root of the transaction list.
246    pub fn check_merkle_root(&self) -> bool {
247        match self.compute_merkle_root() {
248            Some(merkle_root) => self.header.merkle_root == merkle_root,
249            None => false,
250        }
251    }
252
253    /// Checks if witness commitment in coinbase matches the transaction list.
254    pub fn check_witness_commitment(&self) -> bool {
255        const MAGIC: [u8; 6] = [0x6a, 0x24, 0xaa, 0x21, 0xa9, 0xed];
256        // Witness commitment is optional if there are no transactions using SegWit in the block.
257        if self.txdata.iter().all(|t| t.input.iter().all(|i| i.witness.is_empty())) {
258            return true;
259        }
260
261        if self.txdata.is_empty() {
262            return false;
263        }
264
265        let coinbase = &self.txdata[0];
266        if !coinbase.is_coinbase() {
267            return false;
268        }
269
270        // Commitment is in the last output that starts with magic bytes.
271        if let Some(pos) = coinbase
272            .output
273            .iter()
274            .rposition(|o| o.script_pubkey.len() >= 38 && o.script_pubkey.as_bytes()[0..6] == MAGIC)
275        {
276            let commitment = WitnessCommitment::from_slice(
277                &coinbase.output[pos].script_pubkey.as_bytes()[6..38],
278            )
279            .unwrap();
280            // Witness reserved value is in coinbase input witness.
281            let witness_vec: Vec<_> = coinbase.input[0].witness.iter().collect();
282            if witness_vec.len() == 1 && witness_vec[0].len() == 32 {
283                if let Some(witness_root) = self.witness_root() {
284                    return commitment
285                        == Self::compute_witness_commitment(&witness_root, witness_vec[0]);
286                }
287            }
288        }
289
290        false
291    }
292
293    /// Computes the transaction merkle root.
294    pub fn compute_merkle_root(&self) -> Option<TxMerkleNode> {
295        let hashes = self.txdata.iter().map(|obj| obj.compute_txid().to_raw_hash());
296        merkle_tree::calculate_root(hashes).map(|h| h.into())
297    }
298
299    /// Computes the witness commitment for the block's transaction list.
300    pub fn compute_witness_commitment(
301        witness_root: &WitnessMerkleNode,
302        witness_reserved_value: &[u8],
303    ) -> WitnessCommitment {
304        let mut encoder = WitnessCommitment::engine();
305        witness_root.consensus_encode(&mut encoder).expect("engines don't error");
306        encoder.input(witness_reserved_value);
307        WitnessCommitment::from_engine(encoder)
308    }
309
310    /// Computes the merkle root of transactions hashed for witness.
311    pub fn witness_root(&self) -> Option<WitnessMerkleNode> {
312        let hashes = self.txdata.iter().enumerate().map(|(i, t)| {
313            if i == 0 {
314                // Replace the first hash with zeroes.
315                Wtxid::all_zeros().to_raw_hash()
316            } else {
317                t.compute_wtxid().to_raw_hash()
318            }
319        });
320        merkle_tree::calculate_root(hashes).map(|h| h.into())
321    }
322
323    /// Returns the weight of the block.
324    ///
325    /// > Block weight is defined as Base size * 3 + Total size.
326    pub fn weight(&self) -> Weight {
327        // This is the exact definition of a weight unit, as defined by BIP-141 (quote above).
328        let wu = self.base_size() * 3 + self.total_size();
329        Weight::from_wu_usize(wu)
330    }
331
332    /// Returns the base block size.
333    ///
334    /// > Base size is the block size in bytes with the original transaction serialization without
335    /// > any witness-related data, as seen by a non-upgraded node.
336    fn base_size(&self) -> usize {
337        let mut size = Header::SIZE;
338
339        size += VarInt::from(self.txdata.len()).size();
340        size += self.txdata.iter().map(|tx| tx.base_size()).sum::<usize>();
341
342        size
343    }
344
345    /// Returns the total block size.
346    ///
347    /// > Total size is the block size in bytes with transactions serialized as described in BIP144,
348    /// > including base data and witness data.
349    pub fn total_size(&self) -> usize {
350        let mut size = Header::SIZE;
351
352        size += VarInt::from(self.txdata.len()).size();
353        size += self.txdata.iter().map(|tx| tx.total_size()).sum::<usize>();
354
355        size
356    }
357
358    /// Returns the coinbase transaction, if one is present.
359    pub fn coinbase(&self) -> Option<&Transaction> { self.txdata.first() }
360
361    /// Returns the block height, as encoded in the coinbase transaction according to BIP34.
362    pub fn bip34_block_height(&self) -> Result<u64, Bip34Error> {
363        // Citing the spec:
364        // Add height as the first item in the coinbase transaction's scriptSig,
365        // and increase block version to 2. The format of the height is
366        // "minimally encoded serialized CScript"" -- first byte is number of bytes in the number
367        // (will be 0x03 on main net for the next 150 or so years with 2^23-1
368        // blocks), following bytes are little-endian representation of the
369        // number (including a sign bit). Height is the height of the mined
370        // block in the block chain, where the genesis block is height zero (0).
371
372        if self.header.version < Version::TWO {
373            return Err(Bip34Error::Unsupported);
374        }
375
376        let cb = self.coinbase().ok_or(Bip34Error::NotPresent)?;
377        let input = cb.input.first().ok_or(Bip34Error::NotPresent)?;
378        let push = input.script_sig.instructions_minimal().next().ok_or(Bip34Error::NotPresent)?;
379        match push.map_err(|_| Bip34Error::NotPresent)? {
380            script::Instruction::PushBytes(b) => {
381                // Check that the number is encoded in the minimal way.
382                let h = script::read_scriptint(b.as_bytes())
383                    .map_err(|_e| Bip34Error::UnexpectedPush(b.as_bytes().to_vec()))?;
384                if h < 0 {
385                    Err(Bip34Error::NegativeHeight)
386                } else {
387                    Ok(h as u64)
388                }
389            }
390            _ => Err(Bip34Error::NotPresent),
391        }
392    }
393}
394
395impl From<Header> for BlockHash {
396    fn from(header: Header) -> BlockHash { header.block_hash() }
397}
398
399impl From<&Header> for BlockHash {
400    fn from(header: &Header) -> BlockHash { header.block_hash() }
401}
402
403impl From<Block> for BlockHash {
404    fn from(block: Block) -> BlockHash { block.block_hash() }
405}
406
407impl From<&Block> for BlockHash {
408    fn from(block: &Block) -> BlockHash { block.block_hash() }
409}
410
411/// An error when looking up a BIP34 block height.
412#[derive(Debug, Clone, PartialEq, Eq)]
413#[non_exhaustive]
414pub enum Bip34Error {
415    /// The block does not support BIP34 yet.
416    Unsupported,
417    /// No push was present where the BIP34 push was expected.
418    NotPresent,
419    /// The BIP34 push was larger than 8 bytes.
420    UnexpectedPush(Vec<u8>),
421    /// The BIP34 push was negative.
422    NegativeHeight,
423}
424
425internals::impl_from_infallible!(Bip34Error);
426
427impl fmt::Display for Bip34Error {
428    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
429        use Bip34Error::*;
430
431        match *self {
432            Unsupported => write!(f, "block doesn't support BIP34"),
433            NotPresent => write!(f, "BIP34 push not present in block's coinbase"),
434            UnexpectedPush(ref p) => {
435                write!(f, "unexpected byte push of > 8 bytes: {:?}", p)
436            }
437            NegativeHeight => write!(f, "negative BIP34 height"),
438        }
439    }
440}
441
442#[cfg(feature = "std")]
443impl std::error::Error for Bip34Error {
444    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
445        use Bip34Error::*;
446
447        match *self {
448            Unsupported | NotPresent | UnexpectedPush(_) | NegativeHeight => None,
449        }
450    }
451}
452
453/// A block validation error.
454#[derive(Debug, Clone, PartialEq, Eq)]
455#[non_exhaustive]
456pub enum ValidationError {
457    /// The header hash is not below the target.
458    BadProofOfWork,
459    /// The `target` field of a block header did not match the expected difficulty.
460    BadTarget,
461}
462
463internals::impl_from_infallible!(ValidationError);
464
465impl fmt::Display for ValidationError {
466    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
467        use ValidationError::*;
468
469        match *self {
470            BadProofOfWork => f.write_str("block target correct but not attained"),
471            BadTarget => f.write_str("block target incorrect"),
472        }
473    }
474}
475
476#[cfg(feature = "std")]
477impl std::error::Error for ValidationError {
478    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
479        use self::ValidationError::*;
480
481        match *self {
482            BadProofOfWork | BadTarget => None,
483        }
484    }
485}
486
487#[cfg(test)]
488mod tests {
489    use hex::{test_hex_unwrap as hex, FromHex};
490
491    use super::*;
492    use crate::consensus::encode::{deserialize, serialize};
493    use crate::Network;
494
495    #[test]
496    fn test_coinbase_and_bip34() {
497        // testnet block 100,000
498        const BLOCK_HEX: &str = "0200000035ab154183570282ce9afc0b494c9fc6a3cfea05aa8c1add2ecc56490000000038ba3d78e4500a5a7570dbe61960398add4410d278b21cd9708e6d9743f374d544fc055227f1001c29c1ea3b0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff3703a08601000427f1001c046a510100522cfabe6d6d0000000000000000000068692066726f6d20706f6f6c7365727665726aac1eeeed88ffffffff0100f2052a010000001976a914912e2b234f941f30b18afbb4fa46171214bf66c888ac00000000";
499        let block: Block = deserialize(&hex!(BLOCK_HEX)).unwrap();
500
501        let cb_txid = "d574f343976d8e70d91cb278d21044dd8a396019e6db70755a0a50e4783dba38";
502        assert_eq!(block.coinbase().unwrap().compute_txid().to_string(), cb_txid);
503
504        assert_eq!(block.bip34_block_height(), Ok(100_000));
505
506        // block with 9-byte bip34 push
507        const BAD_HEX: &str = "0200000035ab154183570282ce9afc0b494c9fc6a3cfea05aa8c1add2ecc56490000000038ba3d78e4500a5a7570dbe61960398add4410d278b21cd9708e6d9743f374d544fc055227f1001c29c1ea3b0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff3d09a08601112233445566000427f1001c046a510100522cfabe6d6d0000000000000000000068692066726f6d20706f6f6c7365727665726aac1eeeed88ffffffff0100f2052a010000001976a914912e2b234f941f30b18afbb4fa46171214bf66c888ac00000000";
508        let bad: Block = deserialize(&hex!(BAD_HEX)).unwrap();
509
510        let push = Vec::<u8>::from_hex("a08601112233445566").unwrap();
511        assert_eq!(bad.bip34_block_height(), Err(super::Bip34Error::UnexpectedPush(push)));
512    }
513
514    #[test]
515    fn block_test() {
516        let params = Params::new(Network::Bitcoin);
517        // Mainnet block 00000000b0c5a240b2a61d2e75692224efd4cbecdf6eaf4cc2cf477ca7c270e7
518        let some_block = hex!("010000004ddccd549d28f385ab457e98d1b11ce80bfea2c5ab93015ade4973e400000000bf4473e53794beae34e64fccc471dace6ae544180816f89591894e0f417a914cd74d6e49ffff001d323b3a7b0201000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0804ffff001d026e04ffffffff0100f2052a0100000043410446ef0102d1ec5240f0d061a4246c1bdef63fc3dbab7733052fbbf0ecd8f41fc26bf049ebb4f9527f374280259e7cfa99c48b0e3f39c51347a19a5819651503a5ac00000000010000000321f75f3139a013f50f315b23b0c9a2b6eac31e2bec98e5891c924664889942260000000049483045022100cb2c6b346a978ab8c61b18b5e9397755cbd17d6eb2fe0083ef32e067fa6c785a02206ce44e613f31d9a6b0517e46f3db1576e9812cc98d159bfdaf759a5014081b5c01ffffffff79cda0945903627c3da1f85fc95d0b8ee3e76ae0cfdc9a65d09744b1f8fc85430000000049483045022047957cdd957cfd0becd642f6b84d82f49b6cb4c51a91f49246908af7c3cfdf4a022100e96b46621f1bffcf5ea5982f88cef651e9354f5791602369bf5a82a6cd61a62501fffffffffe09f5fe3ffbf5ee97a54eb5e5069e9da6b4856ee86fc52938c2f979b0f38e82000000004847304402204165be9a4cbab8049e1af9723b96199bfd3e85f44c6b4c0177e3962686b26073022028f638da23fc003760861ad481ead4099312c60030d4cb57820ce4d33812a5ce01ffffffff01009d966b01000000434104ea1feff861b51fe3f5f8a3b12d0f4712db80e919548a80839fc47c6a21e66d957e9c5d8cd108c7a2d2324bad71f9904ac0ae7336507d785b17a2c115e427a32fac00000000");
519        let cutoff_block = hex!("010000004ddccd549d28f385ab457e98d1b11ce80bfea2c5ab93015ade4973e400000000bf4473e53794beae34e64fccc471dace6ae544180816f89591894e0f417a914cd74d6e49ffff001d323b3a7b0201000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0804ffff001d026e04ffffffff0100f2052a0100000043410446ef0102d1ec5240f0d061a4246c1bdef63fc3dbab7733052fbbf0ecd8f41fc26bf049ebb4f9527f374280259e7cfa99c48b0e3f39c51347a19a5819651503a5ac00000000010000000321f75f3139a013f50f315b23b0c9a2b6eac31e2bec98e5891c924664889942260000000049483045022100cb2c6b346a978ab8c61b18b5e9397755cbd17d6eb2fe0083ef32e067fa6c785a02206ce44e613f31d9a6b0517e46f3db1576e9812cc98d159bfdaf759a5014081b5c01ffffffff79cda0945903627c3da1f85fc95d0b8ee3e76ae0cfdc9a65d09744b1f8fc85430000000049483045022047957cdd957cfd0becd642f6b84d82f49b6cb4c51a91f49246908af7c3cfdf4a022100e96b46621f1bffcf5ea5982f88cef651e9354f5791602369bf5a82a6cd61a62501fffffffffe09f5fe3ffbf5ee97a54eb5e5069e9da6b4856ee86fc52938c2f979b0f38e82000000004847304402204165be9a4cbab8049e1af9723b96199bfd3e85f44c6b4c0177e3962686b26073022028f638da23fc003760861ad481ead4099312c60030d4cb57820ce4d33812a5ce01ffffffff01009d966b01000000434104ea1feff861b51fe3f5f8a3b12d0f4712db80e919548a80839fc47c6a21e66d957e9c5d8cd108c7a2d2324bad71f9904ac0ae7336507d785b17a2c115e427a32fac");
520
521        let prevhash = hex!("4ddccd549d28f385ab457e98d1b11ce80bfea2c5ab93015ade4973e400000000");
522        let merkle = hex!("bf4473e53794beae34e64fccc471dace6ae544180816f89591894e0f417a914c");
523        let work = Work::from(0x100010001_u128);
524
525        let decode: Result<Block, _> = deserialize(&some_block);
526        let bad_decode: Result<Block, _> = deserialize(&cutoff_block);
527
528        assert!(decode.is_ok());
529        assert!(bad_decode.is_err());
530        let real_decode = decode.unwrap();
531        assert_eq!(real_decode.header.version, Version(1));
532        assert_eq!(serialize(&real_decode.header.prev_blockhash), prevhash);
533        assert_eq!(real_decode.header.merkle_root, real_decode.compute_merkle_root().unwrap());
534        assert_eq!(serialize(&real_decode.header.merkle_root), merkle);
535        assert_eq!(real_decode.header.time, 1231965655);
536        assert_eq!(real_decode.header.bits, CompactTarget::from_consensus(486604799));
537        assert_eq!(real_decode.header.nonce, 2067413810);
538        assert_eq!(real_decode.header.work(), work);
539        assert_eq!(
540            real_decode.header.validate_pow(real_decode.header.target()).unwrap(),
541            real_decode.block_hash()
542        );
543        assert_eq!(real_decode.header.difficulty(&params), 1);
544        assert_eq!(real_decode.header.difficulty_float(), 1.0);
545
546        assert_eq!(real_decode.total_size(), some_block.len());
547        assert_eq!(real_decode.base_size(), some_block.len());
548        assert_eq!(
549            real_decode.weight(),
550            Weight::from_non_witness_data_size(some_block.len() as u64)
551        );
552
553        // should be also ok for a non-witness block as commitment is optional in that case
554        assert!(real_decode.check_witness_commitment());
555
556        assert_eq!(serialize(&real_decode), some_block);
557    }
558
559    // Check testnet block 000000000000045e0b1660b6445b5e5c5ab63c9a4f956be7e1e69be04fa4497b
560    #[test]
561    fn segwit_block_test() {
562        let params = Params::new(Network::Testnet);
563        let segwit_block = include_bytes!("../../tests/data/testnet_block_000000000000045e0b1660b6445b5e5c5ab63c9a4f956be7e1e69be04fa4497b.raw").to_vec();
564
565        let decode: Result<Block, _> = deserialize(&segwit_block);
566
567        let prevhash = hex!("2aa2f2ca794ccbd40c16e2f3333f6b8b683f9e7179b2c4d74906000000000000");
568        let merkle = hex!("10bc26e70a2f672ad420a6153dd0c28b40a6002c55531bfc99bf8994a8e8f67e");
569        let work = Work::from(0x257c3becdacc64_u64);
570
571        assert!(decode.is_ok());
572        let real_decode = decode.unwrap();
573        assert_eq!(real_decode.header.version, Version(Version::USE_VERSION_BITS as i32)); // VERSIONBITS but no bits set
574        assert_eq!(serialize(&real_decode.header.prev_blockhash), prevhash);
575        assert_eq!(serialize(&real_decode.header.merkle_root), merkle);
576        assert_eq!(real_decode.header.merkle_root, real_decode.compute_merkle_root().unwrap());
577        assert_eq!(real_decode.header.time, 1472004949);
578        assert_eq!(real_decode.header.bits, CompactTarget::from_consensus(0x1a06d450));
579        assert_eq!(real_decode.header.nonce, 1879759182);
580        assert_eq!(real_decode.header.work(), work);
581        assert_eq!(
582            real_decode.header.validate_pow(real_decode.header.target()).unwrap(),
583            real_decode.block_hash()
584        );
585        assert_eq!(real_decode.header.difficulty(&params), 2456598);
586        assert_eq!(real_decode.header.difficulty_float(), 2456598.4399242126);
587
588        assert_eq!(real_decode.total_size(), segwit_block.len());
589        assert_eq!(real_decode.base_size(), 4283);
590        assert_eq!(real_decode.weight(), Weight::from_wu(17168));
591
592        assert!(real_decode.check_witness_commitment());
593
594        assert_eq!(serialize(&real_decode), segwit_block);
595    }
596
597    #[test]
598    fn block_version_test() {
599        let block = hex!("ffffff7f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
600        let decode: Result<Block, _> = deserialize(&block);
601        assert!(decode.is_ok());
602        let real_decode = decode.unwrap();
603        assert_eq!(real_decode.header.version, Version(2147483647));
604
605        let block2 = hex!("000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
606        let decode2: Result<Block, _> = deserialize(&block2);
607        assert!(decode2.is_ok());
608        let real_decode2 = decode2.unwrap();
609        assert_eq!(real_decode2.header.version, Version(-2147483648));
610    }
611
612    #[test]
613    fn validate_pow_test() {
614        let some_header = hex!("010000004ddccd549d28f385ab457e98d1b11ce80bfea2c5ab93015ade4973e400000000bf4473e53794beae34e64fccc471dace6ae544180816f89591894e0f417a914cd74d6e49ffff001d323b3a7b");
615        let some_header: Header =
616            deserialize(&some_header).expect("Can't deserialize correct block header");
617        assert_eq!(
618            some_header.validate_pow(some_header.target()).unwrap(),
619            some_header.block_hash()
620        );
621
622        // test with zero target
623        match some_header.validate_pow(Target::ZERO) {
624            Err(ValidationError::BadTarget) => (),
625            _ => panic!("unexpected result from validate_pow"),
626        }
627
628        // test with modified header
629        let mut invalid_header: Header = some_header;
630        invalid_header.version.0 += 1;
631        match invalid_header.validate_pow(invalid_header.target()) {
632            Err(ValidationError::BadProofOfWork) => (),
633            _ => panic!("unexpected result from validate_pow"),
634        }
635    }
636
637    #[test]
638    fn compact_roundrtip_test() {
639        let some_header = hex!("010000004ddccd549d28f385ab457e98d1b11ce80bfea2c5ab93015ade4973e400000000bf4473e53794beae34e64fccc471dace6ae544180816f89591894e0f417a914cd74d6e49ffff001d323b3a7b");
640
641        let header: Header =
642            deserialize(&some_header).expect("Can't deserialize correct block header");
643
644        assert_eq!(header.bits, header.target().to_compact_lossy());
645    }
646
647    #[test]
648    fn soft_fork_signalling() {
649        for i in 0..31 {
650            let version_int = (0x20000000u32 ^ 1 << i) as i32;
651            let version = Version(version_int);
652            if i < 29 {
653                assert!(version.is_signalling_soft_fork(i));
654            } else {
655                assert!(!version.is_signalling_soft_fork(i));
656            }
657        }
658
659        let segwit_signal = Version(0x20000000 ^ 1 << 1);
660        assert!(!segwit_signal.is_signalling_soft_fork(0));
661        assert!(segwit_signal.is_signalling_soft_fork(1));
662        assert!(!segwit_signal.is_signalling_soft_fork(2));
663    }
664}
665
666#[cfg(bench)]
667mod benches {
668    use io::sink;
669    use test::{black_box, Bencher};
670
671    use super::Block;
672    use crate::consensus::{deserialize, Decodable, Encodable};
673
674    #[bench]
675    pub fn bench_stream_reader(bh: &mut Bencher) {
676        let big_block = include_bytes!("../../tests/data/mainnet_block_000000000000000000000c835b2adcaedc20fdf6ee440009c249452c726dafae.raw");
677        assert_eq!(big_block.len(), 1_381_836);
678        let big_block = black_box(big_block);
679
680        bh.iter(|| {
681            let mut reader = &big_block[..];
682            let block = Block::consensus_decode(&mut reader).unwrap();
683            black_box(&block);
684        });
685    }
686
687    #[bench]
688    pub fn bench_block_serialize(bh: &mut Bencher) {
689        let raw_block = include_bytes!("../../tests/data/mainnet_block_000000000000000000000c835b2adcaedc20fdf6ee440009c249452c726dafae.raw");
690
691        let block: Block = deserialize(&raw_block[..]).unwrap();
692
693        let mut data = Vec::with_capacity(raw_block.len());
694
695        bh.iter(|| {
696            let result = block.consensus_encode(&mut data);
697            black_box(&result);
698            data.clear();
699        });
700    }
701
702    #[bench]
703    pub fn bench_block_serialize_logic(bh: &mut Bencher) {
704        let raw_block = include_bytes!("../../tests/data/mainnet_block_000000000000000000000c835b2adcaedc20fdf6ee440009c249452c726dafae.raw");
705
706        let block: Block = deserialize(&raw_block[..]).unwrap();
707
708        bh.iter(|| {
709            let size = block.consensus_encode(&mut sink());
710            black_box(&size);
711        });
712    }
713
714    #[bench]
715    pub fn bench_block_deserialize(bh: &mut Bencher) {
716        let raw_block = include_bytes!("../../tests/data/mainnet_block_000000000000000000000c835b2adcaedc20fdf6ee440009c249452c726dafae.raw");
717
718        bh.iter(|| {
719            let block: Block = deserialize(&raw_block[..]).unwrap();
720            black_box(&block);
721        });
722    }
723}