From b4fb14bc521d270096b28df0d752cc174e934cb0 Mon Sep 17 00:00:00 2001 From: Peter Goodspeed-Niklaus Date: Thu, 5 Mar 2020 09:19:03 +0100 Subject: [PATCH 1/4] WIP: Add current_relay_block to ValidationParams, resolve circular dep Resolving the circular dependency was relatively simple: just move a bunch of parachain-specific stuff from the parachain package into the primitives package, then fix up the Cargo manifests. Then, publicly import all the stuff which was moved so that we don't break any external packages which depend on parachain. We have a deprecation notice on that `pub use` statement because downstream consumers should depend on items in the right place. Unfortunately, it doesn't actually do anything due to https://github.com/rust-lang/rust/issues/47236. Still, we'll leave it in against the day that bug gets fixed. Adding current_relay_block to ValidationParams is only part of the work, of course: we now need to go back to where that struct is instantiated, and insert it there, tracing it back until we get to some kind of relay chain instance from which we can get the actual current value and insert it appropriately. --- parachain/Cargo.toml | 2 + parachain/src/lib.rs | 164 +++--------------------------------- primitives/Cargo.toml | 7 +- primitives/src/parachain.rs | 159 ++++++++++++++++++++++++++++++++-- 4 files changed, 171 insertions(+), 161 deletions(-) diff --git a/parachain/Cargo.toml b/parachain/Cargo.toml index 85948c302244..a0104dc6f803 100644 --- a/parachain/Cargo.toml +++ b/parachain/Cargo.toml @@ -18,6 +18,7 @@ sp-io = { git = "https://github.com/paritytech/substrate", branch = "cumulus-bra lazy_static = { version = "1.4.0", optional = true } parking_lot = { version = "0.10.0", optional = true } log = { version = "0.4.8", optional = true } +polkadot-primitives = { path = "../primitives", default-features = false } [target.'cfg(not(target_os = "unknown"))'.dependencies] shared_memory = { version = "0.10.0", optional = true } @@ -44,4 +45,5 @@ std = [ "sp-externalities", "sc-executor", "sp-io", + "polkadot-primitives/std", ] diff --git a/parachain/src/lib.rs b/parachain/src/lib.rs index d1324140d78f..5367a01c0a1c 100644 --- a/parachain/src/lib.rs +++ b/parachain/src/lib.rs @@ -50,12 +50,21 @@ mod wasm_api; use rstd::vec::Vec; -use codec::{Encode, Decode, CompactAs}; -use sp_core::{RuntimeDebug, TypeId}; +use codec::{Encode, Decode}; #[cfg(all(not(feature = "std"), feature = "wasm-api"))] pub use wasm_api::*; +#[deprecated(note="moved to primitives package")] +pub use polkadot_primitives::{BlockNumber, parachain::{ + AccountIdConversion, + Id, + IncomingMessage, + LOWEST_USER_ID, + ParachainDispatchOrigin, + UpwardMessage, +}}; + /// Validation parameters for evaluating the parachain validity function. // TODO: balance downloads (https://github.com/paritytech/polkadot/issues/220) #[derive(PartialEq, Eq, Decode)] @@ -65,6 +74,8 @@ pub struct ValidationParams { pub block_data: Vec, /// Previous head-data. pub parent_head: Vec, + /// Number of the current relay chain block. + pub current_relay_block: BlockNumber, } /// The result of parachain validation. @@ -75,152 +86,3 @@ pub struct ValidationResult { /// New head data that should be included in the relay chain state. pub head_data: Vec, } - -/// Unique identifier of a parachain. -#[derive( - Clone, CompactAs, Copy, Decode, Default, Encode, Eq, - Hash, Ord, PartialEq, PartialOrd, RuntimeDebug, -)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize, derive_more::Display))] -pub struct Id(u32); - -impl TypeId for Id { - const TYPE_ID: [u8; 4] = *b"para"; -} - -/// Type for determining the active set of parachains. -pub trait ActiveThreads { - /// Return the current ordered set of `Id`s of active parathreads. - fn active_threads() -> Vec; -} - -impl From for u32 { - fn from(x: Id) -> Self { x.0 } -} - -impl From for Id { - fn from(x: u32) -> Self { Id(x) } -} - -const USER_INDEX_START: u32 = 1000; - -/// The ID of the first user (non-system) parachain. -pub const LOWEST_USER_ID: Id = Id(USER_INDEX_START); - -impl Id { - /// Create an `Id`. - pub const fn new(id: u32) -> Self { - Self(id) - } - - /// Returns `true` if this parachain runs with system-level privileges. - pub fn is_system(&self) -> bool { self.0 < USER_INDEX_START } -} - -impl rstd::ops::Add for Id { - type Output = Self; - - fn add(self, other: u32) -> Self { - Self(self.0 + other) - } -} - -// TODO: Remove all of this, move sp-runtime::AccountIdConversion to own crate and and use that. -// #360 -struct TrailingZeroInput<'a>(&'a [u8]); -impl<'a> codec::Input for TrailingZeroInput<'a> { - fn remaining_len(&mut self) -> Result, codec::Error> { - Ok(None) - } - - fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> { - let len = into.len().min(self.0.len()); - into[..len].copy_from_slice(&self.0[..len]); - for i in &mut into[len..] { - *i = 0; - } - self.0 = &self.0[len..]; - Ok(()) - } -} - -/// This type can be converted into and possibly from an AccountId (which itself is generic). -pub trait AccountIdConversion: Sized { - /// Convert into an account ID. This is infallible. - fn into_account(&self) -> AccountId; - - /// Try to convert an account ID into this type. Might not succeed. - fn try_from_account(a: &AccountId) -> Option; -} - -/// Format is b"para" ++ encode(parachain ID) ++ 00.... where 00... is indefinite trailing -/// zeroes to fill AccountId. -impl AccountIdConversion for Id { - fn into_account(&self) -> T { - (b"para", self).using_encoded(|b| - T::decode(&mut TrailingZeroInput(b)) - ).unwrap_or_default() - } - - fn try_from_account(x: &T) -> Option { - x.using_encoded(|d| { - if &d[0..4] != b"para" { return None } - let mut cursor = &d[4..]; - let result = Decode::decode(&mut cursor).ok()?; - if cursor.iter().all(|x| *x == 0) { - Some(result) - } else { - None - } - }) - } -} - -/// Which origin a parachain's message to the relay chain should be dispatched from. -#[derive(Clone, PartialEq, Eq, Encode, Decode)] -#[cfg_attr(feature = "std", derive(Debug))] -#[repr(u8)] -pub enum ParachainDispatchOrigin { - /// As a simple `Origin::Signed`, using `ParaId::account_id` as its value. This is good when - /// interacting with standard modules such as `balances`. - Signed, - /// As the special `Origin::Parachain(ParaId)`. This is good when interacting with parachain- - /// aware modules which need to succinctly verify that the origin is a parachain. - Parachain, - /// As the simple, superuser `Origin::Root`. This can only be done on specially permissioned - /// parachains. - Root, -} - -impl rstd::convert::TryFrom for ParachainDispatchOrigin { - type Error = (); - fn try_from(x: u8) -> core::result::Result { - const SIGNED: u8 = ParachainDispatchOrigin::Signed as u8; - const PARACHAIN: u8 = ParachainDispatchOrigin::Parachain as u8; - Ok(match x { - SIGNED => ParachainDispatchOrigin::Signed, - PARACHAIN => ParachainDispatchOrigin::Parachain, - _ => return Err(()), - }) - } -} - -/// A message from a parachain to its Relay Chain. -#[derive(Clone, PartialEq, Eq, Encode, Decode, sp_runtime_interface::pass_by::PassByCodec)] -#[cfg_attr(feature = "std", derive(Debug))] -pub struct UpwardMessage { - /// The origin for the message to be sent from. - pub origin: ParachainDispatchOrigin, - /// The message data. - pub data: Vec, -} - -/// An incoming message. -#[derive(PartialEq, Eq, Decode)] -#[cfg_attr(feature = "std", derive(Debug, Encode))] -pub struct IncomingMessage { - /// The source parachain. - pub source: Id, - /// The data of the message. - pub data: Vec, -} diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index 98861c5afc0b..db9beee34309 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -11,13 +11,13 @@ primitives = { package = "sp-core", git = "https://github.com/paritytech/substra inherents = { package = "sp-inherents", git = "https://github.com/paritytech/substrate", branch = "cumulus-branch", default-features = false } application-crypto = { package = "sp-application-crypto", git = "https://github.com/paritytech/substrate", branch = "cumulus-branch", default-features = false } sp-api = { git = "https://github.com/paritytech/substrate", branch = "cumulus-branch", default-features = false } +sp-runtime-interface = { git = "https://github.com/paritytech/substrate", branch = "cumulus-branch", default-features = false } sp-version = { git = "https://github.com/paritytech/substrate", branch = "cumulus-branch", default-features = false } rstd = { package = "sp-std", git = "https://github.com/paritytech/substrate", branch = "cumulus-branch", default-features = false } runtime_primitives = { package = "sp-runtime", git = "https://github.com/paritytech/substrate", branch = "cumulus-branch", default-features = false } -polkadot-parachain = { path = "../parachain", default-features = false } trie = { package = "sp-trie", git = "https://github.com/paritytech/substrate", branch = "cumulus-branch", default-features = false } bitvec = { version = "0.15.2", default-features = false, features = ["alloc"] } -babe = { package = "pallet-babe", git = "https://github.com/paritytech/substrate", branch = "cumulus-branch", default-features = false } +derive_more = { version = "0.99.2" } [dev-dependencies] sp-serializer = { git = "https://github.com/paritytech/substrate", branch = "cumulus-branch" } @@ -31,11 +31,10 @@ std = [ "inherents/std", "trie/std", "sp-api/std", + "sp-runtime-interface/std", "rstd/std", "sp-version/std", "runtime_primitives/std", "serde", - "polkadot-parachain/std", "bitvec/std", - "babe/std" ] diff --git a/primitives/src/parachain.rs b/primitives/src/parachain.rs index 045f99d62319..faa9f083bbe4 100644 --- a/primitives/src/parachain.rs +++ b/primitives/src/parachain.rs @@ -18,7 +18,7 @@ use rstd::prelude::*; use rstd::cmp::Ordering; -use parity_scale_codec::{Encode, Decode}; +use parity_scale_codec::{Encode, Decode, CompactAs}; use bitvec::vec::BitVec; use super::{Hash, Balance}; @@ -27,17 +27,13 @@ use serde::{Serialize, Deserialize}; #[cfg(feature = "std")] use primitives::bytes; -use primitives::RuntimeDebug; +use primitives::{RuntimeDebug, TypeId}; use inherents::InherentIdentifier; use application_crypto::KeyTypeId; #[cfg(feature = "std")] use trie::TrieConfiguration; -pub use polkadot_parachain::{ - Id, ParachainDispatchOrigin, LOWEST_USER_ID, UpwardMessage, -}; - /// The key type ID for a collator key. pub const COLLATOR_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"coll"); @@ -465,6 +461,157 @@ pub mod id { pub const PARACHAIN_HOST: ApiId = *b"parahost"; } +/// Unique identifier of a parachain. +#[derive( + Clone, CompactAs, Copy, Decode, Default, Encode, Eq, + Hash, Ord, PartialEq, PartialOrd, RuntimeDebug, +)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize, derive_more::Display))] +pub struct Id(u32); + +impl TypeId for Id { + const TYPE_ID: [u8; 4] = *b"para"; +} + +const USER_INDEX_START: u32 = 1000; + +/// The ID of the first user (non-system) parachain. +pub const LOWEST_USER_ID: Id = Id(USER_INDEX_START); + +impl Id { + /// Create an `Id`. + pub const fn new(id: u32) -> Self { + Self(id) + } + + /// Returns `true` if this parachain runs with system-level privileges. + pub fn is_system(&self) -> bool { self.0 < USER_INDEX_START } +} + +impl rstd::ops::Add for Id { + type Output = Self; + + fn add(self, other: u32) -> Self { + Self(self.0 + other) + } +} + +/// Type for determining the active set of parachains. +pub trait ActiveThreads { + /// Return the current ordered set of `Id`s of active parathreads. + fn active_threads() -> Vec; +} + +impl From for u32 { + fn from(x: Id) -> Self { x.0 } +} + +impl From for Id { + fn from(x: u32) -> Self { Id(x) } +} + +// TODO: Remove all of this, move sp-runtime::AccountIdConversion to own crate and and use that. +// #360 +struct TrailingZeroInput<'a>(&'a [u8]); +impl<'a> parity_scale_codec::Input for TrailingZeroInput<'a> { + fn remaining_len(&mut self) -> Result, parity_scale_codec::Error> { + Ok(None) + } + + fn read(&mut self, into: &mut [u8]) -> Result<(), parity_scale_codec::Error> { + let len = into.len().min(self.0.len()); + into[..len].copy_from_slice(&self.0[..len]); + for i in &mut into[len..] { + *i = 0; + } + self.0 = &self.0[len..]; + Ok(()) + } +} + +/// This type can be converted into and possibly from an AccountId (which itself is generic). +pub trait AccountIdConversion: Sized { + /// Convert into an account ID. This is infallible. + fn into_account(&self) -> AccountId; + + /// Try to convert an account ID into this type. Might not succeed. + fn try_from_account(a: &AccountId) -> Option; +} + +/// Format is b"para" ++ encode(parachain ID) ++ 00.... where 00... is indefinite trailing +/// zeroes to fill AccountId. +impl AccountIdConversion for Id { + fn into_account(&self) -> T { + (b"para", self).using_encoded(|b| + T::decode(&mut TrailingZeroInput(b)) + ).unwrap_or_default() + } + + fn try_from_account(x: &T) -> Option { + x.using_encoded(|d| { + if &d[0..4] != b"para" { return None } + let mut cursor = &d[4..]; + let result = Decode::decode(&mut cursor).ok()?; + if cursor.iter().all(|x| *x == 0) { + Some(result) + } else { + None + } + }) + } +} + + +/// Which origin a parachain's message to the relay chain should be dispatched from. +#[derive(Clone, PartialEq, Eq, Encode, Decode)] +#[cfg_attr(feature = "std", derive(Debug))] +#[repr(u8)] +pub enum ParachainDispatchOrigin { + /// As a simple `Origin::Signed`, using `ParaId::account_id` as its value. This is good when + /// interacting with standard modules such as `balances`. + Signed, + /// As the special `Origin::Parachain(ParaId)`. This is good when interacting with parachain- + /// aware modules which need to succinctly verify that the origin is a parachain. + Parachain, + /// As the simple, superuser `Origin::Root`. This can only be done on specially permissioned + /// parachains. + Root, +} + +impl rstd::convert::TryFrom for ParachainDispatchOrigin { + type Error = (); + fn try_from(x: u8) -> core::result::Result { + const SIGNED: u8 = ParachainDispatchOrigin::Signed as u8; + const PARACHAIN: u8 = ParachainDispatchOrigin::Parachain as u8; + Ok(match x { + SIGNED => ParachainDispatchOrigin::Signed, + PARACHAIN => ParachainDispatchOrigin::Parachain, + _ => return Err(()), + }) + } +} + +/// A message from a parachain to its Relay Chain. +#[derive(Clone, PartialEq, Eq, Encode, Decode, sp_runtime_interface::pass_by::PassByCodec)] +#[cfg_attr(feature = "std", derive(Debug))] +pub struct UpwardMessage { + /// The origin for the message to be sent from. + pub origin: ParachainDispatchOrigin, + /// The message data. + pub data: Vec, +} + +/// An incoming message. +#[derive(PartialEq, Eq, Decode)] +#[cfg_attr(feature = "std", derive(Debug, Encode))] +pub struct IncomingMessage { + /// The source parachain. + pub source: Id, + /// The data of the message. + pub data: Vec, +} + + #[cfg(test)] mod tests { use super::*; From 649fbe4d213cdd7722eab98ea070c55e9f7231b8 Mon Sep 17 00:00:00 2001 From: Peter Goodspeed-Niklaus Date: Thu, 5 Mar 2020 11:18:46 +0100 Subject: [PATCH 2/4] WIP: add get_current_relay_block function args to one path back toward relay chain The parachain validation logic trends heavily toward functions, not structs with methods. This is probably a good thing for efficiency, but does make it harder to incorporate an external piece of state like the current relay chain block number: we have to change several functions signatures and their call sites, not just add a field to a struct. This commit partially traces back one of the chains of compilation errors resulting from missing function parameters, adding parameters to parent functions appropriately. At `validation::collation::collation_fetch`, the parameters change from type `BlockNumber` to type `F: Fn() -> BlockNumber`, because that loop looks like a place where the relay chain might potentially change during execution. Unfortunately, this doesn't work as-is right now, because within `validation::validation_service::launch_work`, we get errors that `get_current_relay_block` may not live long enough. The compiler suggests requiring a `'static` lifetime, which feels like a strategy which won't work unless the struct where the relay chain block number is actually stored is also `'static`. Adding a `'a` lifetime tied to `&'a self` doesn't work either. It looks like the restriction comes from `futures::task::Spawn`, whose future must apparently conform to `'static`. We could just pass the current block number all the way from the top of the function chain, but it's not yet obvious how these functions are called by the relay chain, and at what points the current block might change during execution. Therefore, questions: - Can we assume that the relay chain current block will not change during execution of this function chain? If yes, we can just pass the block number, which is `Copy` and therefore in `'static`. - If no, is there a reasonable way to get a `'static` function from the relay chain so we can still use this strategy to get the current relay block number? - If no, how should we propagate this data? Channels maybe? - If we retain the closure strategy, is it a problem to call the non-async function `get_current_relay_block` within `async fn collation_fetch`? Given that async closures are not yet stable, do we have the option not to? --- validation/src/collation.rs | 11 +++++++++-- validation/src/validation_service/mod.rs | 11 ++++++++--- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/validation/src/collation.rs b/validation/src/collation.rs index 6812dda5862c..204e4643c8a7 100644 --- a/validation/src/collation.rs +++ b/validation/src/collation.rs @@ -22,7 +22,7 @@ use std::sync::Arc; use polkadot_primitives::{ - BlakeTwo256, Block, Hash, HashT, BlockId, Balance, + BlakeTwo256, Block, Hash, HashT, BlockId, Balance, BlockNumber, parachain::{ CollatorId, CandidateReceipt, CollationInfo, ParachainHost, Id as ParaId, Collation, FeeSchedule, ErasureChunk, @@ -65,9 +65,10 @@ pub trait Collators: Clone { } /// A future which resolves when a collation is available. -pub async fn collation_fetch( +pub async fn collation_fetch( parachain: ParaId, relay_parent_hash: Hash, + get_current_relay_block: GCRB, collators: C, client: Arc

