Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Add current relay block to ValidationParams #879

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions network/src/legacy/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -133,6 +134,7 @@ impl<P, T: Clone> Clone for Router<P, T> {
}

impl<P: ProvideRuntimeApi<Block> + Send + Sync + 'static, T> Router<P, T> where
P: HeaderBackend<Block>,
P::Api: ParachainHost<Block, Error = sp_blockchain::Error>,
T: Clone + Executor + Send + 'static,
{
Expand Down
3 changes: 2 additions & 1 deletion network/src/legacy/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -167,7 +168,7 @@ impl<P, T> ValidationNetwork<P, T> {

/// A long-lived network which can create parachain statement routing processes on demand.
impl<P, T> ParachainNetwork for ValidationNetwork<P, T> where
P: ProvideRuntimeApi<Block> + Send + Sync + 'static,
P: ProvideRuntimeApi<Block> + HeaderBackend<Block> + Send + Sync + 'static,
P::Api: ParachainHost<Block, Error = sp_blockchain::Error>,
T: Clone + Executor + Send + Sync + 'static,
{
Expand Down
7 changes: 4 additions & 3 deletions network/src/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -110,7 +111,7 @@ pub fn start<C, Api, SP>(
executor: SP,
) -> Result<Service, futures::task::SpawnError> where
C: ChainContext + 'static,
Api: ProvideRuntimeApi<Block> + Send + Sync + 'static,
Api: ProvideRuntimeApi<Block> + HeaderBackend<Block> + Send + Sync + 'static,
Api::Api: ParachainHost<Block, Error = sp_blockchain::Error>,
SP: Spawn + Clone + Send + 'static,
{
Expand Down Expand Up @@ -566,7 +567,7 @@ async fn worker_loop<Api, Sp>(
mut receiver: mpsc::Receiver<ServiceToWorkerMsg>,
executor: Sp,
) where
Api: ProvideRuntimeApi<Block> + Send + Sync + 'static,
Api: ProvideRuntimeApi<Block> + HeaderBackend<Block> + Send + Sync + 'static,
Api::Api: ParachainHost<Block, Error = sp_blockchain::Error>,
Sp: Spawn + Clone + Send + 'static,
{
Expand Down Expand Up @@ -690,7 +691,7 @@ async fn statement_import_loop<Api>(
mut exit: exit_future::Exit,
executor: impl Spawn,
) where
Api: ProvideRuntimeApi<Block> + Send + Sync + 'static,
Api: ProvideRuntimeApi<Block> + HeaderBackend<Block> + Send + Sync + 'static,
Api::Api: ParachainHost<Block, Error = sp_blockchain::Error>,
{
let topic = crate::legacy::router::attestation_topic(relay_parent);
Expand Down
2 changes: 2 additions & 0 deletions parachain/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we want to bring polkadot-primitives in as a dependency. It depends on substrate primitives crates that we don't want to force all parachains to link to.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The motivation there was to enable the use polkadot_primitives::BlockNumber import. If we replace the block number with the relay chain header, we still have to either use polkadot_primitives::Header, or make the ValidationParams struct generic.

I think you're right: if we have a generic ValidationParams, then we don't need most of the refactor in b4fb14b, which reduces the changes necessary to make all this work.

Copy link
Contributor

@rphmeier rphmeier Mar 9, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really like the idea of ValidationParams being generic, since we know what the types are going to be and are just getting around some type-fu.

I'd suggest instead breaking down polkadot-primitives into multiple crates and bringing in a crate which does not import Substrate WASM externalities.


[target.'cfg(not(target_os = "unknown"))'.dependencies]
shared_memory = { version = "0.10.0", optional = true }
Expand All @@ -44,4 +45,5 @@ std = [
"sp-externalities",
"sc-executor",
"sp-io",
"polkadot-primitives/std",
]
163 changes: 12 additions & 151 deletions parachain/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,20 @@ 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::*;

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)]
Expand All @@ -65,6 +73,8 @@ pub struct ValidationParams {
pub block_data: Vec<u8>,
/// Previous head-data.
pub parent_head: Vec<u8>,
/// Number of the current relay chain block.
pub current_relay_block: BlockNumber,
}

/// The result of parachain validation.
Expand All @@ -75,152 +85,3 @@ pub struct ValidationResult {
/// New head data that should be included in the relay chain state.
pub head_data: Vec<u8>,
}

/// 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<Id>;
}

impl From<Id> for u32 {
fn from(x: Id) -> Self { x.0 }
}

impl From<u32> 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<u32> 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<Option<usize>, 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<AccountId>: 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<Self>;
}

/// Format is b"para" ++ encode(parachain ID) ++ 00.... where 00... is indefinite trailing
/// zeroes to fill AccountId.
impl<T: Encode + Decode + Default> AccountIdConversion<T> 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<Self> {
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<u8> for ParachainDispatchOrigin {
type Error = ();
fn try_from(x: u8) -> core::result::Result<ParachainDispatchOrigin, ()> {
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<u8>,
}

/// 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<u8>,
}
7 changes: 3 additions & 4 deletions primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand All @@ -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"
]
Loading