referrerpolicy=no-referrer-when-downgrade

phragmen_balancing/
phragmen_balancing.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//! Fuzzing for sequential phragmen with potential balancing.
19
20mod common;
21
22use common::*;
23use honggfuzz::fuzz;
24use rand::{self, SeedableRng};
25use sp_npos_elections::{
26	assignment_ratio_to_staked_normalized, seq_phragmen, to_supports, BalancingConfig,
27	ElectionResult, EvaluateSupport, VoteWeight,
28};
29use sp_runtime::Perbill;
30
31fn main() {
32	loop {
33		fuzz!(|data: (usize, usize, usize, usize, u64)| {
34			let (mut target_count, mut voter_count, mut iterations, mut to_elect, seed) = data;
35			let rng = rand::rngs::SmallRng::seed_from_u64(seed);
36			target_count = to_range(target_count, 100, 200);
37			voter_count = to_range(voter_count, 100, 200);
38			iterations = to_range(iterations, 0, 30);
39			to_elect = to_range(to_elect, 25, target_count);
40
41			println!(
42				"++ [voter_count: {} / target_count:{} / to_elect:{} / iterations:{}]",
43				voter_count, target_count, to_elect, iterations,
44			);
45			let (unbalanced, candidates, voters, stake_of_tree) = generate_random_npos_result(
46				voter_count as u64,
47				target_count as u64,
48				to_elect,
49				rng,
50				ElectionType::Phragmen(None),
51			);
52
53			let stake_of = |who: &AccountId| -> VoteWeight { *stake_of_tree.get(who).unwrap() };
54
55			let unbalanced_score = {
56				let staked =
57					assignment_ratio_to_staked_normalized(unbalanced.assignments, &stake_of)
58						.unwrap();
59				let score = to_supports(staked.as_ref()).evaluate();
60
61				if score.minimal_stake == 0 {
62					// such cases cannot be improved by balancing.
63					return
64				}
65				score
66			};
67
68			if iterations > 0 {
69				let config = BalancingConfig { iterations, tolerance: 0 };
70				let balanced: ElectionResult<AccountId, sp_runtime::Perbill> =
71					seq_phragmen(to_elect, candidates, voters, Some(config)).unwrap();
72
73				let balanced_score = {
74					let staked =
75						assignment_ratio_to_staked_normalized(balanced.assignments, &stake_of)
76							.unwrap();
77					to_supports(staked.as_ref()).evaluate()
78				};
79
80				let enhance =
81					balanced_score.strict_threshold_better(unbalanced_score, Perbill::zero());
82
83				println!(
84					"iter = {} // {:?} -> {:?} [{}]",
85					iterations, unbalanced_score, balanced_score, enhance,
86				);
87
88				// The only guarantee of balancing is such that the first and third element of the
89				// score cannot decrease.
90				assert!(
91					balanced_score.minimal_stake >= unbalanced_score.minimal_stake &&
92						balanced_score.sum_stake == unbalanced_score.sum_stake &&
93						balanced_score.sum_stake_squared <= unbalanced_score.sum_stake_squared
94				);
95			}
96		});
97	}
98}