Skip to content
Merged
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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@ Cargo.lock

# all the key files
*.key

# output files from cmds
encoded.call
solution.supports.bin
71 changes: 65 additions & 6 deletions src/commands/emergency_solution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@

//! The emergency-solution command.

use crate::{error::Error, opt::Solver, prelude::*, static_types};
use crate::{epm, error::Error, opt::Solver, prelude::*, static_types};
use clap::Parser;
use codec::Encode;
use sp_core::hexdisplay::HexDisplay;
use std::io::Write;
use subxt::tx::TxPayload;

#[derive(Debug, Clone, Parser)]
#[cfg_attr(test, derive(PartialEq))]
Expand All @@ -30,13 +34,13 @@ pub struct EmergencySolutionConfig {
#[clap(subcommand)]
pub solver: Solver,

/// The number of top backed winners to take. All are taken, if not provided.
pub take: Option<usize>,
/// The number of top backed winners to take instead. All are taken, if not provided.
pub force_winner_count: Option<u32>,
}

pub async fn emergency_solution_cmd<T>(
_api: SubxtClient,
_config: EmergencySolutionConfig,
api: SubxtClient,
config: EmergencySolutionConfig,
) -> Result<(), Error>
where
T: MinerConfig<AccountId = AccountId, MaxVotesPerVoter = static_types::MaxVotesPerVoter>
Expand All @@ -45,5 +49,60 @@ where
+ 'static,
T::Solution: Send,
{
todo!("not possible to implement yet");
if let Some(max_winners) = config.force_winner_count {
static_types::MaxWinners::set(max_winners);
}

let round = api
.storage()
.at(config.at)
.await?
.fetch_or_default(&runtime::storage().election_provider_multi_phase().round())
.await?;

let miner_solution = epm::fetch_snapshot_and_mine_solution::<T>(
&api,
config.at,
config.solver,
round,
config.force_winner_count,
)
.await?;

let ready_solution = miner_solution.feasibility_check()?;
let encoded_size = ready_solution.encoded_size();
let score = ready_solution.score;

let mut supports = ready_solution.supports.into_inner();

// maybe truncate.
if let Some(force_winner_count) = config.force_winner_count {
log::info!(
target: LOG_TARGET,
"truncating {} winners to {}",
supports.len(),
force_winner_count
);
supports.sort_unstable_by_key(|(_, s)| s.total);
supports.truncate(force_winner_count as usize);
}

let call = epm::set_emergency_result(supports.clone())?;
let encoded_call = call.encode_call_data(&api.metadata())?;
let encoded_supports = supports.encode();

// write results to files.
let mut supports_file = std::fs::File::create("solution.supports.bin")?;
let mut encoded_call_file = std::fs::File::create("encoded.call")?;
supports_file.write_all(&encoded_supports)?;
encoded_call_file.write_all(&encoded_call)?;

let hex = HexDisplay::from(&encoded_call);
log::info!(target: LOG_TARGET, "Hex call:\n {:?}", hex);

log::info!(target: LOG_TARGET, "Use the hex encoded call above to construct the governance proposal or the extrinsic to submit.");
log::info!(target: LOG_TARGET, "ReadySolution: size {:?} / score = {:?}", encoded_size, score);
log::info!(target: LOG_TARGET, "`set_emergency_result` encoded call written to ./encoded.call");

Ok(())
}
4 changes: 2 additions & 2 deletions src/commands/monitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ where
.inspect_err(|e| log::error!(target: LOG_TARGET, "Mining solution failed: {:?}", e))
.await?;

