referrerpolicy=no-referrer-when-downgrade

normalize/
normalize.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 normalize`. `honggfuzz` CLI options can
20//! 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 normalize hfuzz_workspace/normalize/*.fuzz`.
25
26use honggfuzz::fuzz;
27use sp_arithmetic::Normalizable;
28
29type Ty = u64;
30
31fn main() {
32	let sum_limit = Ty::max_value() as u128;
33	let len_limit: usize = Ty::max_value().try_into().unwrap();
34
35	loop {
36		fuzz!(|data: (Vec<Ty>, Ty)| {
37			let (data, norm) = data;
38			if data.is_empty() {
39				return
40			}
41			let pre_sum: u128 = data.iter().map(|x| *x as u128).sum();
42
43			let normalized = data.normalize(norm);
44			// error cases.
45			if pre_sum > sum_limit || data.len() > len_limit {
46				assert!(normalized.is_err())
47			} else if let Ok(normalized) = normalized {
48				// if sum goes beyond u128, panic.
49				let sum: u128 = normalized.iter().map(|x| *x as u128).sum();
50
51				// if this function returns Ok(), then it will ALWAYS be accurate.
52				assert_eq!(sum, norm as u128, "sums don't match {:?}, {}", normalized, norm);
53			} else {
54				panic!("Should have returned Ok for input = {:?}, target = {:?}", data, norm);
55			}
56		})
57	}
58}