Skip to content

Commit

Permalink
Expose valid (min, max) difficulty transition thresholds
Browse files Browse the repository at this point in the history
Once `U256` was made private, we lost the ability to check whether a
valid difficulty transition was made in the chain, since `Target`
no longer exposes any arithmetic operations.
  • Loading branch information
wpaulino committed May 2, 2023
1 parent cce8512 commit f95a3e9
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions bitcoin/src/pow.rs
Expand Up @@ -234,6 +234,34 @@ impl Target {
/// [`difficulty`]: Target::difficulty
#[cfg_attr(all(test, mutate), mutate)]
pub fn difficulty_float(&self) -> f64 { TARGET_MAX_F64 / self.0.to_f64() }

/// Computes the minimum valid [`Target`] threshold allowed for a block in which a difficulty
/// adjustment occurs. Note that the result is bounded by [`Target::MAX`].
///
/// The difficulty can only decrease or increase by a factor of 4 max on each difficulty
/// adjustment period.
pub fn min_difficulty_transition_threshold(&self) -> Self {
let min = Self(self.0 >> 2);
if min > Self::MAX {
Self::MAX
} else {
min
}
}

/// Computes the maximum valid [`Target`] threshold allowed for a block in which a difficulty
/// adjustment occurs. Note that the result is bounded by [`Target::MAX`].
///
/// The difficulty can only decrease or increase by a factor of 4 max on each difficulty
/// adjustment period.
pub fn max_difficulty_transition_threshold(&self) -> Self {
let max = Self(self.0 << 2);
if max > Self::MAX {
Self::MAX
} else {
max
}
}
}
do_impl!(Target);

Expand Down

0 comments on commit f95a3e9

Please sign in to comment.