Skip to content

Commit

Permalink
feat: prevent possible division by zero in difficulty calculation (#5828
Browse files Browse the repository at this point in the history
)

Description
---
Prevented possible division by zero panic in `fn
u256_scalar_to_difficulty(scalar: U256) -> Result<Difficulty,
DifficultyError>`

Motivation and Context
---
Code should not be able to panic.

How Has This Been Tested?
---
Unit test added

What process can a PR reviewer use to test or verify this change?
---
Code walkthrough

<!-- Checklist -->
<!-- 1. Is the title of your PR in the form that would make nice release
notes? The title, excluding the conventional commit
tag, will be included exactly as is in the CHANGELOG, so please think
about it carefully. -->


Breaking Changes
---

- [x] None
- [ ] Requires data directory on base node to be deleted
- [ ] Requires hard fork
- [ ] Other - Please specify

<!-- Does this include a breaking change? If so, include this line as a
footer -->
<!-- BREAKING CHANGE: Description what the user should do, e.g. delete a
database, resync the chain -->
  • Loading branch information
hansieodendaal committed Oct 3, 2023
1 parent 754fb16 commit f85a878
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
13 changes: 13 additions & 0 deletions base_layer/core/src/proof_of_work/difficulty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ impl Difficulty {
}

fn u256_scalar_to_difficulty(scalar: U256) -> Result<Difficulty, DifficultyError> {
if scalar == U256::zero() {
return Err(DifficultyError::DivideByZero);
}
let result = U256::MAX / scalar;
let result = result.min(u64::MAX.into());
Difficulty::from_u64(result.low_u64())
Expand Down Expand Up @@ -285,4 +288,14 @@ mod test {
Difficulty::from_u64(expected).unwrap()
);
}

#[test]
fn u256_scalar_to_difficulty_division_by_zero() {
let bytes = [];
assert!(Difficulty::little_endian_difficulty(&bytes).is_err());
assert!(Difficulty::big_endian_difficulty(&bytes).is_err());
let bytes = [0u8; 32];
assert!(Difficulty::little_endian_difficulty(&bytes).is_err());
assert!(Difficulty::big_endian_difficulty(&bytes).is_err());
}
}
2 changes: 2 additions & 0 deletions base_layer/core/src/proof_of_work/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,6 @@ pub enum DifficultyError {
InvalidDifficulty,
#[error("Maximum block time overflowed u64")]
MaxBlockTimeOverflow,
#[error("Divide by zero")]
DivideByZero,
}

0 comments on commit f85a878

Please sign in to comment.