Skip to content

sp-arithmetic: add checked functions and extend fuzzer coverage #8472

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 37 additions & 0 deletions prdoc/pr_8472.prdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
title: add checked functions and extend fuzzer coverage
doc:
- audience: Runtime Dev
description: |
Changes:
- `helpers_128bit.rs`:
- Added `checked_multiply_by_rational_with_rounding`.
- Proper use of `ArithmeticError`.
- Added test for introduced checked versions.
- `per_things.rs`:
- Added `checked_*` versions of `square`, `mul_floor`, `mul_ceil`, `overflow_prune_mul`, `rational_mul_correction` `saturating_reciprocal_mul`, `saturating_reciprocal_mul_floor`, `saturating_reciprocal_mul_ceil` and `from_rational_with_rounding` to the `PerThing` trait and their implementations within `implement_per_thing` the macro where it applies.
- Added additional `checked_int_div` and `checked_div_with_rounding`.
- Added tests for the newly `checked_*` additions in `checked_reciprocal_mul_works`, `checked_from_rational_works`, `checked_arithmetic_works` and `checked_int_div_works`.
- Proper use of `ArithmeticError`.
- Added test for introduced checked versions.
- `fixed_point.rs`:
- Added `try_into_perbill` which is a checked version of `into_perbill`.
- Added checked version of `from_rational_with_rounding`.
- Proper use of `ArithmeticError`.
- `rational.rs`:
- Added `checked_to_den` and `checked_lcm`.
- Updated `checked_add` and `checked_sub` to follow the pattern of other checked versions.
- Simplified import of `helpers_128bit`.
- Proper use of `ArithmeticError`.
- Added test for introduced checked versions.
- `fuzzing`:
- `per_thing_checked_arith.rs`: Covers general `PerThing` checked arithmetic operations (`checked_mul_floor`, `checked_mul_ceil`, reciprocal multiplications, `checked_square`, `checked_div_with_rounding`, `checked_int_div`).
- `fixed_utils.rs`: Covers `FixedPointNumber` utility functions (`trunc`, `frac`, `ceil`, `floor`, `round`).
- `fixed_to_perbill.rs`: Covers conversions of `try_into_perbill`
- `fixed_to_perthing.rs`: Covers conversions of `try_into_perthing`.
- `fixed_rounding_ops.rs`: Specifically fuzzes `const_checked_mul_with_rounding` and `checked_rounding_div` for `FixedPointNumber` types, testing all 8 `SignedRounding` modes.
- `per_thing_checked_from_rational.rs`: Covers `PerThing::checked_from_rational_with_rounding` comparing against the non-checked version and validating error handling.
- `fixed_checked_ops.rs`: Covers core `FixedPointNumber` checked arithmetic operations (`add`, `sub`, `mul`, `div`, `from_integer`, `from_rational`, `mul_int`, `div_int`, `sqrt`) for `FixedI64`, `FixedU64`, `FixedI128`, and `FixedU128`, using `BigInt` for oracle comparisons and overflow detection.
- `checked_mul_by_rational.rs`: Covers `helpers_128bit::checked_multiply_by_rational_with_rounding` with different rounding modes and error conditions (DivisionByZero, Overflow).
crates:
- name: sp-arithmetic
bump: minor
33 changes: 33 additions & 0 deletions substrate/primitives/arithmetic/fuzzer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,42 @@ path = "src/multiply_by_rational_with_rounding.rs"
name = "fixed_point"
path = "src/fixed_point.rs"

[[bin]]
name = "checked_mul_by_rational"
path = "src/checked_mul_by_rational.rs"

[[bin]]
name = "per_thing_checked_from_rational"
path = "src/per_thing_checked_from_rational.rs"

[[bin]]
name = "fixed_checked_ops"
path = "src/fixed_checked_ops.rs"

[[bin]]
name = "per_thing_checked_arith"
path = "src/per_thing_checked_arith.rs"

[[bin]]
name = "fixed_utils"
path = "src/fixed_utils.rs"

[[bin]]
name = "fixed_to_perbill"
path = "src/fixed_to_perbill.rs"

[[bin]]
name = "fixed_to_perthing"
path = "src/fixed_to_perthing.rs"

[[bin]]
name = "fixed_rounding_ops"
path = "src/fixed_rounding_ops.rs"

[dependencies]
arbitrary = { workspace = true }
fraction = { workspace = true }
honggfuzz = { workspace = true }
num-bigint = { workspace = true }
num-traits = { workspace = true }
sp-arithmetic = { workspace = true, default-features = true }
108 changes: 108 additions & 0 deletions substrate/primitives/arithmetic/fuzzer/src/checked_mul_by_rational.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! # Running
//! Running this fuzzer can be done with `cargo hfuzz run checked_mul_by_rational`.
//! `honggfuzz` CLI options can be used by setting `HFUZZ_RUN_ARGS`, such as `-n 4` to use 4
//! threads.
//!
//! # Debugging a panic
//! Once a panic is found, it can be debugged with
//! `cargo hfuzz run-debug checked_mul_by_rational hfuzz_workspace/checked_mul_by_rational/*.fuzz`.
//!
//! # More information
//! More information about `honggfuzz` can be found
//! [here](https://docs.rs/honggfuzz/).

use honggfuzz::fuzz;
use sp_arithmetic::{
helpers_128bit::{
checked_multiply_by_rational_with_rounding, multiply_by_rational_with_rounding,
},
ArithmeticError, Rounding,
Rounding::{Down, NearestPrefDown, NearestPrefUp, Up},
};

#[derive(Debug, Clone, Copy)]
struct ArbitraryRounding(Rounding);

impl arbitrary::Arbitrary<'_> for ArbitraryRounding {
fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
Ok(Self(match u.int_in_range(0..=3)? {
0 => Up,
1 => NearestPrefUp,
2 => Down,
3 => NearestPrefDown,
_ => unreachable!(),
}))
}
}

fn main() {
loop {
fuzz!(|data: (u128, u128, u128, ArbitraryRounding)| {
let (a, b, c, arbitrary_rounding) = data;
let r = arbitrary_rounding.0;

let checked_res = checked_multiply_by_rational_with_rounding(a, b, c, r);
let non_checked_res = multiply_by_rational_with_rounding(a, b, c, r);

if c == 0 {
assert_eq!(
checked_res,
Err(ArithmeticError::DivisionByZero),
"Denominator 0: checked failed. a={}, b={}, c={}, r={:?}",
a,
b,
c,
r
);
assert_eq!(
non_checked_res, None,
"Denominator 0: non-checked failed. a={}, b={}, c={}, r={:?}",
a, b, c, r
);
} else {
match non_checked_res {
Some(val_non_checked) => {
assert_eq!(
checked_res,
Ok(val_non_checked),
"Non-checked Some, Checked Ok mismatch. a={}, b={}, c={}, r={:?}",
a,
b,
c,
r
);
},
None => {
// This implies an overflow for the non-checked version.
assert_eq!(
checked_res,
Err(ArithmeticError::Overflow),
"Non-checked None, Checked Overflow mismatch. a={}, b={}, c={}, r={:?}",
a,
b,
c,
r
);
},
}
}
});
}
}
Loading
Loading