Skip to content

Commit

Permalink
Update polkadot to the latest master (paritytech#251)
Browse files Browse the repository at this point in the history
* update cumulus to latest polkadot

* s/Trait/Config

To be more consistent with the new naming.

* Update Cargo.lock

* fix network tests
  • Loading branch information
pepyakin authored Dec 1, 2020
1 parent 4e82ce6 commit ba1fa36
Show file tree
Hide file tree
Showing 10 changed files with 359 additions and 326 deletions.
529 changes: 276 additions & 253 deletions Cargo.lock

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions message-broker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,19 @@ use cumulus_primitives::{
};

/// Configuration trait of the message broker pallet.
pub trait Trait: frame_system::Trait {
pub trait Config: frame_system::Config {
/// The downward message handlers that will be informed when a message is received.
type DownwardMessageHandlers: DownwardMessageHandler;
}

decl_storage! {
trait Store for Module<T: Trait> as MessageBroker {
trait Store for Module<T: Config> as MessageBroker {
PendingUpwardMessages: Vec<UpwardMessage>;
}
}

decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
pub struct Module<T: Config> for enum Call where origin: T::Origin {
/// An entrypoint for an inherent to deposit downward messages into the runtime. It accepts
/// and processes the list of downward messages.
#[weight = (10, DispatchClass::Mandatory)]
Expand Down Expand Up @@ -96,7 +96,7 @@ pub enum SendUpErr {
TooBig,
}

impl<T: Trait> Module<T> {
impl<T: Config> Module<T> {
pub fn send_upward_message(message: UpwardMessage) -> Result<(), SendUpErr> {
// TODO: check the message against the limit. The limit should be sourced from the
// relay-chain configuration.
Expand All @@ -105,7 +105,7 @@ impl<T: Trait> Module<T> {
}
}

impl<T: Trait> ProvideInherent for Module<T> {
impl<T: Config> ProvideInherent for Module<T> {
type Call = Call<T>;
type Error = MakeFatalError<()>;
const INHERENT_IDENTIFIER: InherentIdentifier = DOWNWARD_MESSAGES_IDENTIFIER;
Expand Down
42 changes: 26 additions & 16 deletions network/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ mod wait_on_relay_chain_block;

use sc_client_api::{Backend, BlockchainEvents};
use sp_api::ProvideRuntimeApi;
use sp_blockchain::{Error as ClientError, HeaderBackend};
use sp_blockchain::HeaderBackend;
use sp_consensus::{
block_validation::{BlockAnnounceValidator as BlockAnnounceValidatorT, Validation},
SyncOracle,
Expand Down Expand Up @@ -54,11 +54,21 @@ use futures::{
};
use log::trace;

use std::{marker::PhantomData, pin::Pin, sync::Arc};
use std::{marker::PhantomData, pin::Pin, sync::Arc, fmt};

use wait_on_relay_chain_block::WaitOnRelayChainBlock;

type BlockAnnounceError = Box<dyn std::error::Error + Send>;
type BoxedError = Box<dyn std::error::Error + Send>;

#[derive(Debug)]
struct BlockAnnounceError(String);
impl std::error::Error for BlockAnnounceError { }

impl fmt::Display for BlockAnnounceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}

/// Parachain specific block announce validator.
///
Expand Down Expand Up @@ -131,7 +141,7 @@ where
fn handle_empty_block_announce_data(
&self,
header: Block::Header,
) -> impl Future<Output = Result<Validation, BlockAnnounceError>> {
) -> impl Future<Output = Result<Validation, BoxedError>> {
let relay_chain_client = self.relay_chain_client.clone();
let relay_chain_backend = self.relay_chain_backend.clone();
let para_id = self.para_id;
Expand All @@ -149,15 +159,15 @@ where
para_id,
OccupiedCoreAssumption::TimedOut,
)
.map_err(|e| Box::new(ClientError::Msg(format!("{:?}", e))) as Box<_>)?
.map_err(|e| Box::new(BlockAnnounceError(format!("{:?}", e))) as Box<_>)?
.ok_or_else(|| {
Box::new(ClientError::Msg(
Box::new(BlockAnnounceError(
"Could not find parachain head in relay chain".into(),
)) as Box<_>
})?;
let parent_head = Block::Header::decode(&mut &local_validation_data.parent_head.0[..])
.map_err(|e| {
Box::new(ClientError::Msg(format!(
Box::new(BlockAnnounceError(format!(
"Failed to decode parachain head: {:?}",
e
))) as Box<_>
Expand Down Expand Up @@ -192,7 +202,7 @@ where
&mut self,
header: &Block::Header,
mut data: &[u8],
) -> Pin<Box<dyn Future<Output = Result<Validation, BlockAnnounceError>> + Send>> {
) -> 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();
}
Expand All @@ -205,7 +215,7 @@ where

let signed_stmt = match SignedFullStatement::decode(&mut data) {
Ok(r) => r,
Err(_) => return ready(Err(Box::new(ClientError::Msg(
Err(_) => return ready(Err(Box::new(BlockAnnounceError(
"cannot decode block announcement justification, must be a `SignedFullStatement`"
.into(),
)) as Box<_>))
Expand All @@ -221,15 +231,15 @@ where
let candidate_receipt = match signed_stmt.payload() {
Statement::Seconded(ref candidate_receipt) => candidate_receipt,
_ => {
return Err(Box::new(ClientError::Msg(
return Err(Box::new(BlockAnnounceError(
"block announcement justification must be a `Statement::Seconded`".into(),
)) as Box<_>)
}
};

// Check the header in the candidate_receipt match header given header.
if header_encoded != candidate_receipt.commitments.head_data.0 {
return Err(Box::new(ClientError::Msg(
return Err(Box::new(BlockAnnounceError(
"block announcement header does not match the one justified".into(),
)) as Box<_>);
}
Expand All @@ -239,7 +249,7 @@ where
wait_on_relay_chain_block
.wait_on_relay_chain_block(*relay_parent)
.await
.map_err(|e| Box::new(ClientError::Msg(e.to_string())) as Box<_>)?;
.map_err(|e| Box::new(BlockAnnounceError(e.to_string())) as Box<_>)?;

let runtime_api = relay_chain_client.runtime_api();
let validator_index = signed_stmt.validator_index();
Expand All @@ -248,7 +258,7 @@ where
let session_index = match runtime_api.session_index_for_child(&runtime_api_block_id) {
Ok(r) => r,
Err(e) => {
return Err(Box::new(ClientError::Msg(format!("{:?}", e))) as Box<_>);
return Err(Box::new(BlockAnnounceError(format!("{:?}", e))) as Box<_>);
}
};

Expand All @@ -261,13 +271,13 @@ where
let authorities = match runtime_api.validators(&runtime_api_block_id) {
Ok(r) => r,
Err(e) => {
return Err(Box::new(ClientError::Msg(format!("{:?}", e))) as Box<_>);
return Err(Box::new(BlockAnnounceError(format!("{:?}", e))) as Box<_>);
}
};
let signer = match authorities.get(validator_index as usize) {
Some(r) => r,
None => {
return Err(Box::new(ClientError::Msg(
return Err(Box::new(BlockAnnounceError(
"block accouncement justification signer is a validator index out of bound"
.to_string(),
)) as Box<_>);
Expand All @@ -279,7 +289,7 @@ where
.check_signature(&signing_context, &signer)
.is_err()
{
return Err(Box::new(ClientError::Msg(
return Err(Box::new(BlockAnnounceError(
"block announcement justification signature is invalid".to_string(),
)) as Box<_>);
}
Expand Down
22 changes: 11 additions & 11 deletions network/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,24 @@ use polkadot_primitives::v1::{
CandidateEvent, CommittedCandidateReceipt, CoreState, GroupRotationInfo, Hash as PHash,
HeadData, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption,
ParachainHost, PersistedValidationData, SessionIndex, SigningContext, ValidationCode,
ValidationData, ValidationOutputs, ValidatorId, ValidatorIndex, SessionInfo,
ValidationData, ValidatorId, ValidatorIndex, SessionInfo,
};
use polkadot_test_client::{
Client as PClient, ClientBlockImportExt, DefaultTestClientBuilderExt, FullBackend as PBackend,
InitPolkadotBlockBuilder, TestClientBuilder, TestClientBuilderExt,
};
use sp_api::{ApiRef, ProvideRuntimeApi};
use sp_blockchain::{Error as ClientError, HeaderBackend};
use sp_blockchain::HeaderBackend;
use sp_consensus::{block_validation::BlockAnnounceValidator as _, BlockOrigin};
use sp_core::H256;
use sp_keyring::Sr25519Keyring;
use sp_keystore::{testing::KeyStore, SyncCryptoStore, SyncCryptoStorePtr};
use sp_runtime::RuntimeAppPublic;
use std::collections::BTreeMap;

fn check_error(error: crate::BlockAnnounceError, check_error: impl Fn(&ClientError) -> bool) {
fn check_error(error: crate::BoxedError, check_error: impl Fn(&BlockAnnounceError) -> bool) {
let error = *error
.downcast::<ClientError>()
.downcast::<BlockAnnounceError>()
.expect("Downcasts error to `ClientError`");
if !check_error(&error) {
panic!("Invalid error: {:?}", error);
Expand Down Expand Up @@ -192,7 +192,7 @@ fn check_statement_is_encoded_correctly() {
check_error(res, |error| {
matches!(
error,
ClientError::Msg(x) if x.contains("must be a `SignedFullStatement`")
BlockAnnounceError(x) if x.contains("must be a `SignedFullStatement`")
)
});
}
Expand All @@ -209,8 +209,8 @@ fn check_signer_is_legit_validator() {
.expect("Should fail on invalid validator");

assert!(matches!(
*res.downcast::<ClientError>().unwrap(),
ClientError::Msg(x) if x.contains("signer is a validator")
*res.downcast::<BlockAnnounceError>().unwrap(),
BlockAnnounceError(x) if x.contains("signer is a validator")
));
}

Expand All @@ -233,7 +233,7 @@ fn check_statement_is_correctly_signed() {
check_error(res, |error| {
matches!(
error,
ClientError::Msg(x) if x.contains("signature is invalid")
BlockAnnounceError(x) if x.contains("signature is invalid")
)
});
}
Expand Down Expand Up @@ -279,7 +279,7 @@ fn check_statement_seconded() {
check_error(res, |error| {
matches!(
error,
ClientError::Msg(x) if x.contains("must be a `Statement::Seconded`")
BlockAnnounceError(x) if x.contains("must be a `Statement::Seconded`")
)
});
}
Expand All @@ -300,7 +300,7 @@ fn check_header_match_candidate_receipt_header() {
check_error(res, |error| {
matches!(
error,
ClientError::Msg(x) if x.contains("header does not match")
BlockAnnounceError(x) if x.contains("header does not match")
)
});
}
Expand Down Expand Up @@ -431,7 +431,7 @@ sp_api::mock_impl_runtime_apis! {
None
}

fn check_validation_outputs(_: ParaId, _: ValidationOutputs) -> bool {
fn check_validation_outputs(_: ParaId, _: CandidateCommitments) -> bool {
false
}

Expand Down
24 changes: 12 additions & 12 deletions parachain-upgrade/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,17 +47,17 @@ use sp_std::vec::Vec;
type System<T> = frame_system::Module<T>;

/// The pallet's configuration trait.
pub trait Trait: frame_system::Trait {
pub trait Config: frame_system::Config {
/// The overarching event type.
type Event: From<Event> + Into<<Self as frame_system::Trait>::Event>;
type Event: From<Event> + Into<<Self as frame_system::Config>::Event>;

/// Something which can be notified when the validation data is set.
type OnValidationData: OnValidationData;
}

// This pallet's storage items.
decl_storage! {
trait Store for Module<T: Trait> as ParachainUpgrade {
trait Store for Module<T: Config> as ParachainUpgrade {
// we need to store the new validation function for the span between
// setting it and applying it.
PendingValidationFunction get(fn new_validation_function):
Expand All @@ -73,7 +73,7 @@ decl_storage! {

// The pallet's dispatchable functions.
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
pub struct Module<T: Config> for enum Call where origin: T::Origin {
// Initializing events
// this is needed only if you are using events in your pallet
fn deposit_event() = default;
Expand Down Expand Up @@ -146,7 +146,7 @@ decl_module! {
}
}

impl<T: Trait> Module<T> {
impl<T: Config> Module<T> {
/// Get validation data.
///
/// Returns `Some(_)` after the inherent set the data for the current block.
Expand Down Expand Up @@ -213,7 +213,7 @@ impl<T: Trait> Module<T> {
}
}

impl<T: Trait> ProvideInherent for Module<T> {
impl<T: Config> ProvideInherent for Module<T> {
type Call = Call<T>;
type Error = sp_inherents::MakeFatalError<()>;
const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
Expand All @@ -239,7 +239,7 @@ decl_event! {
}

decl_error! {
pub enum Error for Module<T: Trait> {
pub enum Error for Module<T: Config> {
/// Attempt to upgrade validation function while existing upgrade pending
OverlappingUpgrades,
/// Polkadot currently prohibits this parachain from upgrading its validation function
Expand Down Expand Up @@ -309,7 +309,7 @@ mod tests {
transaction_version: 1,
};
}
impl frame_system::Trait for Test {
impl frame_system::Config for Test {
type Origin = Origin;
type Call = ();
type Index = u64;
Expand All @@ -336,7 +336,7 @@ mod tests {
type BaseCallFilter = ();
type SystemWeightInfo = ();
}
impl Trait for Test {
impl Config for Test {
type Event = TestEvent;
type OnValidationData = ();
}
Expand Down Expand Up @@ -383,7 +383,7 @@ mod tests {
}

struct BlockTest {
n: <Test as frame_system::Trait>::BlockNumber,
n: <Test as frame_system::Config>::BlockNumber,
within_block: Box<dyn Fn()>,
after_block: Option<Box<dyn Fn()>>,
}
Expand All @@ -410,7 +410,7 @@ mod tests {
self
}

fn add<F>(self, n: <Test as frame_system::Trait>::BlockNumber, within_block: F) -> Self
fn add<F>(self, n: <Test as frame_system::Config>::BlockNumber, within_block: F) -> Self
where
F: 'static + Fn(),
{
Expand All @@ -423,7 +423,7 @@ mod tests {

fn add_with_post_test<F1, F2>(
self,
n: <Test as frame_system::Trait>::BlockNumber,
n: <Test as frame_system::Config>::BlockNumber,
within_block: F1,
after_block: F2,
) -> Self
Expand Down
Loading

0 comments on commit ba1fa36

Please sign in to comment.