Merge rust-bitcoin/rust-bitcoin#3438: Implement Arbitrary for Block

0c824c9c68 Implement Arbitrary for Block (Shing Him Ng)

Pull request description:

  Implementing `Arbitrary` for `Block` and its child types

ACKs for top commit:
  apoelstra:
    ACK 0c824c9c68 successfully ran local tests
  tcharding:
    ACK 0c824c9c68

Tree-SHA512: 407acd4155ca7496bf7c59af19f103b22b4c74dd013c2e2c42aae690ba7264ecd42ed034355cf8895f2532f8cef77dfdbeac250301a6973afd5f3920be7e4310
This commit is contained in:
Andrew Poelstra 2024-10-12 13:41:44 +00:00
commit 76f022d380
2 changed files with 42 additions and 0 deletions

View File

@ -12,6 +12,8 @@ use core::fmt;
use hashes::{sha256d, HashEngine}; use hashes::{sha256d, HashEngine};
use internals::compact_size; use internals::compact_size;
use io::{BufRead, Write}; use io::{BufRead, Write};
#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};
use super::Weight; use super::Weight;
use crate::consensus::{encode, Decodable, Encodable}; use crate::consensus::{encode, Decodable, Encodable};
@ -400,6 +402,30 @@ impl std::error::Error for ValidationError {
} }
} }
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Header {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Header {
version: Version::arbitrary(u)?,
prev_blockhash: BlockHash::from_byte_array(u.arbitrary()?),
merkle_root: TxMerkleNode::from_byte_array(u.arbitrary()?),
time: u.arbitrary()?,
bits: CompactTarget::from_consensus(u.arbitrary()?),
nonce: u.arbitrary()?
})
}
}
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Block {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Block {
header: Header::arbitrary(u)?,
txdata: Vec::<Transaction>::arbitrary(u)?,
})
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use hex::{test_hex_unwrap as hex, FromHex}; use hex::{test_hex_unwrap as hex, FromHex};

View File

@ -8,6 +8,8 @@
//! these blocks and the blockchain. //! these blocks and the blockchain.
use hashes::sha256d; use hashes::sha256d;
#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};
/// Bitcoin block version number. /// Bitcoin block version number.
/// ///
@ -90,3 +92,17 @@ impl BlockHash {
/// Dummy hash used as the previous blockhash of the genesis block. /// Dummy hash used as the previous blockhash of the genesis block.
pub const GENESIS_PREVIOUS_BLOCK_HASH: Self = Self::from_byte_array([0; 32]); pub const GENESIS_PREVIOUS_BLOCK_HASH: Self = Self::from_byte_array([0; 32]);
} }
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Version {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
// Equally weight known versions and arbitrary versions
let choice = u.int_in_range(0..=3)?;
match choice {
0 => Ok(Version::ONE),
1 => Ok(Version::TWO),
2 => Ok(Version::NO_SOFT_FORK_SIGNALLING),
_ => Ok(Version::from_consensus(u.arbitrary()?))
}
}
}