Skip to content

Commit

Permalink
Merge rust-bitcoin#3403: Refine Sequence and Version Arbitrary
Browse files Browse the repository at this point in the history
…impls

9d98727 Refine Sequence and Version Arbitrary impls (Shing Him Ng)

Pull request description:

  Refine `Sequence` and `Version` `Arbitrary` impls with an equal weighting for special cases and the arbitrary case

  Idea originally posted here: rust-bitcoin#3363 (comment)

ACKs for top commit:
  tcharding:
    ACK 9d98727
  apoelstra:
    ACK 9d98727 successfully ran local tests

Tree-SHA512: 3274e4423515009187abc5d7e8dd0390b2fe4295c674ae4d784981fa2ac698f63ee69453ecbb9d6d36d6ff421753b38f7148fa41b11bc5460673a603ccfeb8c5
  • Loading branch information
apoelstra committed Sep 27, 2024
2 parents be4dffb + 9d98727 commit 02a4538
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
24 changes: 22 additions & 2 deletions primitives/src/sequence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,27 @@ units::impl_parse_str_from_int_infallible!(Sequence, u32, from_consensus);
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Sequence {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let s = u32::arbitrary(u)?;
Ok(Sequence(s))
let mut choice_range = 4;
if cfg!(feature = "alloc") {
choice_range = 8;
}

// Equally weight the cases of meaningful sequence numbers
let choice = u.int_in_range(0..=choice_range)?;
match choice {
0 => Ok(Sequence::MAX),
1 => Ok(Sequence::ZERO),
2 => Ok(Sequence::MIN_NO_RBF),
3 => Ok(Sequence::ENABLE_RBF_NO_LOCKTIME),
#[cfg(feature = "alloc")]
4 => Ok(Sequence::from_consensus(relative::Height::MIN.to_consensus_u32())),
#[cfg(feature = "alloc")]
5 => Ok(Sequence::from_consensus(relative::Height::MAX.to_consensus_u32())),
#[cfg(feature = "alloc")]
6 => Ok(Sequence::from_consensus(relative::Time::MIN.to_consensus_u32())),
#[cfg(feature = "alloc")]
7 => Ok(Sequence::from_consensus(relative::Time::MAX.to_consensus_u32())),
_ => Ok(Sequence(u.arbitrary()?))
}
}
}
9 changes: 7 additions & 2 deletions primitives/src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,13 @@ impl fmt::Display for Version {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Version {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let v = i32::arbitrary(u)?;
Ok(Version(v))
// Equally weight the case of normal version numbers
let choice = u.int_in_range(0..=2)?;
match choice {
0 => Ok(Version::ONE),
1 => Ok(Version::TWO),
_ => Ok(Version(u.arbitrary()?))
}
}
}

Expand Down

0 comments on commit 02a4538

Please sign in to comment.