// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see .
//! Parachain specific networking
//!
//! Provides a custom block announcement implementation for parachains
//! that use the relay chain provided consensus. See [`BlockAnnounceValidator`]
//! and [`WaitToAnnounce`] for more information about this implementation.
use sc_client_api::{Backend, BlockchainEvents};
use sp_api::ProvideRuntimeApi;
use sp_blockchain::HeaderBackend;
use sp_consensus::{
block_validation::{BlockAnnounceValidator as BlockAnnounceValidatorT, Validation},
SyncOracle,
};
use sp_core::traits::SpawnNamed;
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, HashFor, Header as HeaderT},
};
use polkadot_node_primitives::{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,
};
use polkadot_client::ClientHandle;
use codec::{Decode, Encode};
use futures::{
channel::oneshot,
future::{ready, FutureExt},
Future,
};
use std::{convert::TryFrom, fmt, marker::PhantomData, pin::Pin, sync::Arc};
use wait_on_relay_chain_block::WaitOnRelayChainBlock;
#[cfg(test)]
mod tests;
mod wait_on_relay_chain_block;
const LOG_TARGET: &str = "sync::cumulus";
type BoxedError = Box;
#[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)
}
}
/// The data that we attach to a block announcement.
///
/// This will be used to prove that a header belongs to a block that is probably being backed by
/// the relay chain.
#[derive(Encode, Decode, Debug)]
pub struct BlockAnnounceData {
receipt: CandidateReceipt,
statement: UncheckedSigned,
}
impl BlockAnnounceData {
/// Validate that the receipt, statement and announced header match.
///
/// This will not check the signature, for this you should use [`BlockAnnounceData::check_signature`].
fn validate(&self, encoded_header: Vec) -> Result<(), Validation> {
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 });
};
if *candidate_hash != self.receipt.hash() {
tracing::debug!(
target: LOG_TARGET,
"Receipt candidate hash doesn't match candidate hash in statement",
);
return Err(Validation::Failure { disconnect: true });
}
if HeadData(encoded_header).hash() != self.receipt.descriptor.para_head {
tracing::debug!(
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 });
}
Ok(())
}
/// Check the signature of the statement.
///
/// Returns an `Err(_)` if it failed.
fn check_signature
(
self,
relay_chain_client: &Arc
,
) -> Result
where
P: ProvideRuntimeApi + Send + Sync + 'static,
P::Api: ParachainHost,
{
let runtime_api = relay_chain_client.runtime_api();
let validator_index = self.statement.unchecked_validator_index();
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)));
}
};
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)));
}
};
let signer = match authorities.get(validator_index.0 as usize) {
Some(r) => r,
None => {
tracing::debug!(
target: LOG_TARGET,
"Block announcement justification signer is a validator index out of bound",
);
return Ok(Validation::Failure { disconnect: true });
}
};
// Check statement is correctly signed.
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 });
}
Ok(Validation::Success { is_new_best: true })
}
}
impl TryFrom<&'_ SignedFullStatement> for BlockAnnounceData {
type Error = ();
fn try_from(stmt: &SignedFullStatement) -> Result {
let receipt = if let Statement::Seconded(receipt) = stmt.payload() {
receipt.to_plain()
} else {
return Err(());
};
Ok(BlockAnnounceData {
receipt,
statement: stmt.convert_payload().into(),
})
}
}
/// Parachain specific block announce validator.
///
/// This block announce validator is required if the parachain is running
/// with the relay chain provided consensus to make sure each node only
/// imports a reasonable number of blocks per round. The relay chain provided
/// consensus doesn't have any authorities and so it could happen that without
/// this special block announce validator a node would need to import *millions*
/// of blocks per round, which is clearly not doable.
///
/// To solve this problem, each block announcement is delayed until a collator
/// has received a [`Statement::Seconded`] for its `PoV`. This message tells the
/// collator that its `PoV` was validated successfully by a parachain validator and
/// that it is very likely that this `PoV` will be included in the relay chain. Every
/// collator that doesn't receive the message for its `PoV` will not announce its block.
/// For more information on the block announcement, see [`WaitToAnnounce`].
///
/// For each block announcement that is received, the generic block announcement validation
/// will call this validator and provides the extra data that was attached to the announcement.
/// We call this extra data `justification`.
/// It is expected that the attached data is a SCALE encoded [`BlockAnnounceData`]. The
/// statement is checked to be a [`CompactStatement::Candidate`] and that it is signed by an active
/// parachain validator.
///
/// If no justification was provided we check if the block announcement is at the tip of the known
/// chain. If it is at the tip, it is required to provide a justification or otherwise we reject
/// it. However, if the announcement is for a block below the tip the announcement is accepted
/// as it probably comes from a node that is currently syncing the chain.
pub struct BlockAnnounceValidator {
phantom: PhantomData,
relay_chain_client: Arc,
relay_chain_backend: Arc,
para_id: ParaId,
relay_chain_sync_oracle: Box,
wait_on_relay_chain_block: WaitOnRelayChainBlock,
}
impl BlockAnnounceValidator {
/// Create a new [`BlockAnnounceValidator`].
pub fn new(
relay_chain_client: Arc,
para_id: ParaId,
relay_chain_sync_oracle: Box,
relay_chain_backend: Arc,
relay_chain_blockchain_events: Arc,
) -> Self {
Self {
phantom: Default::default(),
relay_chain_client,
para_id,
relay_chain_sync_oracle,
relay_chain_backend: relay_chain_backend.clone(),
wait_on_relay_chain_block: WaitOnRelayChainBlock::new(
relay_chain_backend,
relay_chain_blockchain_events,
),
}
}
}
impl BlockAnnounceValidator
where
R: ProvideRuntimeApi + Send + Sync + 'static,
R::Api: ParachainHost,
B: Backend + 'static,
// Rust bug: https://github.com/rust-lang/rust/issues/24159
sc_client_api::StateBackendFor: sc_client_api::StateBackend>,
{
/// Get the included block of the given parachain in the relay chain.
fn included_block(
relay_chain_client: &R,
block_id: &BlockId,
para_id: ParaId,
) -> Result {
let validation_data = relay_chain_client
.runtime_api()
.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<_>
})?;
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<_>
})?;
Ok(para_head)
}
/// Get the backed block hash of the given parachain in the relay chain.
fn backed_block_hash(
relay_chain_client: &R,
block_id: &BlockId,
para_id: ParaId,
) -> Result