, max_block_data_size: Option, @@ -77,6 +78,7 @@ pub async fn collation_fetch( C: Collators + Unpin, P: ProvideRuntimeApi, ::Collation: Unpin, + GCRB: Fn() -> BlockNumber, { let relay_parent = BlockId::hash(relay_parent_hash); @@ -87,6 +89,7 @@ pub async fn collation_fetch( let res = validate_collation( &*client, &relay_parent, + get_current_relay_block(), &collation, max_block_data_size, ); @@ -281,6 +284,7 @@ pub fn validate_chunk( fn do_validation

( client: &P, relay_parent: &BlockId, + current_relay_block: BlockNumber, pov_block: &PoVBlock, para_id: ParaId, max_block_data_size: Option, @@ -311,6 +315,7 @@ fn do_validation

( let params = ValidationParams { parent_head: chain_status.head_data.0.clone(), block_data: pov_block.block_data.0.clone(), + current_relay_block, }; let ext = Externalities::new(chain_status.balance, chain_status.fee_schedule); @@ -406,6 +411,7 @@ pub fn validate_receipt

( let (parent_head, _fees) = do_validation( client, relay_parent, + receipt.current_relay_block, pov_block, receipt.parachain_index, max_block_data_size, @@ -451,6 +457,7 @@ pub fn validate_receipt

( pub fn validate_collation

( client: &P, relay_parent: &BlockId, + current_relay_block: BlockNumber, collation: &Collation, max_block_data_size: Option, ) -> Result<(HeadData, Balance), Error> where diff --git a/validation/src/validation_service/mod.rs b/validation/src/validation_service/mod.rs index 3c4f75f5c990..7cd3fcf51458 100644 --- a/validation/src/validation_service/mod.rs +++ b/validation/src/validation_service/mod.rs @@ -34,7 +34,7 @@ use sp_blockchain::HeaderBackend; use block_builder::BlockBuilderApi; use consensus::SelectChain; use futures::{future::ready, prelude::*, task::{Spawn, SpawnExt}}; -use polkadot_primitives::{Block, Hash, BlockId}; +use polkadot_primitives::{Block, Hash, BlockId, BlockNumber}; use polkadot_primitives::parachain::{ Chain, ParachainHost, Id as ParaId, ValidatorIndex, ValidatorId, ValidatorPair, }; @@ -368,7 +368,7 @@ impl ParachainValidationInstances where } // launch parachain work asynchronously. - fn launch_work( + fn launch_work( &self, relay_parent: Hash, validation_para: ParaId, @@ -376,7 +376,11 @@ impl ParachainValidationInstances where max_block_data_size: Option, authorities_num: usize, local_id: ValidatorIndex, - ) { + get_current_relay_block: GCRB, + ) + where + GCRB: Fn() -> BlockNumber + Send, + { let (collators, client) = (self.collators.clone(), self.client.clone()); let availability_store = self.availability_store.clone(); @@ -385,6 +389,7 @@ impl ParachainValidationInstances where let collation_work = crate::collation::collation_fetch( validation_para, relay_parent, + get_current_relay_block, collators, client.clone(), max_block_data_size, From f81b1f6aeaa1bd9fdf0287fe2c73371fa885ebc3 Mon Sep 17 00:00:00 2001 From: Peter Goodspeed-Niklaus Date: Thu, 5 Mar 2020 13:54:25 +0100 Subject: [PATCH 3/4] Get current relay block head without messing with signatures Turns out we already had a client object available which implemented the necessary trait; the difficulty was just that I didn't know that a. the trait existed, or that b. the client in our possession implemented that trait. This does make things much neater; it just means propagating the trait bound backwards as implemented here. --- network/src/legacy/router.rs | 2 ++ network/src/legacy/validation.rs | 3 ++- network/src/protocol.rs | 7 ++++--- validation/src/collation.rs | 21 ++++++++------------- validation/src/shared_table/mod.rs | 3 ++- validation/src/validation_service/mod.rs | 10 +++------- 6 files changed, 21 insertions(+), 25 deletions(-) diff --git a/network/src/legacy/router.rs b/network/src/legacy/router.rs index 4a969a4870e6..d4feaca2dff8 100644 --- a/network/src/legacy/router.rs +++ b/network/src/legacy/router.rs @@ -32,6 +32,7 @@ use polkadot_primitives::parachain::{ CandidateReceipt, ParachainHost, ValidatorIndex, Collation, PoVBlock, ErasureChunk, }; use sp_api::ProvideRuntimeApi; +use sp_blockchain::HeaderBackend; use futures::prelude::*; use futures::{task::SpawnExt, future::ready}; @@ -133,6 +134,7 @@ impl Clone for Router { } impl + Send + Sync + 'static, T> Router where + P: HeaderBackend, P::Api: ParachainHost, T: Clone + Executor + Send + 'static, { diff --git a/network/src/legacy/validation.rs b/network/src/legacy/validation.rs index c64f21428d41..0901b016df90 100644 --- a/network/src/legacy/validation.rs +++ b/network/src/legacy/validation.rs @@ -29,6 +29,7 @@ use polkadot_primitives::parachain::{ ValidatorId, PoVBlock, }; use sp_api::ProvideRuntimeApi; +use sp_blockchain::HeaderBackend; use futures::prelude::*; use futures::task::SpawnExt; @@ -167,7 +168,7 @@ impl ValidationNetwork { /// A long-lived network which can create parachain statement routing processes on demand. impl ParachainNetwork for ValidationNetwork where - P: ProvideRuntimeApi + Send + Sync + 'static, + P: ProvideRuntimeApi + HeaderBackend + Send + Sync + 'static, P::Api: ParachainHost, T: Clone + Executor + Send + Sync + 'static, { diff --git a/network/src/protocol.rs b/network/src/protocol.rs index acdee6830771..9fdb73f30cef 100644 --- a/network/src/protocol.rs +++ b/network/src/protocol.rs @@ -40,6 +40,7 @@ use polkadot_validation::{ }; use sc_network::{config::Roles, Event, PeerId}; use sp_api::ProvideRuntimeApi; +use sp_blockchain::HeaderBackend; use std::collections::HashMap; use std::pin::Pin; @@ -110,7 +111,7 @@ pub fn start( executor: SP, ) -> Result where C: ChainContext + 'static, - Api: ProvideRuntimeApi + Send + Sync + 'static, + Api: ProvideRuntimeApi + HeaderBackend + Send + Sync + 'static, Api::Api: ParachainHost, SP: Spawn + Clone + Send + 'static, { @@ -566,7 +567,7 @@ async fn worker_loop( mut receiver: mpsc::Receiver, executor: Sp, ) where - Api: ProvideRuntimeApi + Send + Sync + 'static, + Api: ProvideRuntimeApi + HeaderBackend + Send + Sync + 'static, Api::Api: ParachainHost, Sp: Spawn + Clone + Send + 'static, { @@ -690,7 +691,7 @@ async fn statement_import_loop( mut exit: exit_future::Exit, executor: impl Spawn, ) where - Api: ProvideRuntimeApi + Send + Sync + 'static, + Api: ProvideRuntimeApi + HeaderBackend + Send + Sync + 'static, Api::Api: ParachainHost, { let topic = crate::legacy::router::attestation_topic(relay_parent); diff --git a/validation/src/collation.rs b/validation/src/collation.rs index 204e4643c8a7..0ee2d7606716 100644 --- a/validation/src/collation.rs +++ b/validation/src/collation.rs @@ -22,7 +22,7 @@ use std::sync::Arc; use polkadot_primitives::{ - BlakeTwo256, Block, Hash, HashT, BlockId, Balance, BlockNumber, + BlakeTwo256, Block, Hash, HashT, BlockId, Balance, parachain::{ CollatorId, CandidateReceipt, CollationInfo, ParachainHost, Id as ParaId, Collation, FeeSchedule, ErasureChunk, @@ -31,6 +31,7 @@ use polkadot_primitives::{ }; use polkadot_erasure_coding as erasure; use sp_api::ProvideRuntimeApi; +use sp_blockchain::HeaderBackend; use parachain::{ wasm_executor::{self, ExecutionMode}, UpwardMessage, }; @@ -65,10 +66,9 @@ pub trait Collators: Clone { } /// A future which resolves when a collation is available. -pub async fn collation_fetch( +pub async fn collation_fetch( parachain: ParaId, relay_parent_hash: Hash, - get_current_relay_block: GCRB, collators: C, client: Arc

, max_block_data_size: Option, @@ -76,9 +76,8 @@ pub async fn collation_fetch( where P::Api: ParachainHost, C: Collators + Unpin, - P: ProvideRuntimeApi, + P: ProvideRuntimeApi + HeaderBackend, ::Collation: Unpin, - GCRB: Fn() -> BlockNumber, { let relay_parent = BlockId::hash(relay_parent_hash); @@ -89,7 +88,6 @@ pub async fn collation_fetch( let res = validate_collation( &*client, &relay_parent, - get_current_relay_block(), &collation, max_block_data_size, ); @@ -284,7 +282,6 @@ pub fn validate_chunk( fn do_validation

( client: &P, relay_parent: &BlockId, - current_relay_block: BlockNumber, pov_block: &PoVBlock, para_id: ParaId, max_block_data_size: Option, @@ -292,7 +289,7 @@ fn do_validation

( head_data: &HeadData, upward_messages: &Vec, ) -> Result<(HeadData, Balance), Error> where - P: ProvideRuntimeApi, + P: ProvideRuntimeApi + HeaderBackend, P::Api: ParachainHost, { use parachain::ValidationParams; @@ -315,7 +312,7 @@ fn do_validation

( let params = ValidationParams { parent_head: chain_status.head_data.0.clone(), block_data: pov_block.block_data.0.clone(), - current_relay_block, + current_relay_block: client.info().best_number, }; let ext = Externalities::new(chain_status.balance, chain_status.fee_schedule); @@ -405,13 +402,12 @@ pub fn validate_receipt

( receipt: &CandidateReceipt, max_block_data_size: Option, ) -> Result, Error> where - P: ProvideRuntimeApi, + P: ProvideRuntimeApi + HeaderBackend, P::Api: ParachainHost, { let (parent_head, _fees) = do_validation( client, relay_parent, - receipt.current_relay_block, pov_block, receipt.parachain_index, max_block_data_size, @@ -457,11 +453,10 @@ pub fn validate_receipt

( pub fn validate_collation

( client: &P, relay_parent: &BlockId, - current_relay_block: BlockNumber, collation: &Collation, max_block_data_size: Option, ) -> Result<(HeadData, Balance), Error> where - P: ProvideRuntimeApi, + P: ProvideRuntimeApi + HeaderBackend, P::Api: ParachainHost, { let para_id = collation.info.parachain_index; diff --git a/validation/src/shared_table/mod.rs b/validation/src/shared_table/mod.rs index 77ab0a78ac7f..9e4538d16d63 100644 --- a/validation/src/shared_table/mod.rs +++ b/validation/src/shared_table/mod.rs @@ -38,6 +38,7 @@ use super::{GroupInfo, TableRouter}; use self::includable::IncludabilitySender; use primitives::Pair; use sp_api::ProvideRuntimeApi; +use sp_blockchain::HeaderBackend; mod includable; @@ -267,7 +268,7 @@ impl ParachainWork { impl Send + FnMut(&BlockId, &PoVBlock, &CandidateReceipt) -> Result + Unpin, > where - P: Send + Sync + 'static, + P: HeaderBackend + Send + Sync + 'static, P::Api: ParachainHost, { let max_block_data_size = self.max_block_data_size; diff --git a/validation/src/validation_service/mod.rs b/validation/src/validation_service/mod.rs index 7cd3fcf51458..5df3d8dede75 100644 --- a/validation/src/validation_service/mod.rs +++ b/validation/src/validation_service/mod.rs @@ -34,7 +34,7 @@ use sp_blockchain::HeaderBackend; use block_builder::BlockBuilderApi; use consensus::SelectChain; use futures::{future::ready, prelude::*, task::{Spawn, SpawnExt}}; -use polkadot_primitives::{Block, Hash, BlockId, BlockNumber}; +use polkadot_primitives::{Block, Hash, BlockId}; use polkadot_primitives::parachain::{ Chain, ParachainHost, Id as ParaId, ValidatorIndex, ValidatorId, ValidatorPair, }; @@ -368,7 +368,7 @@ impl ParachainValidationInstances where } // launch parachain work asynchronously. - fn launch_work( + fn launch_work( &self, relay_parent: Hash, validation_para: ParaId, @@ -376,11 +376,8 @@ impl ParachainValidationInstances where max_block_data_size: Option, authorities_num: usize, local_id: ValidatorIndex, - get_current_relay_block: GCRB, ) - where - GCRB: Fn() -> BlockNumber + Send, - { + where { let (collators, client) = (self.collators.clone(), self.client.clone()); let availability_store = self.availability_store.clone(); @@ -389,7 +386,6 @@ impl ParachainValidationInstances where let collation_work = crate::collation::collation_fetch( validation_para, relay_parent, - get_current_relay_block, collators, client.clone(), max_block_data_size, From 7cf90473cab41a09313b21d2bbb26249b4f7dc6a Mon Sep 17 00:00:00 2001 From: Peter Goodspeed-Niklaus Date: Fri, 6 Mar 2020 09:37:31 +0100 Subject: [PATCH 4/4] apply quick review comments --- parachain/src/lib.rs | 1 - validation/src/validation_service/mod.rs | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/parachain/src/lib.rs b/parachain/src/lib.rs index 5367a01c0a1c..215e60c290bd 100644 --- a/parachain/src/lib.rs +++ b/parachain/src/lib.rs @@ -55,7 +55,6 @@ use codec::{Encode, Decode}; #[cfg(all(not(feature = "std"), feature = "wasm-api"))] pub use wasm_api::*; -#[deprecated(note="moved to primitives package")] pub use polkadot_primitives::{BlockNumber, parachain::{ AccountIdConversion, Id, diff --git a/validation/src/validation_service/mod.rs b/validation/src/validation_service/mod.rs index 5df3d8dede75..3c4f75f5c990 100644 --- a/validation/src/validation_service/mod.rs +++ b/validation/src/validation_service/mod.rs @@ -376,8 +376,7 @@ impl ParachainValidationInstances where max_block_data_size: Option, authorities_num: usize, local_id: ValidatorIndex, - ) - where { + ) { let (collators, client) = (self.collators.clone(), self.client.clone()); let availability_store = self.availability_store.clone();