bitcoin/blockdata/
block.rs

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