ensure_no_previous_solution::<T::Solution>(&api, hash, signer.account_id())
ensure_no_previous_solution::<T::Solution>(&api, hash, &signer.account_id().0.into())
.inspect_err(|e| {
log::debug!(
target: LOG_TARGET,
Expand Down Expand Up @@ -367,7 +367,7 @@ where
})
.await?;

ensure_no_previous_solution::<T::Solution>(&api, best_head, signer.account_id())
ensure_no_previous_solution::<T::Solution>(&api, best_head, &signer.account_id().0.into())
.inspect_err(|e| {
log::debug!(
target: LOG_TARGET,
Expand Down
22 changes: 18 additions & 4 deletions src/epm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use crate::{
use codec::{Decode, Encode};
use frame_election_provider_support::{NposSolution, PhragMMS, SequentialPhragmen};
use frame_support::weights::Weight;
use pallet_election_provider_multi_phase::{RawSolution, SolutionOrSnapshotSize};
use pallet_election_provider_multi_phase::{RawSolution, ReadySolution, SolutionOrSnapshotSize};
use scale_info::{PortableRegistry, TypeInfo};
use scale_value::scale::{decode_as_type, TypeId};
use sp_core::Bytes;
Expand Down Expand Up @@ -67,7 +67,8 @@ pub(crate) async fn update_metadata_constants(api: &SubxtClient) -> Result<(), E
const SIGNED_MAX_WEIGHT: EpmConstant = EpmConstant::new("SignedMaxWeight");
const MAX_LENGTH: EpmConstant = EpmConstant::new("MinerMaxLength");
const MAX_VOTES_PER_VOTER: EpmConstant = EpmConstant::new("MinerMaxVotesPerVoter");
const MAX_WINNERS: EpmConstant = EpmConstant::new("MinerMaxWinners");
// NOTE: `MaxWinners` is used instead of `MinerMaxWinners` to work with older metadata.
const MAX_WINNERS: EpmConstant = EpmConstant::new("MaxWinners");
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, this was set to work with older metadata right?

Smart move as this is just duplicated in the MinerConfig :P

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add a comment for that :)


fn log_metadata(metadata: EpmConstant, val: impl std::fmt::Display) {
log::trace!(target: LOG_TARGET, "updating metadata constant `{metadata}`: {val}",);
Expand Down Expand Up @@ -112,6 +113,16 @@ fn read_constant<'a, T: serde::Deserialize<'a>>(
})
}

/// Helper to construct a set emergency solution transaction.
pub(crate) fn set_emergency_result<A: Encode + TypeInfo + 'static>(
supports: frame_election_provider_support::Supports<A>,
) -> Result<DynamicTxPayload<'static>, Error> {
let scale_result = to_scale_value(supports)
.map_err(|e| Error::DynamicTransaction(format!("Failed to encode `Supports`: {:?}", e)))?;

Ok(subxt::dynamic::tx(EPM_PALLET_NAME, "set_emergency_election_result", vec![scale_result]))
}

/// Helper to construct a signed solution transaction.
pub fn signed_solution<S: NposSolution + Encode + TypeInfo + 'static>(
solution: RawSolution<S>,
Expand Down Expand Up @@ -169,6 +180,7 @@ pub async fn snapshot_at(at: Option<Hash>, api: &SubxtClient) -> Result<RoundSna
}

/// Helper to fetch snapshot data via RPC

/// and compute an NPos solution via [`pallet_election_provider_multi_phase`].
pub async fn fetch_snapshot_and_mine_solution<T>(
api: &SubxtClient,
Expand Down Expand Up @@ -272,7 +284,9 @@ where
}

/// Check that this solution is feasible
pub fn feasibility_check(&self) -> Result<(), Error> {
///
/// Returns a [`pallet_election_provider_multi_phase::ReadySolution`] if the check passes.
pub fn feasibility_check(&self) -> Result<ReadySolution<AccountId, T::MaxWinners>, Error> {
match Miner::<T>::feasibility_check(
RawSolution { solution: self.solution.clone(), score: self.score, round: self.round },
pallet_election_provider_multi_phase::ElectionCompute::Signed,
Expand All @@ -281,7 +295,7 @@ where
self.round,
self.minimum_untrusted_score,
) {
Ok(_) => Ok(()),
Ok(ready_solution) => Ok(ready_solution),
Err(e) => {
log::error!(target: LOG_TARGET, "Solution feasibility error {:?}", e);
Err(Error::Feasibility(format!("{:?}", e)))
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ mod tests {
prometheus_port: None,
log: "info".to_string(),
command: Command::EmergencySolution(commands::EmergencySolutionConfig {
take: Some(99),
force_winner_count: Some(99),
at: None,
solver: opt::Solver::PhragMMS { iterations: 1337 },
}),
Expand Down
2 changes: 1 addition & 1 deletion src/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub use pallet_election_provider_multi_phase::{Miner, MinerConfig};
pub use subxt::ext::sp_core;

/// The account id type.
pub type AccountId = subxt::utils::AccountId32;
pub type AccountId = sp_runtime::AccountId32;
/// The header type. We re-export it here, but we can easily get it from block as well.
pub type Header =
subxt::config::substrate::SubstrateHeader<u32, subxt::config::substrate::BlakeTwo256>;
Expand Down