per_thing_mult_fraction/per_thing_mult_fraction.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! # Running
19//! Running this fuzzer can be done with `cargo hfuzz run per_thing_mult_fraction`. `honggfuzz` CLI
20//! options can be used by setting `HFUZZ_RUN_ARGS`, such as `-n 4` to use 4 threads.
21//!
22//! # Debugging a panic
23//! Once a panic is found, it can be debugged with
24//! `cargo hfuzz run-debug per_thing_mult_fraction hfuzz_workspace/per_thing_mult_fraction/*.fuzz`.
25
26use honggfuzz::fuzz;
27use sp_arithmetic::{PerThing, Perbill, Percent, Perquintill, *};
28
29/// Tries to disprove `(n / d) * d <= n` for any `PerThing`s.
30fn main() {
31 loop {
32 fuzz!(|data: (u128, u128)| {
33 let (n, d) = (data.0.min(data.1), data.0.max(data.1).max(1));
34
35 check_mul::<PerU16>(n, d);
36 check_mul::<Percent>(n, d);
37 check_mul::<Perbill>(n, d);
38 check_mul::<Perquintill>(n, d);
39
40 check_reciprocal_mul::<PerU16>(n, d);
41 check_reciprocal_mul::<Percent>(n, d);
42 check_reciprocal_mul::<Perbill>(n, d);
43 check_reciprocal_mul::<Perquintill>(n, d);
44 })
45 }
46}
47
48/// Checks that `(n / d) * d <= n`.
49fn check_mul<P: PerThing>(n: u128, d: u128)
50where
51 P: PerThing + core::ops::Mul<u128, Output = u128>,
52{
53 let q = P::from_rational_with_rounding(n, d, Rounding::Down).unwrap();
54 assert!(q * d <= n, "{:?} * {:?} <= {:?}", q, d, n);
55}
56
57/// Checks that `n / (n / d) >= d`.
58fn check_reciprocal_mul<P: PerThing>(n: u128, d: u128)
59where
60 P: PerThing + core::ops::Mul<u128, Output = u128>,
61{
62 let q = P::from_rational_with_rounding(n, d, Rounding::Down).unwrap();
63 if q.is_zero() {
64 return
65 }
66
67 let r = q.saturating_reciprocal_mul_floor(n);
68 assert!(r >= d, "{} / ({} / {}) != {} but {}", n, n, d, d, r);
69}