backing: move the min votes threshold to the runtime (#1200)

* move min backing votes const to runtime

also cache it per-session in the backing subsystem

Signed-off-by: alindima <alin@parity.io>

* add runtime migration

* introduce api versioning for min_backing votes

also enable it for rococo/versi for testing

* also add min_backing_votes runtime calls to statement-distribution

this dependency has been recently introduced by async backing

* remove explicit version runtime API call

this is not needed, as the RuntimeAPISubsystem already takes care
of versioning and will return NotSupported if the version is not
right.

* address review comments

- parametrise backing votes runtime API with session index
- remove RuntimeInfo usage in backing subsystem, as runtime API
caches the min backing votes by session index anyway.
- move the logic for adjusting the configured needed backing votes with the size of the backing group
to a primitives helper.
- move the legacy min backing votes value to a primitives helper.
- mark JoinMultiple error as fatal, since the Canceled (non-multiple) counterpart is also fatal.
- make backing subsystem handle fatal errors for new leaves update.
- add HostConfiguration consistency check for zeroed backing votes threshold
- add cumulus accompanying change

* fix cumulus test compilation

* fix tests

* more small fixes

* fix merge

* bump runtime api version for westend and rollback version for rococo

---------

Signed-off-by: alindima <alin@parity.io>
Co-authored-by: Javier Viola <javier@parity.io>
This commit is contained in:
Alin Dima
2023-08-31 14:01:36 +03:00
committed by GitHub
parent f1845f725d
commit d6af073aa5
37 changed files with 920 additions and 255 deletions
+1
View File
@@ -79,6 +79,7 @@ pub enum Error {
RuntimeApiUnavailable(#[source] oneshot::Canceled),
#[error("a channel was closed before receipt in try_join!")]
#[fatal]
JoinMultiple(#[source] oneshot::Canceled),
#[error("Obtaining erasure chunks failed")]
+33 -22
View File
@@ -80,8 +80,8 @@ use futures::{
use error::{Error, FatalResult};
use polkadot_node_primitives::{
minimum_votes, AvailableData, InvalidCandidate, PoV, SignedFullStatementWithPVD,
StatementWithPVD, ValidationResult,
AvailableData, InvalidCandidate, PoV, SignedFullStatementWithPVD, StatementWithPVD,
ValidationResult,
};
use polkadot_node_subsystem::{
messages::{
@@ -98,7 +98,9 @@ use polkadot_node_subsystem_util::{
backing_implicit_view::{FetchError as ImplicitViewFetchError, View as ImplicitView},
request_from_runtime, request_session_index_for_child, request_validator_groups,
request_validators,
runtime::{prospective_parachains_mode, ProspectiveParachainsMode},
runtime::{
self, prospective_parachains_mode, request_min_backing_votes, ProspectiveParachainsMode,
},
Validator,
};
use polkadot_primitives::{
@@ -219,6 +221,8 @@ struct PerRelayParentState {
awaiting_validation: HashSet<CandidateHash>,
/// Data needed for retrying in case of `ValidatedCandidateCommand::AttestNoPoV`.
fallbacks: HashMap<CandidateHash, AttestingData>,
/// The minimum backing votes threshold.
minimum_backing_votes: u32,
}
struct PerCandidateState {
@@ -400,8 +404,8 @@ impl TableContextTrait for TableContext {
self.groups.get(group).map_or(false, |g| g.iter().any(|a| a == authority))
}
fn requisite_votes(&self, group: &ParaId) -> usize {
self.groups.get(group).map_or(usize::MAX, |g| minimum_votes(g.len()))
fn get_group_size(&self, group: &ParaId) -> Option<usize> {
self.groups.get(group).map(|g| g.len())
}
}
@@ -965,28 +969,25 @@ async fn construct_per_relay_parent_state<Context>(
($x: expr) => {
match $x {
Ok(x) => x,
Err(e) => {
gum::warn!(
target: LOG_TARGET,
err = ?e,
"Failed to fetch runtime API data for job",
);
Err(err) => {
// Only bubble up fatal errors.
error::log_error(Err(Into::<runtime::Error>::into(err).into()))?;
// We can't do candidate validation work if we don't have the
// requisite runtime API data. But these errors should not take
// down the node.
return Ok(None);
}
return Ok(None)
},
}
}
};
}
let parent = relay_parent;
let (validators, groups, session_index, cores) = futures::try_join!(
let (session_index, validators, groups, cores) = futures::try_join!(
request_session_index_for_child(parent, ctx.sender()).await,
request_validators(parent, ctx.sender()).await,
request_validator_groups(parent, ctx.sender()).await,
request_session_index_for_child(parent, ctx.sender()).await,
request_from_runtime(parent, ctx.sender(), |tx| {
RuntimeApiRequest::AvailabilityCores(tx)
},)
@@ -994,10 +995,12 @@ async fn construct_per_relay_parent_state<Context>(
)
.map_err(Error::JoinMultiple)?;
let session_index = try_runtime_api!(session_index);
let validators: Vec<_> = try_runtime_api!(validators);
let (validator_groups, group_rotation_info) = try_runtime_api!(groups);
let session_index = try_runtime_api!(session_index);
let cores = try_runtime_api!(cores);
let minimum_backing_votes =
try_runtime_api!(request_min_backing_votes(parent, session_index, ctx.sender()).await);
let signing_context = SigningContext { parent_hash: parent, session_index };
let validator =
@@ -1061,6 +1064,7 @@ async fn construct_per_relay_parent_state<Context>(
issued_statements: HashSet::new(),
awaiting_validation: HashSet::new(),
fallbacks: HashMap::new(),
minimum_backing_votes,
}))
}
@@ -1563,10 +1567,13 @@ async fn post_import_statement_actions<Context>(
rp_state: &mut PerRelayParentState,
summary: Option<&TableSummary>,
) -> Result<(), Error> {
if let Some(attested) = summary
.as_ref()
.and_then(|s| rp_state.table.attested_candidate(&s.candidate, &rp_state.table_context))
{
if let Some(attested) = summary.as_ref().and_then(|s| {
rp_state.table.attested_candidate(
&s.candidate,
&rp_state.table_context,
rp_state.minimum_backing_votes,
)
}) {
let candidate_hash = attested.candidate.hash();
// `HashSet::insert` returns true if the thing wasn't in there already.
@@ -2009,7 +2016,11 @@ fn handle_get_backed_candidates_message(
};
rp_state
.table
.attested_candidate(&candidate_hash, &rp_state.table_context)
.attested_candidate(
&candidate_hash,
&rp_state.table_context,
rp_state.minimum_backing_votes,
)
.and_then(|attested| table_attested_to_backed(attested, &rp_state.table_context))
})
.collect();
+24 -11
View File
@@ -34,7 +34,7 @@ use polkadot_node_subsystem::{
use polkadot_node_subsystem_test_helpers as test_helpers;
use polkadot_primitives::{
CandidateDescriptor, GroupRotationInfo, HeadData, PersistedValidationData, PvfExecTimeoutKind,
ScheduledCore, SessionIndex,
ScheduledCore, SessionIndex, LEGACY_MIN_BACKING_VOTES,
};
use sp_application_crypto::AppCrypto;
use sp_keyring::Sr25519Keyring;
@@ -80,6 +80,7 @@ struct TestState {
head_data: HashMap<ParaId, HeadData>,
signing_context: SigningContext,
relay_parent: Hash,
minimum_backing_votes: u32,
}
impl TestState {
@@ -150,6 +151,7 @@ impl Default for TestState {
validation_data,
signing_context,
relay_parent,
minimum_backing_votes: LEGACY_MIN_BACKING_VOTES,
}
}
}
@@ -250,6 +252,16 @@ async fn test_startup(virtual_overseer: &mut VirtualOverseer, test_state: &TestS
}
);
// Check that subsystem job issues a request for the session index for child.
assert_matches!(
virtual_overseer.recv().await,
AllMessages::RuntimeApi(
RuntimeApiMessage::Request(parent, RuntimeApiRequest::SessionIndexForChild(tx))
) if parent == test_state.relay_parent => {
tx.send(Ok(test_state.signing_context.session_index)).unwrap();
}
);
// Check that subsystem job issues a request for a validator set.
assert_matches!(
virtual_overseer.recv().await,
@@ -270,16 +282,6 @@ async fn test_startup(virtual_overseer: &mut VirtualOverseer, test_state: &TestS
}
);
// Check that subsystem job issues a request for the session index for child.
assert_matches!(
virtual_overseer.recv().await,
AllMessages::RuntimeApi(
RuntimeApiMessage::Request(parent, RuntimeApiRequest::SessionIndexForChild(tx))
) if parent == test_state.relay_parent => {
tx.send(Ok(test_state.signing_context.session_index)).unwrap();
}
);
// Check that subsystem job issues a request for the availability cores.
assert_matches!(
virtual_overseer.recv().await,
@@ -289,6 +291,17 @@ async fn test_startup(virtual_overseer: &mut VirtualOverseer, test_state: &TestS
tx.send(Ok(test_state.availability_cores.clone())).unwrap();
}
);
// Check if subsystem job issues a request for the minimum backing votes.
assert_matches!(
virtual_overseer.recv().await,
AllMessages::RuntimeApi(RuntimeApiMessage::Request(
parent,
RuntimeApiRequest::MinimumBackingVotes(session_index, tx),
)) if parent == test_state.relay_parent && session_index == test_state.signing_context.session_index => {
tx.send(Ok(test_state.minimum_backing_votes)).unwrap();
}
);
}
// Test that a `CandidateBackingMessage::Second` issues validation work
@@ -138,13 +138,24 @@ async fn activate_leaf(
}
for (hash, number) in ancestry_iter.take(requested_len) {
// Check that subsystem job issues a request for a validator set.
let msg = match next_overseer_message.take() {
Some(msg) => msg,
None => virtual_overseer.recv().await,
};
// Check that subsystem job issues a request for the session index for child.
assert_matches!(
msg,
AllMessages::RuntimeApi(
RuntimeApiMessage::Request(parent, RuntimeApiRequest::SessionIndexForChild(tx))
) if parent == hash => {
tx.send(Ok(test_state.signing_context.session_index)).unwrap();
}
);
// Check that subsystem job issues a request for a validator set.
assert_matches!(
virtual_overseer.recv().await,
AllMessages::RuntimeApi(
RuntimeApiMessage::Request(parent, RuntimeApiRequest::Validators(tx))
) if parent == hash => {
@@ -164,16 +175,6 @@ async fn activate_leaf(
}
);
// Check that subsystem job issues a request for the session index for child.
assert_matches!(
virtual_overseer.recv().await,
AllMessages::RuntimeApi(
RuntimeApiMessage::Request(parent, RuntimeApiRequest::SessionIndexForChild(tx))
) if parent == hash => {
tx.send(Ok(test_state.signing_context.session_index)).unwrap();
}
);
// Check that subsystem job issues a request for the availability cores.
assert_matches!(
virtual_overseer.recv().await,
@@ -183,6 +184,17 @@ async fn activate_leaf(
tx.send(Ok(test_state.availability_cores.clone())).unwrap();
}
);
// Check if subsystem job issues a request for the minimum backing votes.
assert_matches!(
virtual_overseer.recv().await,
AllMessages::RuntimeApi(RuntimeApiMessage::Request(
parent,
RuntimeApiRequest::MinimumBackingVotes(session_index, tx),
)) if parent == hash && session_index == test_state.signing_context.session_index => {
tx.send(Ok(test_state.minimum_backing_votes)).unwrap();
}
);
}
}
@@ -65,6 +65,7 @@ pub(crate) struct RequestResultCache {
LruMap<Hash, Vec<(SessionIndex, CandidateHash, vstaging::slashing::PendingSlashes)>>,
key_ownership_proof:
LruMap<(Hash, ValidatorId), Option<vstaging::slashing::OpaqueKeyOwnershipProof>>,
minimum_backing_votes: LruMap<SessionIndex, u32>,
staging_para_backing_state: LruMap<(Hash, ParaId), Option<vstaging::BackingState>>,
staging_async_backing_params: LruMap<Hash, vstaging::AsyncBackingParams>,
@@ -97,6 +98,7 @@ impl Default for RequestResultCache {
disputes: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)),
unapplied_slashes: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)),
key_ownership_proof: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)),
minimum_backing_votes: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)),
staging_para_backing_state: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)),
staging_async_backing_params: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)),
@@ -434,6 +436,18 @@ impl RequestResultCache {
None
}
pub(crate) fn minimum_backing_votes(&mut self, session_index: SessionIndex) -> Option<u32> {
self.minimum_backing_votes.get(&session_index).copied()
}
pub(crate) fn cache_minimum_backing_votes(
&mut self,
session_index: SessionIndex,
minimum_backing_votes: u32,
) {
self.minimum_backing_votes.insert(session_index, minimum_backing_votes);
}
pub(crate) fn staging_para_backing_state(
&mut self,
key: (Hash, ParaId),
@@ -469,6 +483,7 @@ pub(crate) enum RequestResult {
// The structure of each variant is (relay_parent, [params,]*, result)
Authorities(Hash, Vec<AuthorityDiscoveryId>),
Validators(Hash, Vec<ValidatorId>),
MinimumBackingVotes(Hash, SessionIndex, u32),
ValidatorGroups(Hash, (Vec<Vec<ValidatorIndex>>, GroupRotationInfo)),
AvailabilityCores(Hash, Vec<CoreState>),
PersistedValidationData(Hash, ParaId, OccupiedCoreAssumption, Option<PersistedValidationData>),
+18
View File
@@ -101,6 +101,9 @@ where
self.requests_cache.cache_authorities(relay_parent, authorities),
Validators(relay_parent, validators) =>
self.requests_cache.cache_validators(relay_parent, validators),
MinimumBackingVotes(_, session_index, minimum_backing_votes) => self
.requests_cache
.cache_minimum_backing_votes(session_index, minimum_backing_votes),
ValidatorGroups(relay_parent, groups) =>
self.requests_cache.cache_validator_groups(relay_parent, groups),
AvailabilityCores(relay_parent, cores) =>
@@ -301,6 +304,15 @@ where
Request::StagingAsyncBackingParams(sender) =>
query!(staging_async_backing_params(), sender)
.map(|sender| Request::StagingAsyncBackingParams(sender)),
Request::MinimumBackingVotes(index, sender) => {
if let Some(value) = self.requests_cache.minimum_backing_votes(index) {
self.metrics.on_cached_request();
let _ = sender.send(Ok(value));
None
} else {
Some(Request::MinimumBackingVotes(index, sender))
}
},
}
}
@@ -551,6 +563,12 @@ where
ver = Request::SUBMIT_REPORT_DISPUTE_LOST_RUNTIME_REQUIREMENT,
sender
),
Request::MinimumBackingVotes(index, sender) => query!(
MinimumBackingVotes,
minimum_backing_votes(index),
ver = Request::MINIMUM_BACKING_VOTES_RUNTIME_REQUIREMENT,
sender
),
Request::StagingParaBackingState(para, sender) => {
query!(
@@ -264,6 +264,10 @@ impl RuntimeApiSubsystemClient for MockSubsystemClient {
) -> Result<Option<vstaging::BackingState>, ApiError> {
todo!("Not required for tests")
}
async fn minimum_backing_votes(&self, _: Hash, _: SessionIndex) -> Result<u32, ApiError> {
todo!("Not required for tests")
}
}
#[test]
@@ -16,6 +16,7 @@ sp-keystore = { path = "../../../../substrate/primitives/keystore" }
polkadot-node-subsystem = { path = "../../subsystem" }
polkadot-node-primitives = { path = "../../primitives" }
polkadot-node-subsystem-util = { path = "../../subsystem-util" }
polkadot-node-subsystem-types = { path = "../../subsystem-types" }
polkadot-node-network-protocol = { path = "../protocol" }
arrayvec = "0.7.4"
indexmap = "1.9.1"
@@ -39,4 +40,3 @@ sc-network = { path = "../../../../substrate/client/network" }
futures-timer = "3.0.2"
polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" }
rand_chacha = "0.3"
polkadot-node-subsystem-types = { path = "../../subsystem-types" }
@@ -1074,7 +1074,7 @@ mod tests {
fn dummy_groups(group_size: usize) -> Groups {
let groups = vec![(0..(group_size as u32)).map(ValidatorIndex).collect()].into();
Groups::new(groups)
Groups::new(groups, 2)
}
#[test]
@@ -16,8 +16,10 @@
//! A utility for tracking groups and their members within a session.
use polkadot_node_primitives::minimum_votes;
use polkadot_primitives::vstaging::{GroupIndex, IndexedVec, ValidatorIndex};
use polkadot_primitives::{
effective_minimum_backing_votes,
vstaging::{GroupIndex, IndexedVec, ValidatorIndex},
};
use std::collections::HashMap;
@@ -27,12 +29,16 @@ use std::collections::HashMap;
pub struct Groups {
groups: IndexedVec<GroupIndex, Vec<ValidatorIndex>>,
by_validator_index: HashMap<ValidatorIndex, GroupIndex>,
backing_threshold: u32,
}
impl Groups {
/// Create a new [`Groups`] tracker with the groups and discovery keys
/// from the session.
pub fn new(groups: IndexedVec<GroupIndex, Vec<ValidatorIndex>>) -> Self {
pub fn new(
groups: IndexedVec<GroupIndex, Vec<ValidatorIndex>>,
backing_threshold: u32,
) -> Self {
let mut by_validator_index = HashMap::new();
for (i, group) in groups.iter().enumerate() {
@@ -42,7 +48,7 @@ impl Groups {
}
}
Groups { groups, by_validator_index }
Groups { groups, by_validator_index, backing_threshold }
}
/// Access all the underlying groups.
@@ -60,7 +66,8 @@ impl Groups {
&self,
group_index: GroupIndex,
) -> Option<(usize, usize)> {
self.get(group_index).map(|g| (g.len(), minimum_votes(g.len())))
self.get(group_index)
.map(|g| (g.len(), effective_minimum_backing_votes(g.len(), self.backing_threshold)))
}
/// Get the group index for a validator by index.
@@ -41,8 +41,9 @@ use polkadot_node_subsystem::{
overseer, ActivatedLeaf,
};
use polkadot_node_subsystem_util::{
backing_implicit_view::View as ImplicitView, reputation::ReputationAggregator,
runtime::ProspectiveParachainsMode,
backing_implicit_view::View as ImplicitView,
reputation::ReputationAggregator,
runtime::{request_min_backing_votes, ProspectiveParachainsMode},
};
use polkadot_primitives::vstaging::{
AuthorityDiscoveryId, CandidateHash, CompactStatement, CoreIndex, CoreState, GroupIndex,
@@ -163,8 +164,8 @@ struct PerSessionState {
}
impl PerSessionState {
fn new(session_info: SessionInfo, keystore: &KeystorePtr) -> Self {
let groups = Groups::new(session_info.validator_groups.clone());
fn new(session_info: SessionInfo, keystore: &KeystorePtr, backing_threshold: u32) -> Self {
let groups = Groups::new(session_info.validator_groups.clone(), backing_threshold);
let mut authority_lookup = HashMap::new();
for (i, ad) in session_info.discovery_keys.iter().cloned().enumerate() {
authority_lookup.insert(ad, ValidatorIndex(i as _));
@@ -504,9 +505,13 @@ pub(crate) async fn handle_active_leaves_update<Context>(
Some(s) => s,
};
state
.per_session
.insert(session_index, PerSessionState::new(session_info, &state.keystore));
let minimum_backing_votes =
request_min_backing_votes(new_relay_parent, session_index, ctx.sender()).await?;
state.per_session.insert(
session_index,
PerSessionState::new(session_info, &state.keystore, minimum_backing_votes),
);
}
let per_session = state
@@ -2502,7 +2507,7 @@ pub(crate) async fn dispatch_requests<Context>(ctx: &mut Context, state: &mut St
Some(RequestProperties {
unwanted_mask,
backing_threshold: if require_backing {
Some(polkadot_node_primitives::minimum_votes(group.len()))
Some(per_session.groups.get_size_and_backing_threshold(group_index)?.1)
} else {
None
},
@@ -356,7 +356,7 @@ async fn activate_leaf(
virtual_overseer: &mut VirtualOverseer,
leaf: &TestLeaf,
test_state: &TestState,
expect_session_info_request: bool,
is_new_session: bool,
) {
let activated = ActivatedLeaf {
hash: leaf.hash,
@@ -371,14 +371,14 @@ async fn activate_leaf(
))))
.await;
handle_leaf_activation(virtual_overseer, leaf, test_state, expect_session_info_request).await;
handle_leaf_activation(virtual_overseer, leaf, test_state, is_new_session).await;
}
async fn handle_leaf_activation(
virtual_overseer: &mut VirtualOverseer,
leaf: &TestLeaf,
test_state: &TestState,
expect_session_info_request: bool,
is_new_session: bool,
) {
let TestLeaf { number, hash, parent_hash, para_data, session, availability_cores } = leaf;
@@ -447,7 +447,7 @@ async fn handle_leaf_activation(
}
);
if expect_session_info_request {
if is_new_session {
assert_matches!(
virtual_overseer.recv().await,
AllMessages::RuntimeApi(
@@ -455,6 +455,16 @@ async fn handle_leaf_activation(
tx.send(Ok(Some(test_state.session_info.clone()))).unwrap();
}
);
assert_matches!(
virtual_overseer.recv().await,
AllMessages::RuntimeApi(RuntimeApiMessage::Request(
parent,
RuntimeApiRequest::MinimumBackingVotes(session_index, tx),
)) if parent == *hash && session_index == *session => {
tx.send(Ok(2)).unwrap();
}
);
}
}
-7
View File
@@ -649,10 +649,3 @@ pub fn maybe_compress_pov(pov: PoV) -> PoV {
let pov = PoV { block_data: BlockData(raw) };
pov
}
/// How many votes we need to consider a candidate backed.
///
/// WARNING: This has to be kept in sync with the runtime check in the inclusion module.
pub fn minimum_votes(n_validators: usize) -> usize {
std::cmp::min(2, n_validators)
}
@@ -691,6 +691,8 @@ pub enum RuntimeApiRequest {
slashing::OpaqueKeyOwnershipProof,
RuntimeApiSender<Option<()>>,
),
/// Get the minimum required backing votes.
MinimumBackingVotes(SessionIndex, RuntimeApiSender<u32>),
/// Get the backing state of the given para.
/// This is a staging API that will not be available on production runtimes.
@@ -719,6 +721,9 @@ impl RuntimeApiRequest {
/// `SubmitReportDisputeLost`
pub const SUBMIT_REPORT_DISPUTE_LOST_RUNTIME_REQUIREMENT: u32 = 5;
/// `MinimumBackingVotes`
pub const MINIMUM_BACKING_VOTES_RUNTIME_REQUIREMENT: u32 = 6;
/// Minimum version for backing state, required for async backing.
///
/// 99 for now, should be adjusted to VSTAGING/actual runtime version once released.
@@ -232,6 +232,14 @@ pub trait RuntimeApiSubsystemClient {
session_index: SessionIndex,
) -> Result<Option<ExecutorParams>, ApiError>;
// === STAGING v6 ===
/// Get the minimum number of backing votes.
async fn minimum_backing_votes(
&self,
at: Hash,
session_index: SessionIndex,
) -> Result<u32, ApiError>;
// === Asynchronous backing API ===
/// Returns candidate's acceptance limitations for asynchronous backing for a relay parent.
@@ -473,6 +481,14 @@ where
runtime_api.submit_report_dispute_lost(at, dispute_proof, key_ownership_proof)
}
async fn minimum_backing_votes(
&self,
at: Hash,
_session_index: SessionIndex,
) -> Result<u32, ApiError> {
self.client.runtime_api().minimum_backing_votes(at)
}
async fn staging_para_backing_state(
&self,
at: Hash,
@@ -33,7 +33,7 @@ pub enum Error {
/// Some request to the runtime failed.
/// For example if we prune a block we're requesting info about.
#[error("Runtime API error {0}")]
RuntimeRequest(RuntimeApiError),
RuntimeRequest(#[from] RuntimeApiError),
/// We tried fetching a session info which was not available.
#[error("There was no session with the given index {0}")]
@@ -43,7 +43,7 @@ pub enum Error {
pub type Result<T> = std::result::Result<T, Error>;
/// Receive a response from a runtime request and convert errors.
pub(crate) async fn recv_runtime<V>(
pub async fn recv_runtime<V>(
r: oneshot::Receiver<std::result::Result<V, RuntimeApiError>>,
) -> Result<V> {
let result = r
@@ -24,27 +24,29 @@ use sp_core::crypto::ByteArray;
use sp_keystore::{Keystore, KeystorePtr};
use polkadot_node_subsystem::{
errors::RuntimeApiError, messages::RuntimeApiMessage, overseer, SubsystemSender,
errors::RuntimeApiError,
messages::{RuntimeApiMessage, RuntimeApiRequest},
overseer, SubsystemSender,
};
use polkadot_primitives::{
vstaging, CandidateEvent, CandidateHash, CoreState, EncodeAs, GroupIndex, GroupRotationInfo,
Hash, IndexedVec, OccupiedCore, ScrapedOnChainVotes, SessionIndex, SessionInfo, Signed,
SigningContext, UncheckedSigned, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex,
ValidatorIndex, LEGACY_MIN_BACKING_VOTES,
};
use crate::{
request_availability_cores, request_candidate_events, request_key_ownership_proof,
request_on_chain_votes, request_session_index_for_child, request_session_info,
request_staging_async_backing_params, request_submit_report_dispute_lost,
request_availability_cores, request_candidate_events, request_from_runtime,
request_key_ownership_proof, request_on_chain_votes, request_session_index_for_child,
request_session_info, request_staging_async_backing_params, request_submit_report_dispute_lost,
request_unapplied_slashes, request_validation_code_by_hash, request_validator_groups,
};
/// Errors that can happen on runtime fetches.
mod error;
use error::{recv_runtime, Result};
pub use error::{Error, FatalError, JfyiError};
use error::Result;
pub use error::{recv_runtime, Error, FatalError, JfyiError};
const LOG_TARGET: &'static str = "parachain::runtime-info";
@@ -451,3 +453,32 @@ where
})
}
}
/// Request the min backing votes value.
/// Prior to runtime API version 6, just return a hardcoded constant.
pub async fn request_min_backing_votes(
parent: Hash,
session_index: SessionIndex,
sender: &mut impl overseer::SubsystemSender<RuntimeApiMessage>,
) -> Result<u32> {
let min_backing_votes_res = recv_runtime(
request_from_runtime(parent, sender, |tx| {
RuntimeApiRequest::MinimumBackingVotes(session_index, tx)
})
.await,
)
.await;
if let Err(Error::RuntimeRequest(RuntimeApiError::NotSupported { .. })) = min_backing_votes_res
{
gum::trace!(
target: LOG_TARGET,
?parent,
"Querying the backing threshold from the runtime is not supported by the current Runtime API",
);
Ok(LEGACY_MIN_BACKING_VOTES)
} else {
min_backing_votes_res
}
}