Run cargo fmt on the whole code base (#9394)

* Run cargo fmt on the whole code base

* Second run

* Add CI check

* Fix compilation

* More unnecessary braces

* Handle weights

* Use --all

* Use correct attributes...

* Fix UI tests

* AHHHHHHHHH

* 🤦

* Docs

* Fix compilation

* 🤷

* Please stop

* 🤦 x 2

* More

* make rustfmt.toml consistent with polkadot

Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
Bastian Köcher
2021-07-21 16:32:32 +02:00
committed by GitHub
parent d451c38c1c
commit 7b56ab15b4
1010 changed files with 53339 additions and 51208 deletions
@@ -18,36 +18,37 @@
//! Module implementing the logic for verifying and importing AuRa blocks.
use crate::{AuthorityId, find_pre_digest, slot_author, aura_err, Error, authorities};
use std::{
sync::Arc, marker::PhantomData, hash::Hash, fmt::Debug,
};
use crate::{aura_err, authorities, find_pre_digest, slot_author, AuthorityId, Error};
use codec::{Codec, Decode, Encode};
use log::{debug, info, trace};
use prometheus_endpoint::Registry;
use codec::{Encode, Decode, Codec};
use sp_consensus::{
BlockImport, CanAuthorWith, ForkChoiceStrategy, BlockImportParams,
BlockOrigin, Error as ConsensusError,
import_queue::{
Verifier, BasicQueue, DefaultImportQueue, BoxJustificationImport,
},
};
use sc_client_api::{BlockOf, UsageProvider, backend::AuxStore};
use sp_blockchain::{well_known_cache_keys::{self, Id as CacheKeyId}, ProvideCache, HeaderBackend};
use sc_client_api::{backend::AuxStore, BlockOf, UsageProvider};
use sc_consensus_slots::{check_equivocation, CheckedHeader, InherentDataProviderExt};
use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_TRACE};
use sp_api::{ApiExt, ProvideRuntimeApi};
use sp_block_builder::BlockBuilder as BlockBuilderApi;
use sp_runtime::{generic::{BlockId, OpaqueDigestItemId}, Justifications};
use sp_runtime::traits::{Block as BlockT, Header, DigestItemFor};
use sp_api::ProvideRuntimeApi;
use sp_blockchain::{
well_known_cache_keys::{self, Id as CacheKeyId},
HeaderBackend, ProvideCache,
};
use sp_consensus::{
import_queue::{BasicQueue, BoxJustificationImport, DefaultImportQueue, Verifier},
BlockImport, BlockImportParams, BlockOrigin, CanAuthorWith, Error as ConsensusError,
ForkChoiceStrategy,
};
use sp_consensus_aura::{
digests::CompatibleDigestItem, inherents::AuraInherentData, AuraApi, ConsensusLog,
AURA_ENGINE_ID,
};
use sp_consensus_slots::Slot;
use sp_core::crypto::Pair;
use sp_inherents::{CreateInherentDataProviders, InherentDataProvider as _};
use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_TRACE, CONSENSUS_DEBUG};
use sc_consensus_slots::{CheckedHeader, check_equivocation, InherentDataProviderExt};
use sp_consensus_slots::Slot;
use sp_api::ApiExt;
use sp_consensus_aura::{
digests::CompatibleDigestItem, AuraApi, inherents::AuraInherentData,
ConsensusLog, AURA_ENGINE_ID,
use sp_runtime::{
generic::{BlockId, OpaqueDigestItemId},
traits::{Block as BlockT, DigestItemFor, Header},
Justifications,
};
use std::{fmt::Debug, hash::Hash, marker::PhantomData, sync::Arc};
/// check a header has been signed by the right key. If the slot is too far in the future, an error
/// will be returned. If it's successful, returns the pre-header and the digest item
@@ -61,7 +62,8 @@ fn check_header<C, B: BlockT, P: Pair>(
hash: B::Hash,
authorities: &[AuthorityId<P>],
check_for_equivocation: CheckForEquivocation,
) -> Result<CheckedHeader<B::Header, (Slot, DigestItemFor<B>)>, Error<B>> where
) -> Result<CheckedHeader<B::Header, (Slot, DigestItemFor<B>)>, Error<B>>
where
DigestItemFor<B>: CompatibleDigestItem<P::Signature>,
P::Signature: Codec,
C: sc_client_api::backend::AuxStore,
@@ -69,9 +71,7 @@ fn check_header<C, B: BlockT, P: Pair>(
{
let seal = header.digest_mut().pop().ok_or_else(|| Error::HeaderUnsealed(hash))?;
let sig = seal.as_aura_seal().ok_or_else(|| {
aura_err(Error::HeaderBadSeal(hash))
})?;
let sig = seal.as_aura_seal().ok_or_else(|| aura_err(Error::HeaderBadSeal(hash)))?;
let slot = find_pre_digest::<B, P::Signature>(&header)?;
@@ -81,20 +81,17 @@ fn check_header<C, B: BlockT, P: Pair>(
} else {
// check the signature is valid under the expected authority and
// chain state.
let expected_author = slot_author::<P>(slot, &authorities)
.ok_or_else(|| Error::SlotAuthorNotFound)?;
let expected_author =
slot_author::<P>(slot, &authorities).ok_or_else(|| Error::SlotAuthorNotFound)?;
let pre_hash = header.hash();
if P::verify(&sig, pre_hash.as_ref(), expected_author) {
if check_for_equivocation.check_for_equivocation() {
if let Some(equivocation_proof) = check_equivocation(
client,
slot_now,
slot,
&header,
expected_author,
).map_err(Error::Client)? {
if let Some(equivocation_proof) =
check_equivocation(client, slot_now, slot, &header, expected_author)
.map_err(Error::Client)?
{
info!(
target: "aura",
"Slot author is equivocating at slot {} with headers {:?} and {:?}",
@@ -141,7 +138,8 @@ impl<C, P, CAW, CIDP> AuraVerifier<C, P, CAW, CIDP> {
}
}
impl<C, P, CAW, CIDP> AuraVerifier<C, P, CAW, CIDP> where
impl<C, P, CAW, CIDP> AuraVerifier<C, P, CAW, CIDP>
where
P: Send + Sync + 'static,
CAW: Send + Sync + 'static,
CIDP: Send,
@@ -152,8 +150,10 @@ impl<C, P, CAW, CIDP> AuraVerifier<C, P, CAW, CIDP> where
block_id: BlockId<B>,
inherent_data: sp_inherents::InherentData,
create_inherent_data_providers: CIDP::InherentDataProviders,
) -> Result<(), Error<B>> where
C: ProvideRuntimeApi<B>, C::Api: BlockBuilderApi<B>,
) -> Result<(), Error<B>>
where
C: ProvideRuntimeApi<B>,
C::Api: BlockBuilderApi<B>,
CAW: CanAuthorWith<B>,
CIDP: CreateInherentDataProviders<B, ()>,
{
@@ -167,11 +167,11 @@ impl<C, P, CAW, CIDP> AuraVerifier<C, P, CAW, CIDP> where
return Ok(())
}
let inherent_res = self.client.runtime_api().check_inherents(
&block_id,
block,
inherent_data,
).map_err(|e| Error::Client(e.into()))?;
let inherent_res = self
.client
.runtime_api()
.check_inherents(&block_id, block, inherent_data)
.map_err(|e| Error::Client(e.into()))?;
if !inherent_res.ok() {
for (i, e) in inherent_res.into_errors() {
@@ -187,13 +187,14 @@ impl<C, P, CAW, CIDP> AuraVerifier<C, P, CAW, CIDP> where
}
#[async_trait::async_trait]
impl<B: BlockT, C, P, CAW, CIDP> Verifier<B> for AuraVerifier<C, P, CAW, CIDP> where
C: ProvideRuntimeApi<B> +
Send +
Sync +
sc_client_api::backend::AuxStore +
ProvideCache<B> +
BlockOf,
impl<B: BlockT, C, P, CAW, CIDP> Verifier<B> for AuraVerifier<C, P, CAW, CIDP>
where
C: ProvideRuntimeApi<B>
+ Send
+ Sync
+ sc_client_api::backend::AuxStore
+ ProvideCache<B>
+ BlockOf,
C::Api: BlockBuilderApi<B> + AuraApi<B, AuthorityId<P>> + ApiExt<B>,
DigestItemFor<B>: CompatibleDigestItem<P::Signature>,
P: Pair + Send + Sync + 'static,
@@ -215,15 +216,14 @@ impl<B: BlockT, C, P, CAW, CIDP> Verifier<B> for AuraVerifier<C, P, CAW, CIDP> w
let authorities = authorities(self.client.as_ref(), &BlockId::Hash(parent_hash))
.map_err(|e| format!("Could not fetch authorities at {:?}: {:?}", parent_hash, e))?;
let create_inherent_data_providers = self.create_inherent_data_providers
.create_inherent_data_providers(
parent_hash,
(),
)
let create_inherent_data_providers = self
.create_inherent_data_providers
.create_inherent_data_providers(parent_hash, ())
.await
.map_err(|e| Error::<B>::Client(sp_blockchain::Error::Application(e)))?;
let mut inherent_data = create_inherent_data_providers.create_inherent_data()
let mut inherent_data = create_inherent_data_providers
.create_inherent_data()
.map_err(Error::<B>::Inherent)?;
let slot_now = create_inherent_data_providers.slot();
@@ -238,7 +238,8 @@ impl<B: BlockT, C, P, CAW, CIDP> Verifier<B> for AuraVerifier<C, P, CAW, CIDP> w
hash,
&authorities[..],
self.check_for_equivocation,
).map_err(|e| e.to_string())?;
)
.map_err(|e| e.to_string())?;
match checked_header {
CheckedHeader::Checked(pre_header, (slot, seal)) => {
// if the body is passed through, we need to use the runtime
@@ -250,7 +251,8 @@ impl<B: BlockT, C, P, CAW, CIDP> Verifier<B> for AuraVerifier<C, P, CAW, CIDP> w
inherent_data.aura_replace_inherent_data(slot);
// skip the inherents verification if the runtime API is old.
if self.client
if self
.client
.runtime_api()
.has_api_with::<dyn BlockBuilderApi<B>, _>(
&BlockId::Hash(parent_hash),
@@ -263,7 +265,9 @@ impl<B: BlockT, C, P, CAW, CIDP> Verifier<B> for AuraVerifier<C, P, CAW, CIDP> w
BlockId::Hash(parent_hash),
inherent_data,
create_inherent_data_providers,
).await.map_err(|e| e.to_string())?;
)
.await
.map_err(|e| e.to_string())?;
}
let (_, inner_body) = block.deconstruct();
@@ -279,16 +283,18 @@ impl<B: BlockT, C, P, CAW, CIDP> Verifier<B> for AuraVerifier<C, P, CAW, CIDP> w
);
// Look for an authorities-change log.
let maybe_keys = pre_header.digest()
let maybe_keys = pre_header
.digest()
.logs()
.iter()
.filter_map(|l| l.try_to::<ConsensusLog<AuthorityId<P>>>(
OpaqueDigestItemId::Consensus(&AURA_ENGINE_ID)
))
.filter_map(|l| {
l.try_to::<ConsensusLog<AuthorityId<P>>>(OpaqueDigestItemId::Consensus(
&AURA_ENGINE_ID,
))
})
.find_map(|l| match l {
ConsensusLog::AuthoritiesChange(a) => Some(
vec![(well_known_cache_keys::AUTHORITIES, a.encode())]
),
ConsensusLog::AuthoritiesChange(a) =>
Some(vec![(well_known_cache_keys::AUTHORITIES, a.encode())]),
_ => None,
});
@@ -300,7 +306,7 @@ impl<B: BlockT, C, P, CAW, CIDP> Verifier<B> for AuraVerifier<C, P, CAW, CIDP> w
import_block.post_hash = Some(hash);
Ok((import_block, maybe_keys))
}
},
CheckedHeader::Deferred(a, b) => {
debug!(target: "aura", "Checking {:?} failed; {:?}, {:?}.", hash, a, b);
telemetry!(
@@ -312,7 +318,7 @@ impl<B: BlockT, C, P, CAW, CIDP> Verifier<B> for AuraVerifier<C, P, CAW, CIDP> w
"b" => ?b,
);
Err(format!("Header {:?} rejected: too far in the future", hash))
}
},
}
}
}
@@ -375,8 +381,9 @@ pub fn import_queue<'a, P, Block, I, C, S, CAW, CIDP>(
can_author_with,
check_for_equivocation,
telemetry,
}: ImportQueueParams<'a, Block, I, C, S, CAW, CIDP>
) -> Result<DefaultImportQueue<Block, C>, sp_consensus::Error> where
}: ImportQueueParams<'a, Block, I, C, S, CAW, CIDP>,
) -> Result<DefaultImportQueue<Block, C>, sp_consensus::Error>
where
Block: BlockT,
C::Api: BlockBuilderApi<Block> + AuraApi<Block, AuthorityId<P>> + ApiExt<Block>,
C: 'static
@@ -388,7 +395,7 @@ pub fn import_queue<'a, P, Block, I, C, S, CAW, CIDP>(
+ AuxStore
+ UsageProvider<Block>
+ HeaderBackend<Block>,
I: BlockImport<Block, Error=ConsensusError, Transaction = sp_api::TransactionFor<C, Block>>
I: BlockImport<Block, Error = ConsensusError, Transaction = sp_api::TransactionFor<C, Block>>
+ Send
+ Sync
+ 'static,
@@ -401,23 +408,15 @@ pub fn import_queue<'a, P, Block, I, C, S, CAW, CIDP>(
CIDP: CreateInherentDataProviders<Block, ()> + Sync + Send + 'static,
CIDP::InherentDataProviders: InherentDataProviderExt + Send + Sync,
{
let verifier = build_verifier::<P, _, _, _>(
BuildVerifierParams {
client,
create_inherent_data_providers,
can_author_with,
check_for_equivocation,
telemetry,
},
);
let verifier = build_verifier::<P, _, _, _>(BuildVerifierParams {
client,
create_inherent_data_providers,
can_author_with,
check_for_equivocation,
telemetry,
});
Ok(BasicQueue::new(
verifier,
Box::new(block_import),
justification_import,
spawner,
registry,
))
Ok(BasicQueue::new(verifier, Box::new(block_import), justification_import, spawner, registry))
}
/// Parameters of [`build_verifier`].
@@ -442,7 +441,7 @@ pub fn build_verifier<P, C, CIDP, CAW>(
can_author_with,
check_for_equivocation,
telemetry,
}: BuildVerifierParams<C, CIDP, CAW>
}: BuildVerifierParams<C, CIDP, CAW>,
) -> AuraVerifier<C, P, CAW, CIDP> {
AuraVerifier::<_, P, _, _>::new(
client,
+192 -169
View File
@@ -31,50 +31,53 @@
//! NOTE: Aura itself is designed to be generic over the crypto used.
#![forbid(missing_docs, unsafe_code)]
use std::{
sync::Arc, marker::PhantomData, hash::Hash, fmt::Debug, pin::Pin,
convert::{TryFrom, TryInto},
fmt::Debug,
hash::Hash,
marker::PhantomData,
pin::Pin,
sync::Arc,
};
use futures::prelude::*;
use log::{debug, trace};
use codec::{Encode, Decode, Codec};
use codec::{Codec, Decode, Encode};
use sp_consensus::{
BlockImport, Environment, Proposer, CanAuthorWith, ForkChoiceStrategy, BlockImportParams,
BlockOrigin, Error as ConsensusError, SelectChain, StateAction,
};
use sc_client_api::{backend::AuxStore, BlockOf, UsageProvider};
use sp_blockchain::{Result as CResult, ProvideCache, HeaderBackend};
use sp_core::crypto::Public;
use sp_application_crypto::{AppKey, AppPublic};
use sp_runtime::{generic::BlockId, traits::NumberFor};
use sp_runtime::traits::{Block as BlockT, Header, DigestItemFor, Zero, Member};
use sp_api::ProvideRuntimeApi;
use sp_core::crypto::Pair;
use sp_keystore::{SyncCryptoStorePtr, SyncCryptoStore};
use sp_inherents::CreateInherentDataProviders;
use sc_telemetry::TelemetryHandle;
use sc_consensus_slots::{
SlotInfo, BackoffAuthoringBlocksStrategy, InherentDataProviderExt, StorageChanges,
BackoffAuthoringBlocksStrategy, InherentDataProviderExt, SlotInfo, StorageChanges,
};
use sc_telemetry::TelemetryHandle;
use sp_api::ProvideRuntimeApi;
use sp_application_crypto::{AppKey, AppPublic};
use sp_blockchain::{HeaderBackend, ProvideCache, Result as CResult};
use sp_consensus::{
BlockImport, BlockImportParams, BlockOrigin, CanAuthorWith, Environment,
Error as ConsensusError, ForkChoiceStrategy, Proposer, SelectChain, StateAction,
};
use sp_consensus_slots::Slot;
use sp_core::crypto::{Pair, Public};
use sp_inherents::CreateInherentDataProviders;
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr};
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, DigestItemFor, Header, Member, NumberFor, Zero},
};
mod import_queue;
pub use sp_consensus_aura::{
ConsensusLog, AuraApi, AURA_ENGINE_ID, digests::CompatibleDigestItem,
inherents::{
InherentType as AuraInherent,
INHERENT_IDENTIFIER, InherentDataProvider,
},
};
pub use sp_consensus::SyncOracle;
pub use import_queue::{
ImportQueueParams, import_queue, CheckForEquivocation,
build_verifier, BuildVerifierParams, AuraVerifier,
build_verifier, import_queue, AuraVerifier, BuildVerifierParams, CheckForEquivocation,
ImportQueueParams,
};
pub use sc_consensus_slots::SlotProportion;
pub use sp_consensus::SyncOracle;
pub use sp_consensus_aura::{
digests::CompatibleDigestItem,
inherents::{InherentDataProvider, InherentType as AuraInherent, INHERENT_IDENTIFIER},
AuraApi, ConsensusLog, AURA_ENGINE_ID,
};
type AuthorityId<P> = <P as Pair>::Public;
@@ -82,7 +85,8 @@ type AuthorityId<P> = <P as Pair>::Public;
pub type SlotDuration = sc_consensus_slots::SlotDuration<sp_consensus_aura::SlotDuration>;
/// Get type of `SlotDuration` for Aura.
pub fn slot_duration<A, B, C>(client: &C) -> CResult<SlotDuration> where
pub fn slot_duration<A, B, C>(client: &C) -> CResult<SlotDuration>
where
A: Codec,
B: BlockT,
C: AuxStore + ProvideRuntimeApi<B> + UsageProvider<B>,
@@ -93,7 +97,9 @@ pub fn slot_duration<A, B, C>(client: &C) -> CResult<SlotDuration> where
/// Get slot author for given block along with authorities.
fn slot_author<P: Pair>(slot: Slot, authorities: &[AuthorityId<P>]) -> Option<&AuthorityId<P>> {
if authorities.is_empty() { return None }
if authorities.is_empty() {
return None
}
let idx = *slot % (authorities.len() as u64);
assert!(
@@ -101,9 +107,10 @@ fn slot_author<P: Pair>(slot: Slot, authorities: &[AuthorityId<P>]) -> Option<&A
"It is impossible to have a vector with length beyond the address space; qed",
);
let current_author = authorities.get(idx as usize)
.expect("authorities not empty; index constrained to list length;\
this is a valid index; qed");
let current_author = authorities.get(idx as usize).expect(
"authorities not empty; index constrained to list length;\
this is a valid index; qed",
);
Some(current_author)
}
@@ -325,9 +332,8 @@ where
type BlockImport = I;
type SyncOracle = SO;
type JustificationSyncLink = L;
type CreateProposer = Pin<Box<
dyn Future<Output = Result<E::Proposer, sp_consensus::Error>> + Send + 'static
>>;
type CreateProposer =
Pin<Box<dyn Future<Output = Result<E::Proposer, sp_consensus::Error>> + Send + 'static>>;
type Proposer = E::Proposer;
type Claim = P::Public;
type EpochData = Vec<AuthorityId<P>>;
@@ -376,22 +382,25 @@ where
slot: Slot,
_claim: &Self::Claim,
) -> Vec<sp_runtime::DigestItem<B::Hash>> {
vec![
<DigestItemFor<B> as CompatibleDigestItem<P::Signature>>::aura_pre_digest(slot),
]
vec![<DigestItemFor<B> as CompatibleDigestItem<P::Signature>>::aura_pre_digest(slot)]
}
fn block_import_params(&self) -> Box<dyn Fn(
B::Header,
&B::Hash,
Vec<B::Extrinsic>,
StorageChanges<sp_api::TransactionFor<C, B>, B>,
Self::Claim,
Self::EpochData,
) -> Result<
sp_consensus::BlockImportParams<B, sp_api::TransactionFor<C, B>>,
sp_consensus::Error> + Send + 'static>
{
fn block_import_params(
&self,
) -> Box<
dyn Fn(
B::Header,
&B::Hash,
Vec<B::Extrinsic>,
StorageChanges<sp_api::TransactionFor<C, B>, B>,
Self::Claim,
Self::EpochData,
) -> Result<
sp_consensus::BlockImportParams<B, sp_api::TransactionFor<C, B>>,
sp_consensus::Error,
> + Send
+ 'static,
> {
let keystore = self.keystore.clone();
Box::new(move |header, header_hash, body, storage_changes, public, _epoch| {
// sign the pre-sealed hash of the block and then
@@ -402,28 +411,28 @@ where
&*keystore,
<AuthorityId<P> as AppKey>::ID,
&public_type_pair,
header_hash.as_ref()
).map_err(|e| sp_consensus::Error::CannotSign(
public.clone(), e.to_string(),
))?
.ok_or_else(|| sp_consensus::Error::CannotSign(
public.clone(), "Could not find key in keystore.".into(),
))?;
let signature = signature.clone().try_into()
.map_err(|_| sp_consensus::Error::InvalidSignature(
signature, public
))?;
header_hash.as_ref(),
)
.map_err(|e| sp_consensus::Error::CannotSign(public.clone(), e.to_string()))?
.ok_or_else(|| {
sp_consensus::Error::CannotSign(
public.clone(),
"Could not find key in keystore.".into(),
)
})?;
let signature = signature
.clone()
.try_into()
.map_err(|_| sp_consensus::Error::InvalidSignature(signature, public))?;
let signature_digest_item = <
DigestItemFor<B> as CompatibleDigestItem<P::Signature>
>::aura_seal(signature);
let signature_digest_item =
<DigestItemFor<B> as CompatibleDigestItem<P::Signature>>::aura_seal(signature);
let mut import_block = BlockImportParams::new(BlockOrigin::Own, header);
import_block.post_digests.push(signature_digest_item);
import_block.body = Some(body);
import_block.state_action = StateAction::ApplyChanges(
sp_consensus::StorageChanges::Changes(storage_changes)
);
import_block.state_action =
StateAction::ApplyChanges(sp_consensus::StorageChanges::Changes(storage_changes));
import_block.fork_choice = Some(ForkChoiceStrategy::LongestChain);
Ok(import_block)
@@ -443,7 +452,7 @@ where
self.client.info().finalized_number,
slot,
self.logging_target(),
);
)
}
}
false
@@ -458,9 +467,11 @@ where
}
fn proposer(&mut self, block: &B::Header) -> Self::CreateProposer {
Box::pin(self.env.init(block).map_err(|e| {
sp_consensus::Error::ClientImport(format!("{:?}", e)).into()
}))
Box::pin(
self.env
.init(block)
.map_err(|e| sp_consensus::Error::ClientImport(format!("{:?}", e)).into()),
)
}
fn telemetry(&self) -> Option<TelemetryHandle> {
@@ -515,7 +526,7 @@ impl<B: BlockT> std::convert::From<Error<B>> for String {
fn find_pre_digest<B: BlockT, Signature: Codec>(header: &B::Header) -> Result<Slot, Error<B>> {
if header.number().is_zero() {
return Ok(0.into());
return Ok(0.into())
}
let mut pre_digest: Option<Slot> = None;
@@ -530,13 +541,15 @@ fn find_pre_digest<B: BlockT, Signature: Codec>(header: &B::Header) -> Result<Sl
pre_digest.ok_or_else(|| aura_err(Error::NoDigestFound))
}
fn authorities<A, B, C>(client: &C, at: &BlockId<B>) -> Result<Vec<A>, ConsensusError> where
fn authorities<A, B, C>(client: &C, at: &BlockId<B>) -> Result<Vec<A>, ConsensusError>
where
A: Codec + Debug,
B: BlockT,
C: ProvideRuntimeApi<B> + BlockOf + ProvideCache<B>,
C::Api: AuraApi<B, A>,
{
client.runtime_api()
client
.runtime_api()
.authorities(at)
.ok()
.ok_or_else(|| sp_consensus::Error::InvalidAuthoritiesSet.into())
@@ -545,26 +558,31 @@ fn authorities<A, B, C>(client: &C, at: &BlockId<B>) -> Result<Vec<A>, Consensus
#[cfg(test)]
mod tests {
use super::*;
use sp_consensus::{
NoNetwork as DummyOracle, Proposal, AlwaysCanAuthor, DisableProofRecording,
import_queue::BoxJustificationImport, SlotData,
};
use sc_network_test::{Block as TestBlock, *};
use sp_runtime::traits::{Block as BlockT, DigestFor};
use sc_network::config::ProtocolConfig;
use parking_lot::Mutex;
use sp_keyring::sr25519::Keyring;
use sc_client_api::BlockchainEvents;
use sp_consensus_aura::sr25519::AuthorityPair;
use sc_consensus_slots::{SimpleSlotWorker, BackoffAuthoringOnFinalizedHeadLagging};
use std::{task::Poll, time::{Instant, Duration}};
use sc_block_builder::BlockBuilderProvider;
use sp_runtime::traits::Header as _;
use substrate_test_runtime_client::{TestClient, runtime::{Header, H256}};
use sc_client_api::BlockchainEvents;
use sc_consensus_slots::{BackoffAuthoringOnFinalizedHeadLagging, SimpleSlotWorker};
use sc_keystore::LocalKeystore;
use sc_network::config::ProtocolConfig;
use sc_network_test::{Block as TestBlock, *};
use sp_application_crypto::key_types::AURA;
use sp_consensus::{
import_queue::BoxJustificationImport, AlwaysCanAuthor, DisableProofRecording,
NoNetwork as DummyOracle, Proposal, SlotData,
};
use sp_consensus_aura::sr25519::AuthorityPair;
use sp_inherents::InherentData;
use sp_keyring::sr25519::Keyring;
use sp_runtime::traits::{Block as BlockT, DigestFor, Header as _};
use sp_timestamp::InherentDataProvider as TimestampInherentDataProvider;
use std::{
task::Poll,
time::{Duration, Instant},
};
use substrate_test_runtime_client::{
runtime::{Header, H256},
TestClient,
};
type Error = sp_blockchain::Error;
@@ -576,19 +594,15 @@ mod tests {
type CreateProposer = futures::future::Ready<Result<DummyProposer, Error>>;
type Error = Error;
fn init(&mut self, parent_header: &<TestBlock as BlockT>::Header)
-> Self::CreateProposer
{
fn init(&mut self, parent_header: &<TestBlock as BlockT>::Header) -> Self::CreateProposer {
futures::future::ready(Ok(DummyProposer(parent_header.number + 1, self.0.clone())))
}
}
impl Proposer<TestBlock> for DummyProposer {
type Error = Error;
type Transaction = sc_client_api::TransactionFor<
substrate_test_runtime_client::Backend,
TestBlock
>;
type Transaction =
sc_client_api::TransactionFor<substrate_test_runtime_client::Backend, TestBlock>;
type Proposal = future::Ready<Result<Proposal<TestBlock, Self::Transaction, ()>, Error>>;
type ProofRecording = DisableProofRecording;
type Proof = ();
@@ -616,11 +630,13 @@ mod tests {
PeersFullClient,
AuthorityPair,
AlwaysCanAuthor,
Box<dyn CreateInherentDataProviders<
TestBlock,
(),
InherentDataProviders = (TimestampInherentDataProvider, InherentDataProvider)
>>
Box<
dyn CreateInherentDataProviders<
TestBlock,
(),
InherentDataProviders = (TimestampInherentDataProvider, InherentDataProvider),
>,
>,
>;
type AuraPeer = Peer<(), PeersClient>;
@@ -635,14 +651,15 @@ mod tests {
/// Create new test network with peers and given config.
fn from_config(_config: &ProtocolConfig) -> Self {
AuraTestNet {
peers: Vec::new(),
}
AuraTestNet { peers: Vec::new() }
}
fn make_verifier(&self, client: PeersClient, _cfg: &ProtocolConfig, _peer_data: &())
-> Self::Verifier
{
fn make_verifier(
&self,
client: PeersClient,
_cfg: &ProtocolConfig,
_peer_data: &(),
) -> Self::Verifier {
match client {
PeersClient::Full(client, _) => {
let slot_duration = slot_duration(&*client).expect("slot duration available");
@@ -668,7 +685,10 @@ mod tests {
}
}
fn make_block_import(&self, client: PeersClient) -> (
fn make_block_import(
&self,
client: PeersClient,
) -> (
BlockImportAdapter<Self::BlockImport>,
Option<BoxJustificationImport<Block>>,
Self::PeerData,
@@ -693,11 +713,7 @@ mod tests {
sp_tracing::try_init_simple();
let net = AuraTestNet::new(3);
let peers = &[
(0, Keyring::Alice),
(1, Keyring::Bob),
(2, Keyring::Charlie),
];
let peers = &[(0, Keyring::Alice), (1, Keyring::Bob), (2, Keyring::Charlie)];
let net = Arc::new(Mutex::new(net));
let mut import_notifications = Vec::new();
@@ -710,9 +726,9 @@ mod tests {
let client = peer.client().as_full().expect("full clients are created").clone();
let select_chain = peer.select_chain().expect("full client has a select chain");
let keystore_path = tempfile::tempdir().expect("Creates keystore path");
let keystore = Arc::new(LocalKeystore::open(keystore_path.path(), None)
.expect("Creates keystore."));
let keystore = Arc::new(
LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore."),
);
SyncCryptoStore::sr25519_generate_new(&*keystore, AURA, Some(&key.to_seed()))
.expect("Creates authority key");
@@ -720,38 +736,46 @@ mod tests {
let environ = DummyFactory(client.clone());
import_notifications.push(
client.import_notification_stream()
.take_while(|n| future::ready(!(n.origin != BlockOrigin::Own && n.header.number() < &5)))
.for_each(move |_| future::ready(()))
client
.import_notification_stream()
.take_while(|n| {
future::ready(!(n.origin != BlockOrigin::Own && n.header.number() < &5))
})
.for_each(move |_| future::ready(())),
);
let slot_duration = slot_duration(&*client).expect("slot duration available");
aura_futures.push(start_aura::<AuthorityPair, _, _, _, _, _, _, _, _, _, _, _>(StartAuraParams {
slot_duration,
block_import: client.clone(),
select_chain,
client,
proposer_factory: environ,
sync_oracle: DummyOracle,
justification_sync_link: (),
create_inherent_data_providers: |_, _| async {
let timestamp = TimestampInherentDataProvider::from_system_time();
let slot = InherentDataProvider::from_timestamp_and_duration(
*timestamp,
Duration::from_secs(6),
);
aura_futures.push(
start_aura::<AuthorityPair, _, _, _, _, _, _, _, _, _, _, _>(StartAuraParams {
slot_duration,
block_import: client.clone(),
select_chain,
client,
proposer_factory: environ,
sync_oracle: DummyOracle,
justification_sync_link: (),
create_inherent_data_providers: |_, _| async {
let timestamp = TimestampInherentDataProvider::from_system_time();
let slot = InherentDataProvider::from_timestamp_and_duration(
*timestamp,
Duration::from_secs(6),
);
Ok((timestamp, slot))
},
force_authoring: false,
backoff_authoring_blocks: Some(BackoffAuthoringOnFinalizedHeadLagging::default()),
keystore,
can_author_with: sp_consensus::AlwaysCanAuthor,
block_proposal_slot_portion: SlotProportion::new(0.5),
max_block_proposal_slot_portion: None,
telemetry: None,
}).expect("Starts aura"));
Ok((timestamp, slot))
},
force_authoring: false,
backoff_authoring_blocks: Some(
BackoffAuthoringOnFinalizedHeadLagging::default(),
),
keystore,
can_author_with: sp_consensus::AlwaysCanAuthor,
block_proposal_slot_portion: SlotProportion::new(0.5),
max_block_proposal_slot_portion: None,
telemetry: None,
})
.expect("Starts aura"),
);
}
futures::executor::block_on(future::select(
@@ -759,10 +783,7 @@ mod tests {
net.lock().poll(cx);
Poll::<()>::Pending
}),
future::select(
future::join_all(aura_futures),
future::join_all(import_notifications)
)
future::select(future::join_all(aura_futures), future::join_all(import_notifications)),
));
}
@@ -771,11 +792,14 @@ mod tests {
let client = substrate_test_runtime_client::new();
assert_eq!(client.chain_info().best_number, 0);
assert_eq!(authorities(&client, &BlockId::Number(0)).unwrap(), vec![
Keyring::Alice.public().into(),
Keyring::Bob.public().into(),
Keyring::Charlie.public().into()
]);
assert_eq!(
authorities(&client, &BlockId::Number(0)).unwrap(),
vec![
Keyring::Alice.public().into(),
Keyring::Bob.public().into(),
Keyring::Charlie.public().into()
]
);
}
#[test]
@@ -785,12 +809,11 @@ mod tests {
let mut authorities = vec![
Keyring::Alice.public().into(),
Keyring::Bob.public().into(),
Keyring::Charlie.public().into()
Keyring::Charlie.public().into(),
];
let keystore_path = tempfile::tempdir().expect("Creates keystore path");
let keystore = LocalKeystore::open(keystore_path.path(), None)
.expect("Creates keystore.");
let keystore = LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore.");
let public = SyncCryptoStore::sr25519_generate_new(&keystore, AuthorityPair::ID, None)
.expect("Key should be created");
authorities.push(public.into());
@@ -822,7 +845,7 @@ mod tests {
H256::from_low_u64_be(0),
H256::from_low_u64_be(0),
Default::default(),
Default::default()
Default::default(),
);
assert!(worker.claim_slot(&head, 0.into(), &authorities).is_none());
assert!(worker.claim_slot(&head, 1.into(), &authorities).is_none());
@@ -839,12 +862,13 @@ mod tests {
let net = AuraTestNet::new(4);
let keystore_path = tempfile::tempdir().expect("Creates keystore path");
let keystore = LocalKeystore::open(keystore_path.path(), None)
.expect("Creates keystore.");
let keystore = LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore.");
SyncCryptoStore::sr25519_generate_new(
&keystore,
AuthorityPair::ID, Some(&Keyring::Alice.to_seed()),
).expect("Key should be created");
AuthorityPair::ID,
Some(&Keyring::Alice.to_seed()),
)
.expect("Key should be created");
let net = Arc::new(Mutex::new(net));
@@ -870,17 +894,16 @@ mod tests {
let head = client.header(&BlockId::Number(0)).unwrap().unwrap();
let res = futures::executor::block_on(worker.on_slot(
SlotInfo {
slot: 0.into(),
timestamp: 0.into(),
ends_at: Instant::now() + Duration::from_secs(100),
inherent_data: InherentData::new(),
duration: Duration::from_millis(1000),
chain_head: head,
block_size_limit: None,
}
)).unwrap();
let res = futures::executor::block_on(worker.on_slot(SlotInfo {
slot: 0.into(),
timestamp: 0.into(),
ends_at: Instant::now() + Duration::from_secs(100),
inherent_data: InherentData::new(),
duration: Duration::from_millis(1000),
chain_head: head,
block_size_limit: None,
}))
.unwrap();
// The returned block should be imported and we should be able to get its header by now.
assert!(client.header(&BlockId::Hash(res.block.hash())).unwrap().is_some());