From 511344e86c59ceb3931d5e7bc1fef20e9dd0e214 Mon Sep 17 00:00:00 2001
From: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
Date: Wed, 2 Mar 2022 21:52:42 +0000
Subject: [PATCH] Remove balancing iterations from OCW miners (#4995)

* remove random balancing from unsigned solution

* tweak miner a bit

* add comments

* lower kusama staking limits

* Revert "lower kusama staking limits"

This reverts commit 8ccccbb65a97b78505ef71a796698bb067cc6ba0.

* Update utils/staking-miner/src/dry_run.rs

Co-authored-by: Niklas Adolfsson <niklasadolfsson1@gmail.com>

* last review

Co-authored-by: Niklas Adolfsson <niklasadolfsson1@gmail.com>
---
 polkadot/runtime/common/src/elections.rs    | 27 ---------------------
 polkadot/runtime/kusama/src/lib.rs          |  2 +-
 polkadot/runtime/polkadot/src/lib.rs        |  2 +-
 polkadot/runtime/westend/src/lib.rs         |  2 +-
 polkadot/utils/staking-miner/src/dry_run.rs | 16 +++++++-----
 polkadot/utils/staking-miner/src/main.rs    | 13 +++++++---
 polkadot/utils/staking-miner/src/signer.rs  |  8 +++++-
 7 files changed, 30 insertions(+), 40 deletions(-)

diff --git a/polkadot/runtime/common/src/elections.rs b/polkadot/runtime/common/src/elections.rs
index 264df416bb5..87a0a318eb9 100644
--- a/polkadot/runtime/common/src/elections.rs
+++ b/polkadot/runtime/common/src/elections.rs
@@ -66,33 +66,6 @@ pub type OnOnChainAccuracy = sp_runtime::Perbill;
 pub type GenesisElectionOf<T> =
 	frame_election_provider_support::onchain::OnChainSequentialPhragmen<T>;
 
-/// Maximum number of iterations for balancing that will be executed in the embedded miner of
-/// pallet-election-provider-multi-phase.
-pub const MINER_MAX_ITERATIONS: u32 = 10;
-
-/// A source of random balance for the NPoS Solver, which is meant to be run by the off-chain worker
-/// election miner.
-pub struct OffchainRandomBalancing;
-impl frame_support::pallet_prelude::Get<Option<(usize, sp_npos_elections::ExtendedBalance)>>
-	for OffchainRandomBalancing
-{
-	fn get() -> Option<(usize, sp_npos_elections::ExtendedBalance)> {
-		use sp_runtime::{codec::Decode, traits::TrailingZeroInput};
-		let iters = match MINER_MAX_ITERATIONS {
-			0 => 0,
-			max @ _ => {
-				let seed = sp_io::offchain::random_seed();
-				let random = <u32>::decode(&mut TrailingZeroInput::new(&seed))
-					.expect("input is padded with zeroes; qed") %
-					max.saturating_add(1);
-				random as usize
-			},
-		};
-
-		Some((iters, 0))
-	}
-}
-
 /// Implementation of `frame_election_provider_support::SortedListProvider` that updates the
 /// bags-list but uses [`pallet_staking::Nominators`] for `iter`. This is meant to be a transitionary
 /// implementation for runtimes to "test" out the bags-list by keeping it up to date, but not yet
diff --git a/polkadot/runtime/kusama/src/lib.rs b/polkadot/runtime/kusama/src/lib.rs
index 83a08b0377a..3b7cfe528c0 100644
--- a/polkadot/runtime/kusama/src/lib.rs
+++ b/polkadot/runtime/kusama/src/lib.rs
@@ -453,7 +453,7 @@ impl pallet_election_provider_multi_phase::Config for Runtime {
 	type Solver = frame_election_provider_support::SequentialPhragmen<
 		AccountId,
 		pallet_election_provider_multi_phase::SolutionAccuracyOf<Self>,
-		runtime_common::elections::OffchainRandomBalancing,
+		(),
 	>;
 	type BenchmarkingConfig = runtime_common::elections::BenchmarkConfig;
 	type ForceOrigin = EnsureOneOf<
diff --git a/polkadot/runtime/polkadot/src/lib.rs b/polkadot/runtime/polkadot/src/lib.rs
index 2df03a48787..baef4169ea3 100644
--- a/polkadot/runtime/polkadot/src/lib.rs
+++ b/polkadot/runtime/polkadot/src/lib.rs
@@ -494,7 +494,7 @@ impl pallet_election_provider_multi_phase::Config for Runtime {
 	type Solver = frame_election_provider_support::SequentialPhragmen<
 		AccountId,
 		pallet_election_provider_multi_phase::SolutionAccuracyOf<Self>,
-		runtime_common::elections::OffchainRandomBalancing,
+		(),
 	>;
 	type BenchmarkingConfig = runtime_common::elections::BenchmarkConfig;
 	type ForceOrigin = EnsureOneOf<
diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs
index db665417a5f..0fdad6852d6 100644
--- a/polkadot/runtime/westend/src/lib.rs
+++ b/polkadot/runtime/westend/src/lib.rs
@@ -404,7 +404,7 @@ impl pallet_election_provider_multi_phase::Config for Runtime {
 	type Solver = frame_election_provider_support::SequentialPhragmen<
 		AccountId,
 		pallet_election_provider_multi_phase::SolutionAccuracyOf<Self>,
-		runtime_common::elections::OffchainRandomBalancing,
+		(),
 	>;
 	type BenchmarkingConfig = runtime_common::elections::BenchmarkConfig;
 	type ForceOrigin = EnsureRoot<AccountId>;
diff --git a/polkadot/utils/staking-miner/src/dry_run.rs b/polkadot/utils/staking-miner/src/dry_run.rs
index 7c11f7ee106..89814faf367 100644
--- a/polkadot/utils/staking-miner/src/dry_run.rs
+++ b/polkadot/utils/staking-miner/src/dry_run.rs
@@ -115,13 +115,17 @@ macro_rules! dry_run_cmd_for { ($runtime:ident) => { paste::paste! {
 		signer: Signer,
 	) -> Result<(), Error<$crate::[<$runtime _runtime_exports>]::Runtime>> {
 		use $crate::[<$runtime _runtime_exports>]::*;
-		let mut ext = crate::create_election_ext::<Runtime, Block>(
-			rpc.clone(),
-			config.at,
-			vec!["Staking".to_string(), "System".to_string()],
-		).await?;
-		force_create_snapshot::<Runtime>(&mut ext)?;
+		let pallets = if config.force_snapshot {
+			vec!["Staking".to_string(), "BagsList".to_string()]
+		} else {
+			Default::default()
+		};
+		let mut ext = crate::create_election_ext::<Runtime, Block>(rpc.clone(), config.at, pallets).await?;
+		if config.force_snapshot {
+			force_create_snapshot::<Runtime>(&mut ext)?;
+		};
 
+		log::debug!(target: LOG_TARGET, "solving with {:?}", config.solver);
 		let (raw_solution, witness) = crate::mine_with::<Runtime>(&config.solver, &mut ext, false)?;
 
 		let nonce = crate::get_account_info::<Runtime>(&rpc, &signer.account, config.at)
diff --git a/polkadot/utils/staking-miner/src/main.rs b/polkadot/utils/staking-miner/src/main.rs
index 045a849eee5..449a643e22b 100644
--- a/polkadot/utils/staking-miner/src/main.rs
+++ b/polkadot/utils/staking-miner/src/main.rs
@@ -343,6 +343,10 @@ struct DryRunConfig {
 	/// The solver algorithm to use.
 	#[clap(subcommand)]
 	solver: Solvers,
+
+	/// Force create a new snapshot, else expect one to exist onchain.
+	#[clap(long)]
+	force_snapshot: bool,
 }
 
 #[derive(Debug, Clone, Parser)]
@@ -351,12 +355,15 @@ struct SharedConfig {
 	#[clap(long, short, default_value = DEFAULT_URI, env = "URI")]
 	uri: String,
 
-	/// The seed of a funded account in hex.
+	/// The path to a file containing the seed of the account. If the file is not found, the seed is
+	/// used as-is.
+	///
+	/// Can also be provided via the `SEED` environment variable.
 	///
 	/// WARNING: Don't use an account with a large stash for this. Based on how the bot is
 	/// configured, it might re-try and lose funds through transaction fees/deposits.
 	#[clap(long, short, env = "SEED")]
-	seed: String,
+	seed_or_path: String,
 }
 
 #[derive(Debug, Clone, Parser)]
@@ -590,7 +597,7 @@ async fn main() {
 	};
 
 	let signer_account = any_runtime! {
-		signer::signer_uri_from_string::<Runtime>(&shared.seed, &rpc)
+		signer::signer_uri_from_string::<Runtime>(&shared.seed_or_path, &rpc)
 			.await
 			.expect("Provided account is invalid, terminating.")
 	};
diff --git a/polkadot/utils/staking-miner/src/signer.rs b/polkadot/utils/staking-miner/src/signer.rs
index 6a0e45eabb1..6a805338597 100644
--- a/polkadot/utils/staking-miner/src/signer.rs
+++ b/polkadot/utils/staking-miner/src/signer.rs
@@ -57,9 +57,15 @@ pub(crate) async fn signer_uri_from_string<
 			Hash = Hash,
 		> + EPM::Config,
 >(
-	seed: &str,
+	mut seed_or_path: &str,
 	client: &SharedRpcClient,
 ) -> Result<Signer, Error<T>> {
+	seed_or_path = seed_or_path.trim();
+
+	let seed = match std::fs::read(seed_or_path) {
+		Ok(s) => String::from_utf8(s).map_err(|_| Error::<T>::AccountDoesNotExists)?,
+		Err(_) => seed_or_path.to_string(),
+	};
 	let seed = seed.trim();
 
 	let pair = Pair::from_string(seed, None)?;
-- 
GitLab