Skip to content

Commit

Permalink
Debug assert that target != zero in difficulty calc
Browse files Browse the repository at this point in the history
The `difficulty` calculation requires dividing a target value by `self`.
Add an assertion that `self` is not zero to help devs debug this.

Note that this should never really be hit, but its possible there is a
bug somewhere causing the target to be set to zero - so this may help
debugging.

Also, add panics section to rustdocs.
  • Loading branch information
tcharding committed Apr 2, 2024
1 parent c1ba496 commit 104dee9
Showing 1 changed file with 7 additions and 0 deletions.
7 changes: 7 additions & 0 deletions bitcoin/src/pow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,10 +227,17 @@ impl Target {
/// integer but `difficulty()` returns only 128 bits this means for targets below approximately
/// `0xffff_ffff_ffff_ffff_ffff_ffff` `difficulty()` will saturate at `u128::MAX`.
///
/// # Panics
///
/// Panics if `self` is zero (divide by zero).
///
/// [max]: Target::max
/// [target]: crate::blockdata::block::Header::target
#[cfg_attr(all(test, mutate), mutate)]
pub fn difficulty(&self, network: Network) -> u128 {
// Panic here may be eaiser to debug than during the actual division.
assert_ne!(self.0, U256::ZERO, "divide by zero");

let max = match network {
Network::Bitcoin => Target::MAX_ATTAINABLE_MAINNET,
Network::Testnet => Target::MAX_ATTAINABLE_TESTNET,
Expand Down

0 comments on commit 104dee9

Please sign in to comment.