ci: add quick-check with rustfmt (#615)

* ci: add quick-check with clippy and rustfmt

* chore: rustfmt round

* chore: set the same rustfmt config than substrate

* chore: fix formatting

* cI: remove clippy

* ci: switch to nightly for the checks

* ci: fix toolchains and naming

* ci: Limit the check to formatting

* chore: fix formatting

* Update .rustfmt.toml

* Update .rustfmt.toml

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
This commit is contained in:
Chevdor
2021-09-16 16:57:52 +02:00
committed by GitHub
parent 035a576008
commit 1dd000a011
98 changed files with 1244 additions and 1872 deletions
+37 -66
View File
@@ -33,13 +33,13 @@ use sp_runtime::{
traits::{Block as BlockT, HashFor, Header as HeaderT},
};
use polkadot_node_primitives::{SignedFullStatement, Statement, CollationSecondedSignal};
use polkadot_client::ClientHandle;
use polkadot_node_primitives::{CollationSecondedSignal, SignedFullStatement, Statement};
use polkadot_parachain::primitives::HeadData;
use polkadot_primitives::v1::{
Block as PBlock, Hash as PHash, CandidateReceipt, CompactStatement, Id as ParaId,
OccupiedCoreAssumption, ParachainHost, UncheckedSigned, SigningContext,
Block as PBlock, CandidateReceipt, CompactStatement, Hash as PHash, Id as ParaId,
OccupiedCoreAssumption, ParachainHost, SigningContext, UncheckedSigned,
};
use polkadot_client::ClientHandle;
use codec::{Decode, Encode};
use futures::{
@@ -85,14 +85,13 @@ impl BlockAnnounceData {
///
/// This will not check the signature, for this you should use [`BlockAnnounceData::check_signature`].
fn validate(&self, encoded_header: Vec<u8>) -> Result<(), Validation> {
let candidate_hash = if let CompactStatement::Seconded(h) = self.statement.unchecked_payload() {
let candidate_hash = if let CompactStatement::Seconded(h) =
self.statement.unchecked_payload()
{
h
} else {
tracing::debug!(
target: LOG_TARGET,
"`CompactStatement` isn't the candidate variant!",
);
return Err(Validation::Failure { disconnect: true });
tracing::debug!(target: LOG_TARGET, "`CompactStatement` isn't the candidate variant!",);
return Err(Validation::Failure { disconnect: true })
};
if *candidate_hash != self.receipt.hash() {
@@ -100,7 +99,7 @@ impl BlockAnnounceData {
target: LOG_TARGET,
"Receipt candidate hash doesn't match candidate hash in statement",
);
return Err(Validation::Failure { disconnect: true });
return Err(Validation::Failure { disconnect: true })
}
if HeadData(encoded_header).hash() != self.receipt.descriptor.para_head {
@@ -108,7 +107,7 @@ impl BlockAnnounceData {
target: LOG_TARGET,
"Receipt para head hash doesn't match the hash of the header in the block announcement",
);
return Err(Validation::Failure { disconnect: true });
return Err(Validation::Failure { disconnect: true })
}
Ok(())
@@ -131,22 +130,16 @@ impl BlockAnnounceData {
let runtime_api_block_id = BlockId::Hash(self.receipt.descriptor.relay_parent);
let session_index = match runtime_api.session_index_for_child(&runtime_api_block_id) {
Ok(r) => r,
Err(e) => {
return Err(BlockAnnounceError(format!("{:?}", e)));
}
Err(e) => return Err(BlockAnnounceError(format!("{:?}", e))),
};
let signing_context = SigningContext {
parent_hash: self.receipt.descriptor.relay_parent,
session_index,
};
let signing_context =
SigningContext { parent_hash: self.receipt.descriptor.relay_parent, session_index };
// Check that the signer is a legit validator.
let authorities = match runtime_api.validators(&runtime_api_block_id) {
Ok(r) => r,
Err(e) => {
return Err(BlockAnnounceError(format!("{:?}", e)));
}
Err(e) => return Err(BlockAnnounceError(format!("{:?}", e))),
};
let signer = match authorities.get(validator_index.0 as usize) {
Some(r) => r,
@@ -156,22 +149,18 @@ impl BlockAnnounceData {
"Block announcement justification signer is a validator index out of bound",
);
return Ok(Validation::Failure { disconnect: true });
}
return Ok(Validation::Failure { disconnect: true })
},
};
// Check statement is correctly signed.
if self
.statement
.try_into_checked(&signing_context, &signer)
.is_err()
{
if self.statement.try_into_checked(&signing_context, &signer).is_err() {
tracing::debug!(
target: LOG_TARGET,
"Block announcement justification signature is invalid.",
);
return Ok(Validation::Failure { disconnect: true });
return Ok(Validation::Failure { disconnect: true })
}
Ok(Validation::Success { is_new_best: true })
@@ -185,13 +174,10 @@ impl TryFrom<&'_ SignedFullStatement> for BlockAnnounceData {
let receipt = if let Statement::Seconded(receipt) = stmt.payload() {
receipt.to_plain()
} else {
return Err(());
return Err(())
};
Ok(BlockAnnounceData {
receipt,
statement: stmt.convert_payload().into(),
})
Ok(BlockAnnounceData { receipt, statement: stmt.convert_payload().into() })
}
}
@@ -273,16 +259,13 @@ where
.persisted_validation_data(block_id, para_id, OccupiedCoreAssumption::TimedOut)
.map_err(|e| Box::new(BlockAnnounceError(format!("{:?}", e))) as Box<_>)?
.ok_or_else(|| {
Box::new(BlockAnnounceError(
"Could not find parachain head in relay chain".into(),
)) as Box<_>
Box::new(BlockAnnounceError("Could not find parachain head in relay chain".into()))
as Box<_>
})?;
let para_head =
Block::Header::decode(&mut &validation_data.parent_head.0[..]).map_err(|e| {
Box::new(BlockAnnounceError(format!(
"Failed to decode parachain head: {:?}",
e
))) as Box<_>
Box::new(BlockAnnounceError(format!("Failed to decode parachain head: {:?}", e)))
as Box<_>
})?;
Ok(para_head)
@@ -320,21 +303,15 @@ where
let best_head =
Self::included_block(&*relay_chain_client, &runtime_api_block_id, para_id)?;
let known_best_number = best_head.number();
let backed_block = ||
Self::backed_block_hash(&*relay_chain_client, &runtime_api_block_id, para_id);
let backed_block =
|| Self::backed_block_hash(&*relay_chain_client, &runtime_api_block_id, para_id);
if best_head == header {
tracing::debug!(
target: LOG_TARGET,
"Announced block matches best block.",
);
tracing::debug!(target: LOG_TARGET, "Announced block matches best block.",);
Ok(Validation::Success { is_new_best: true })
} else if Some(HeadData(header.encode()).hash()) == backed_block()? {
tracing::debug!(
target: LOG_TARGET,
"Announced block matches latest backed block.",
);
tracing::debug!(target: LOG_TARGET, "Announced block matches latest backed block.",);
Ok(Validation::Success { is_new_best: true })
} else if block_number >= known_best_number {
@@ -367,23 +344,20 @@ where
mut data: &[u8],
) -> Pin<Box<dyn Future<Output = Result<Validation, BoxedError>> + Send>> {
if self.relay_chain_sync_oracle.is_major_syncing() {
return ready(Ok(Validation::Success { is_new_best: false })).boxed();
return ready(Ok(Validation::Success { is_new_best: false })).boxed()
}
if data.is_empty() {
return self
.handle_empty_block_announce_data(header.clone())
.boxed();
return self.handle_empty_block_announce_data(header.clone()).boxed()
}
let block_announce_data = match BlockAnnounceData::decode(&mut data) {
Ok(r) => r,
Err(_) => {
Err(_) =>
return ready(Err(Box::new(BlockAnnounceError(
"Can not decode the `BlockAnnounceData`".into(),
)) as Box<_>))
.boxed()
}
.boxed(),
};
let relay_chain_client = self.relay_chain_client.clone();
@@ -392,7 +366,7 @@ where
async move {
if let Err(e) = block_announce_data.validate(header_encoded) {
return Ok(e);
return Ok(e)
}
let relay_parent = block_announce_data.receipt.descriptor.relay_parent;
@@ -519,10 +493,7 @@ impl<Block: BlockT> WaitToAnnounce<Block> {
spawner: Arc<dyn SpawnNamed + Send + Sync>,
announce_block: Arc<dyn Fn(Block::Hash, Option<Vec<u8>>) + Send + Sync>,
) -> WaitToAnnounce<Block> {
WaitToAnnounce {
spawner,
announce_block,
}
WaitToAnnounce { spawner, announce_block }
}
/// Wait for a candidate message for the block, then announce the block. The candidate
@@ -567,8 +538,8 @@ async fn wait_to_announce<Block: BlockT>(
block = ?block_hash,
"Wait to announce stopped, because sender was dropped.",
);
return;
}
return
},
};
if let Ok(data) = BlockAnnounceData::try_from(&statement) {
+23 -68
View File
@@ -15,15 +15,16 @@
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use super::*;
use cumulus_test_service::runtime::{Block, Header, Hash};
use cumulus_test_service::runtime::{Block, Hash, Header};
use futures::{executor::block_on, poll, task::Poll};
use parking_lot::Mutex;
use polkadot_node_primitives::{SignedFullStatement, Statement};
use polkadot_primitives::v1::{
Block as PBlock, BlockNumber, CandidateCommitments, CandidateDescriptor, CandidateEvent,
CommittedCandidateReceipt, CoreState, GroupRotationInfo, Hash as PHash, HeadData, Id as ParaId,
InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption, ParachainHost,
PersistedValidationData, SessionIndex, SessionInfo, SigningContext, ValidationCode, ValidationCodeHash,
ValidatorId, ValidatorIndex,
PersistedValidationData, SessionIndex, SessionInfo, SigningContext, ValidationCode,
ValidationCodeHash, ValidatorId, ValidatorIndex,
};
use polkadot_test_client::{
Client as PClient, ClientBlockImportExt, DefaultTestClientBuilderExt, FullBackend as PBackend,
@@ -37,7 +38,6 @@ use sp_keyring::Sr25519Keyring;
use sp_keystore::{testing::KeyStore, SyncCryptoStore, SyncCryptoStorePtr};
use sp_runtime::RuntimeAppPublic;
use std::collections::BTreeMap;
use parking_lot::Mutex;
fn check_error(error: crate::BoxedError, check_error: impl Fn(&BlockAnnounceError) -> bool) {
let error = *error
@@ -61,10 +61,8 @@ impl SyncOracle for DummyCollatorNetwork {
}
}
fn make_validator_and_api() -> (
BlockAnnounceValidator<Block, TestApi, PBackend, PClient>,
Arc<TestApi>,
) {
fn make_validator_and_api(
) -> (BlockAnnounceValidator<Block, TestApi, PBackend, PClient>, Arc<TestApi>) {
let api = Arc::new(TestApi::new());
(
@@ -94,12 +92,7 @@ async fn make_gossip_message_and_header_using_genesis(
api: Arc<TestApi>,
validator_index: u32,
) -> (SignedFullStatement, Header) {
let relay_parent = api
.relay_client
.hash(0)
.ok()
.flatten()
.expect("Genesis hash exists");
let relay_parent = api.relay_client.hash(0).ok().flatten().expect("Genesis hash exists");
make_gossip_message_and_header(api, relay_parent, validator_index).await
}
@@ -116,14 +109,9 @@ async fn make_gossip_message_and_header(
Some(&Sr25519Keyring::Alice.to_seed()),
)
.unwrap();
let session_index = api
.runtime_api()
.session_index_for_child(&BlockId::Hash(relay_parent))
.unwrap();
let signing_context = SigningContext {
parent_hash: relay_parent,
session_index,
};
let session_index =
api.runtime_api().session_index_for_child(&BlockId::Hash(relay_parent)).unwrap();
let signing_context = SigningContext { parent_hash: relay_parent, session_index };
let header = default_header();
let candidate_receipt = CommittedCandidateReceipt {
@@ -156,10 +144,7 @@ async fn make_gossip_message_and_header(
#[test]
fn valid_if_no_data_and_less_than_best_known_number() {
let mut validator = make_validator_and_api().0;
let header = Header {
number: 0,
..default_header()
};
let header = Header { number: 0, ..default_header() };
let res = block_on(validator.validate(&header, &[]));
assert_eq!(
@@ -172,11 +157,7 @@ fn valid_if_no_data_and_less_than_best_known_number() {
#[test]
fn invalid_if_no_data_exceeds_best_known_number() {
let mut validator = make_validator_and_api().0;
let header = Header {
number: 1,
state_root: Hash::random(),
..default_header()
};
let header = Header { number: 1, state_root: Hash::random(), ..default_header() };
let res = block_on(validator.validate(&header, &[]));
assert_eq!(
@@ -219,9 +200,7 @@ fn check_signer_is_legit_validator() {
let (mut validator, api) = make_validator_and_api();
let (signed_statement, header) = block_on(make_gossip_message_and_header_using_genesis(api, 1));
let data = BlockAnnounceData::try_from(&signed_statement)
.unwrap()
.encode();
let data = BlockAnnounceData::try_from(&signed_statement).unwrap().encode();
let res = block_on(validator.validate(&header, &data));
assert_eq!(Validation::Failure { disconnect: true }, res.unwrap());
@@ -233,9 +212,7 @@ fn check_statement_is_correctly_signed() {
let (signed_statement, header) = block_on(make_gossip_message_and_header_using_genesis(api, 0));
let mut data = BlockAnnounceData::try_from(&signed_statement)
.unwrap()
.encode();
let mut data = BlockAnnounceData::try_from(&signed_statement).unwrap().encode();
// The signature comes at the end of the type, so change a bit to make the signature invalid.
let last = data.len() - 1;
@@ -258,14 +235,9 @@ fn check_statement_seconded() {
Some(&Sr25519Keyring::Alice.to_seed()),
)
.unwrap();
let session_index = api
.runtime_api()
.session_index_for_child(&BlockId::Hash(relay_parent))
.unwrap();
let signing_context = SigningContext {
parent_hash: relay_parent,
session_index,
};
let session_index =
api.runtime_api().session_index_for_child(&BlockId::Hash(relay_parent)).unwrap();
let signing_context = SigningContext { parent_hash: relay_parent, session_index };
let statement = Statement::Valid(Default::default());
@@ -296,9 +268,7 @@ fn check_header_match_candidate_receipt_header() {
let (signed_statement, mut header) =
block_on(make_gossip_message_and_header_using_genesis(api, 0));
let data = BlockAnnounceData::try_from(&signed_statement)
.unwrap()
.encode();
let data = BlockAnnounceData::try_from(&signed_statement).unwrap().encode();
header.number = 300;
let res = block_on(validator.validate(&header, &data));
@@ -315,17 +285,11 @@ fn relay_parent_not_imported_when_block_announce_is_processed() {
let (mut validator, api) = make_validator_and_api();
let mut client = api.relay_client.clone();
let block = client
.init_polkadot_block_builder()
.build()
.expect("Build new block")
.block;
let block = client.init_polkadot_block_builder().build().expect("Build new block").block;
let (signed_statement, header) = make_gossip_message_and_header(api, block.hash(), 0).await;
let data = BlockAnnounceData::try_from(&signed_statement)
.unwrap()
.encode();
let data = BlockAnnounceData::try_from(&signed_statement).unwrap().encode();
let mut validation = validator.validate(&header, &data);
@@ -333,10 +297,7 @@ fn relay_parent_not_imported_when_block_announce_is_processed() {
// that the future is still pending.
assert!(poll!(&mut validation).is_pending());
client
.import(BlockOrigin::Own, block)
.await
.expect("Imports the block");
client.import(BlockOrigin::Own, block).await.expect("Imports the block");
assert!(matches!(
poll!(validation),
@@ -357,10 +318,7 @@ fn block_announced_without_statement_and_block_only_backed() {
let validation = validator.validate(&header, &[]);
assert!(matches!(
validation.await,
Ok(Validation::Success { is_new_best: true })
));
assert!(matches!(validation.await, Ok(Validation::Success { is_new_best: true })));
});
}
@@ -401,10 +359,7 @@ impl ProvideRuntimeApi<PBlock> for TestApi {
type Api = RuntimeApi;
fn runtime_api<'a>(&'a self) -> ApiRef<'a, Self::Api> {
RuntimeApi {
data: self.data.clone(),
}
.into()
RuntimeApi { data: self.data.clone() }.into()
}
}
+11 -39
View File
@@ -31,10 +31,7 @@ const TIMEOUT_IN_SECONDS: u64 = 6;
/// Custom error type used by [`WaitOnRelayChainBlock`].
#[derive(Debug, derive_more::Display)]
pub enum Error {
#[display(
fmt = "Timeout while waiting for relay-chain block `{}` to be imported.",
_0
)]
#[display(fmt = "Timeout while waiting for relay-chain block `{}` to be imported.", _0)]
Timeout(PHash),
#[display(
fmt = "Import listener closed while waiting for relay-chain block `{}` to be imported.",
@@ -73,20 +70,14 @@ pub struct WaitOnRelayChainBlock<B, BCE> {
impl<B, BCE> Clone for WaitOnRelayChainBlock<B, BCE> {
fn clone(&self) -> Self {
Self {
backend: self.backend.clone(),
block_chain_events: self.block_chain_events.clone(),
}
Self { backend: self.backend.clone(), block_chain_events: self.block_chain_events.clone() }
}
}
impl<B, BCE> WaitOnRelayChainBlock<B, BCE> {
/// Creates a new instance of `Self`.
pub fn new(backend: Arc<B>, block_chain_events: Arc<BCE>) -> Self {
Self {
backend,
block_chain_events,
}
Self { backend, block_chain_events }
}
}
@@ -103,11 +94,9 @@ where
) -> impl Future<Output = Result<(), Error>> {
let _lock = self.backend.get_import_lock().read();
match self.backend.blockchain().status(BlockId::Hash(hash)) {
Ok(BlockStatus::InChain) => {
return ready(Ok(())).boxed();
}
Ok(BlockStatus::InChain) => return ready(Ok(())).boxed(),
Err(err) => return ready(Err(Error::BlockchainError(hash, err))).boxed(),
_ => {}
_ => {},
}
let mut listener = self.block_chain_events.import_notification_stream();
@@ -171,10 +160,7 @@ mod tests {
block_on(async move {
// Should be ready on the first poll
assert!(matches!(
poll!(wait.wait_on_relay_chain_block(hash)),
Poll::Ready(Ok(()))
));
assert!(matches!(poll!(wait.wait_on_relay_chain_block(hash)), Poll::Ready(Ok(()))));
});
}
@@ -191,10 +177,7 @@ mod tests {
assert!(poll!(&mut future).is_pending());
// Import the block that should fire the notification
client
.import(BlockOrigin::Own, block)
.await
.expect("Imports the block");
client.import(BlockOrigin::Own, block).await.expect("Imports the block");
// Now it should have received the notification and report that the block was imported
assert!(matches!(poll!(future), Poll::Ready(Ok(()))));
@@ -208,10 +191,7 @@ mod tests {
let wait = WaitOnRelayChainBlock::new(backend, client.clone());
assert!(matches!(
block_on(wait.wait_on_relay_chain_block(hash)),
Err(Error::Timeout(_))
));
assert!(matches!(block_on(wait.wait_on_relay_chain_block(hash)), Err(Error::Timeout(_))));
}
#[test]
@@ -227,9 +207,7 @@ mod tests {
);
let mut block_builder = client.init_polkadot_block_builder();
// Push an extrinsic to get a different block hash.
block_builder
.push_polkadot_extrinsic(ext)
.expect("Push extrinsic");
block_builder.push_polkadot_extrinsic(ext).expect("Push extrinsic");
let block2 = block_builder.build().expect("Build second block").block;
let hash2 = block2.hash();
@@ -243,20 +221,14 @@ mod tests {
assert!(poll!(&mut future2).is_pending());
// Import the block that should fire the notification
client
.import(BlockOrigin::Own, block2)
.await
.expect("Imports the second block");
client.import(BlockOrigin::Own, block2).await.expect("Imports the second block");
// The import notification of the second block should not make this one finish
assert!(poll!(&mut future).is_pending());
// Now it should have received the notification and report that the block was imported
assert!(matches!(poll!(future2), Poll::Ready(Ok(()))));
client
.import(BlockOrigin::Own, block)
.await
.expect("Imports the first block");
client.import(BlockOrigin::Own, block).await.expect("Imports the first block");
// Now it should be ready
assert!(matches!(poll!(future), Poll::Ready(Ok(()))));