Skip to content
Snippets Groups Projects
Commit ef198a57 authored by Niklas Adolfsson's avatar Niklas Adolfsson Committed by GitHub
Browse files

staking-miner: CLI flag delay solution x secs (#5734)


* staking-miner: CLI flag delay solution x secs

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

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

* more logging

* add more verbose logging

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

Co-authored-by: default avatarDavid <dvdplm@gmail.com>

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

Co-authored-by: default avatarDavid <dvdplm@gmail.com>

* remove redundant check

Co-authored-by: default avatarDavid <dvdplm@gmail.com>
parent bf9e324e
No related merge requests found
...@@ -87,6 +87,7 @@ async fn ensure_no_better_solution<T: EPM::Config, B: BlockT>( ...@@ -87,6 +87,7 @@ async fn ensure_no_better_solution<T: EPM::Config, B: BlockT>(
at: Hash, at: Hash,
score: sp_npos_elections::ElectionScore, score: sp_npos_elections::ElectionScore,
strategy: SubmissionStrategy, strategy: SubmissionStrategy,
max_submissions: u32,
) -> Result<(), Error<T>> { ) -> Result<(), Error<T>> {
let epsilon = match strategy { let epsilon = match strategy {
// don't care about current scores. // don't care about current scores.
...@@ -103,14 +104,38 @@ async fn ensure_no_better_solution<T: EPM::Config, B: BlockT>( ...@@ -103,14 +104,38 @@ async fn ensure_no_better_solution<T: EPM::Config, B: BlockT>(
.map_err::<Error<T>, _>(Into::into)? .map_err::<Error<T>, _>(Into::into)?
.unwrap_or_default(); .unwrap_or_default();
let mut is_best_score = true;
let mut scores = 0;
log::debug!(target: LOG_TARGET, "submitted solutions on chain: {:?}", indices);
// BTreeMap is ordered, take last to get the max score. // BTreeMap is ordered, take last to get the max score.
if let Some(curr_max_score) = indices.into_iter().last().map(|(s, _)| s) { for (curr_max_score, _) in indices.into_iter() {
if !score.strict_threshold_better(curr_max_score, epsilon) { if !score.strict_threshold_better(curr_max_score, epsilon) {
return Err(Error::StrategyNotSatisfied) log::warn!(target: LOG_TARGET, "mined score is not better; skipping to submit");
is_best_score = false;
} }
if score == curr_max_score {
log::warn!(
target: LOG_TARGET,
"mined score has the same score as already submitted score"
);
}
// Indices can't be bigger than u32::MAX so can't overflow.
scores += 1;
} }
Ok(()) if scores == max_submissions {
log::warn!(target: LOG_TARGET, "The submissions queue is full");
}
if is_best_score {
Ok(())
} else {
Err(Error::StrategyNotSatisfied)
}
} }
macro_rules! monitor_cmd_for { ($runtime:tt) => { paste::paste! { macro_rules! monitor_cmd_for { ($runtime:tt) => { paste::paste! {
...@@ -206,6 +231,8 @@ macro_rules! monitor_cmd_for { ($runtime:tt) => { paste::paste! { ...@@ -206,6 +231,8 @@ macro_rules! monitor_cmd_for { ($runtime:tt) => { paste::paste! {
ensure_signed_phase::<Runtime, Block>(&rpc1, hash).await ensure_signed_phase::<Runtime, Block>(&rpc1, hash).await
}); });
tokio::time::sleep(std::time::Duration::from_secs(config.delay as u64)).await;
let no_prev_sol_fut = tokio::spawn(async move { let no_prev_sol_fut = tokio::spawn(async move {
ensure_no_previous_solution::<Runtime, Block>(&rpc2, hash, &account).await ensure_no_previous_solution::<Runtime, Block>(&rpc2, hash, &account).await
}); });
...@@ -265,7 +292,8 @@ macro_rules! monitor_cmd_for { ($runtime:tt) => { paste::paste! { ...@@ -265,7 +292,8 @@ macro_rules! monitor_cmd_for { ($runtime:tt) => { paste::paste! {
let rpc2 = rpc.clone(); let rpc2 = rpc.clone();
let ensure_no_better_fut = tokio::spawn(async move { let ensure_no_better_fut = tokio::spawn(async move {
ensure_no_better_solution::<Runtime, Block>(&rpc1, hash, score, config.submission_strategy).await ensure_no_better_solution::<Runtime, Block>(&rpc1, hash, score, config.submission_strategy,
SignedMaxSubmissions::get()).await
}); });
let ensure_signed_phase_fut = tokio::spawn(async move { let ensure_signed_phase_fut = tokio::spawn(async move {
...@@ -273,10 +301,11 @@ macro_rules! monitor_cmd_for { ($runtime:tt) => { paste::paste! { ...@@ -273,10 +301,11 @@ macro_rules! monitor_cmd_for { ($runtime:tt) => { paste::paste! {
}); });
// Run the calls in parallel and return once all has completed or any failed. // Run the calls in parallel and return once all has completed or any failed.
if tokio::try_join!( if let Err(err) = tokio::try_join!(
flatten(ensure_no_better_fut), flatten(ensure_no_better_fut),
flatten(ensure_signed_phase_fut), flatten(ensure_signed_phase_fut),
).is_err() { ) {
log::debug!(target: LOG_TARGET, "Skipping to submit at block {}; {}", at.number, err);
return; return;
} }
......
...@@ -83,6 +83,17 @@ pub(crate) struct MonitorConfig { ...@@ -83,6 +83,17 @@ pub(crate) struct MonitorConfig {
/// `--submission-strategy "percent-better <percent>"`: submit if the submission is `n` percent better. /// `--submission-strategy "percent-better <percent>"`: submit if the submission is `n` percent better.
#[clap(long, parse(try_from_str), default_value = "if-leading")] #[clap(long, parse(try_from_str), default_value = "if-leading")]
pub submission_strategy: SubmissionStrategy, pub submission_strategy: SubmissionStrategy,
/// Delay in number seconds to wait until starting mining a solution.
///
/// At every block when a solution is attempted
/// a delay can be enforced to avoid submitting at
/// "same time" and risk potential races with other miners.
///
/// When this is enabled and there are competing solutions, your solution might not be submitted
/// if the scores are equal.
#[clap(long, parse(try_from_str), default_value_t = 0)]
pub delay: usize,
} }
#[derive(Debug, Clone, Parser)] #[derive(Debug, Clone, Parser)]
...@@ -202,6 +213,8 @@ mod test_super { ...@@ -202,6 +213,8 @@ mod test_super {
"//Alice", "//Alice",
"--listen", "--listen",
"head", "head",
"--delay",
"12",
"seq-phragmen", "seq-phragmen",
]) ])
.unwrap(); .unwrap();
...@@ -215,6 +228,7 @@ mod test_super { ...@@ -215,6 +228,7 @@ mod test_super {
listen: "head".to_string(), listen: "head".to_string(),
solver: Solver::SeqPhragmen { iterations: 10 }, solver: Solver::SeqPhragmen { iterations: 10 },
submission_strategy: SubmissionStrategy::IfLeading, submission_strategy: SubmissionStrategy::IfLeading,
delay: 12,
}), }),
} }
); );
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment