From 104dee9376ea7abdc16b39eab74317af19a359e9 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Mon, 29 Jan 2024 07:28:04 +1100 Subject: [PATCH] Debug assert that target != zero in difficulty calc 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. --- bitcoin/src/pow.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/bitcoin/src/pow.rs b/bitcoin/src/pow.rs index e99aead2..6292a822 100644 --- a/bitcoin/src/pow.rs +++ b/bitcoin/src/pow.rs @@ -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,