feat: Rebrand Polkadot/Substrate references to PezkuwiChain

This commit systematically rebrands various references from Parity Technologies'
Polkadot/Substrate ecosystem to PezkuwiChain within the kurdistan-sdk.

Key changes include:
- Updated external repository URLs (zombienet-sdk, parity-db, parity-scale-codec, wasm-instrument) to point to pezkuwichain forks.
- Modified internal documentation and code comments to reflect PezkuwiChain naming and structure.
- Replaced direct references to  with  or specific paths within the  for XCM, Pezkuwi, and other modules.
- Cleaned up deprecated  issue and PR references in various  and  files, particularly in  and  modules.
- Adjusted image and logo URLs in documentation to point to PezkuwiChain assets.
- Removed or rephrased comments related to external Polkadot/Substrate PRs and issues.

This is a significant step towards fully customizing the SDK for the PezkuwiChain ecosystem.
This commit is contained in:
2025-12-14 00:04:10 +03:00
parent e4778b4576
commit 379cb741ed
9082 changed files with 997824 additions and 997542 deletions
+543
View File
@@ -0,0 +1,543 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// Pezcumulus 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.
// Pezcumulus 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 Pezcumulus. If not, see <https://www.gnu.org/licenses/>.
//! Teyrchain specific networking
//!
//! Provides a custom block announcement implementation for teyrchains
//! that use the relay chain provided consensus. See [`RequireSecondedInBlockAnnounce`]
//! and [`WaitToAnnounce`] for more information about this implementation.
use pezsp_api::RuntimeApiInfo;
use pezsp_consensus::block_validation::{
BlockAnnounceValidator as BlockAnnounceValidatorT, Validation,
};
use pezsp_core::traits::SpawnNamed;
use pezsp_runtime::traits::{Block as BlockT, Header as HeaderT};
use cumulus_relay_chain_interface::RelayChainInterface;
use pezkuwi_node_primitives::{CollationSecondedSignal, Statement};
use pezkuwi_node_subsystem::messages::RuntimeApiRequest;
use pezkuwi_primitives::{
CandidateReceiptV2 as CandidateReceipt, CompactStatement, Hash as PHash, Id as ParaId,
OccupiedCoreAssumption, SigningContext, UncheckedSigned,
};
use pezkuwi_teyrchain_primitives::primitives::HeadData;
use codec::{Decode, DecodeAll, Encode};
use futures::{channel::oneshot, future::FutureExt, Future};
use std::{fmt, marker::PhantomData, pin::Pin, sync::Arc};
#[cfg(test)]
mod tests;
const LOG_TARGET: &str = "sync::pezcumulus";
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)
}
}
/// 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, Debug)]
pub struct BlockAnnounceData {
/// The receipt identifying the candidate.
receipt: CandidateReceipt,
/// The seconded statement issued by a relay chain validator that approves the candidate.
statement: UncheckedSigned<CompactStatement>,
/// The relay parent that was used as context to sign the [`Self::statement`].
relay_parent: PHash,
}
impl Decode for BlockAnnounceData {
fn decode<I: codec::Input>(input: &mut I) -> Result<Self, codec::Error> {
let receipt = CandidateReceipt::decode(input)?;
let statement = UncheckedSigned::<CompactStatement>::decode(input)?;
let relay_parent = match PHash::decode(input) {
Ok(p) => p,
// For being backwards compatible, we support missing relay-chain parent.
Err(_) => receipt.descriptor.relay_parent(),
};
Ok(Self { receipt, statement, relay_parent })
}
}
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<u8>) -> 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.
async fn check_signature<RCInterface>(
self,
relay_chain_client: &RCInterface,
) -> Result<Validation, BlockAnnounceError>
where
RCInterface: RelayChainInterface + 'static,
{
let validator_index = self.statement.unchecked_validator_index();
let session_index =
match relay_chain_client.session_index_for_child(self.relay_parent).await {
Ok(r) => r,
Err(e) => return Err(BlockAnnounceError(format!("{:?}", e))),
};
let signing_context = SigningContext { parent_hash: self.relay_parent, session_index };
// Check that the signer is a legit validator.
let authorities = match relay_chain_client.validators(self.relay_parent).await {
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<&'_ CollationSecondedSignal> for BlockAnnounceData {
type Error = ();
fn try_from(signal: &CollationSecondedSignal) -> Result<BlockAnnounceData, ()> {
let receipt = if let Statement::Seconded(receipt) = signal.statement.payload() {
receipt.to_plain()
} else {
return Err(());
};
Ok(BlockAnnounceData {
receipt,
statement: signal.statement.convert_payload().into(),
relay_parent: signal.relay_parent,
})
}
}
/// A type alias for the [`RequireSecondedInBlockAnnounce`] validator.
#[deprecated = "This has been renamed to RequireSecondedInBlockAnnounce"]
pub type BlockAnnounceValidator<Block, RCInterface> =
RequireSecondedInBlockAnnounce<Block, RCInterface>;
/// Teyrchain specific block announce validator.
///
/// This is not required when the collation mechanism itself is sybil-resistant, as it is a spam
/// protection mechanism used to prevent nodes from dealing with unbounded numbers of blocks. For
/// sybil-resistant collation mechanisms, this will only slow things down.
///
/// This block announce validator is required if the teyrchain 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 teyrchain 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::Seconded`] and that it is signed by an active
/// teyrchain 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.
#[derive(Clone)]
pub struct RequireSecondedInBlockAnnounce<Block, RCInterface> {
phantom: PhantomData<Block>,
relay_chain_interface: RCInterface,
para_id: ParaId,
}
impl<Block, RCInterface> RequireSecondedInBlockAnnounce<Block, RCInterface>
where
RCInterface: Clone,
{
/// Create a new [`RequireSecondedInBlockAnnounce`].
pub fn new(relay_chain_interface: RCInterface, para_id: ParaId) -> Self {
Self { phantom: Default::default(), relay_chain_interface, para_id }
}
}
impl<Block: BlockT, RCInterface> RequireSecondedInBlockAnnounce<Block, RCInterface>
where
RCInterface: RelayChainInterface + Clone,
{
/// Get the included block of the given teyrchain in the relay chain.
async fn included_block(
relay_chain_interface: &RCInterface,
hash: PHash,
para_id: ParaId,
) -> Result<Block::Header, BoxedError> {
let validation_data = relay_chain_interface
.persisted_validation_data(hash, para_id, OccupiedCoreAssumption::TimedOut)
.await
.map_err(|e| Box::new(BlockAnnounceError(format!("{:?}", e))) as Box<_>)?
.ok_or_else(|| {
Box::new(BlockAnnounceError("Could not find teyrchain 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 teyrchain head: {:?}", e)))
as Box<_>
})?;
Ok(para_head)
}
/// Get the backed block hashes of the given teyrchain in the relay chain.
async fn backed_block_hashes(
relay_chain_interface: &RCInterface,
hash: PHash,
para_id: ParaId,
) -> Result<impl Iterator<Item = PHash>, BoxedError> {
let runtime_api_version = relay_chain_interface
.version(hash)
.await
.map_err(|e| Box::new(BlockAnnounceError(format!("{:?}", e))) as Box<_>)?;
let teyrchain_host_runtime_api_version =
runtime_api_version
.api_version(
&<dyn pezkuwi_primitives::runtime_api::TeyrchainHost<
pezkuwi_primitives::Block,
>>::ID,
)
.unwrap_or_default();
// If the relay chain runtime does not support the new runtime API, fallback to the
// deprecated one.
let candidate_receipts = if teyrchain_host_runtime_api_version <
RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT
{
#[allow(deprecated)]
relay_chain_interface
.candidate_pending_availability(hash, para_id)
.await
.map(|c| c.into_iter().collect::<Vec<_>>())
} else {
relay_chain_interface.candidates_pending_availability(hash, para_id).await
}
.map_err(|e| Box::new(BlockAnnounceError(format!("{:?}", e))) as Box<_>)?;
Ok(candidate_receipts.into_iter().map(|cr| cr.descriptor.para_head()))
}
/// Handle a block announcement with empty data (no statement) attached to it.
async fn handle_empty_block_announce_data(
&self,
header: Block::Header,
) -> Result<Validation, BoxedError> {
let relay_chain_interface = self.relay_chain_interface.clone();
let para_id = self.para_id;
// Check if block is equal or higher than best (this requires a justification)
let relay_chain_best_hash = relay_chain_interface
.best_block_hash()
.await
.map_err(|e| Box::new(e) as Box<_>)?;
let block_number = header.number();
let best_head =
Self::included_block(&relay_chain_interface, relay_chain_best_hash, para_id).await?;
let known_best_number = best_head.number();
if best_head == header {
tracing::debug!(target: LOG_TARGET, "Announced block matches best block.",);
return Ok(Validation::Success { is_new_best: true });
}
let mut backed_blocks =
Self::backed_block_hashes(&relay_chain_interface, relay_chain_best_hash, para_id)
.await?;
let head_hash = HeadData(header.encode()).hash();
if backed_blocks.any(|block_hash| block_hash == head_hash) {
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 {
tracing::debug!(
target: LOG_TARGET,
"Validation failed because a justification is needed if the block at the top of the chain."
);
Ok(Validation::Failure { disconnect: false })
} else {
Ok(Validation::Success { is_new_best: false })
}
}
}
impl<Block: BlockT, RCInterface> BlockAnnounceValidatorT<Block>
for RequireSecondedInBlockAnnounce<Block, RCInterface>
where
RCInterface: RelayChainInterface + Clone + 'static,
{
fn validate(
&mut self,
header: &Block::Header,
data: &[u8],
) -> Pin<Box<dyn Future<Output = Result<Validation, BoxedError>> + Send>> {
let relay_chain_interface = self.relay_chain_interface.clone();
let data = data.to_vec();
let header = header.clone();
let header_encoded = header.encode();
let block_announce_validator = self.clone();
async move {
let relay_chain_is_syncing = relay_chain_interface
.is_major_syncing()
.await
.map_err(
|e| tracing::error!(target: LOG_TARGET, "Unable to determine sync status. {}", e),
)
.unwrap_or(false);
if relay_chain_is_syncing {
return Ok(Validation::Success { is_new_best: false });
}
if data.is_empty() {
return block_announce_validator.handle_empty_block_announce_data(header).await;
}
let block_announce_data = match BlockAnnounceData::decode_all(&mut data.as_slice()) {
Ok(r) => r,
Err(err) =>
return Err(Box::new(BlockAnnounceError(format!(
"Can not decode the `BlockAnnounceData`: {:?}",
err
))) as Box<_>),
};
if let Err(e) = block_announce_data.validate(header_encoded) {
return Ok(e);
}
let relay_parent = block_announce_data.receipt.descriptor.relay_parent();
relay_chain_interface
.wait_for_block(relay_parent)
.await
.map_err(|e| Box::new(BlockAnnounceError(e.to_string())) as Box<_>)?;
block_announce_data
.check_signature(&relay_chain_interface)
.await
.map_err(|e| Box::new(e) as Box<_>)
}
.boxed()
}
}
/// Wait before announcing a block that a candidate message has been received for this block, then
/// add this message as justification for the block announcement.
///
/// This object will spawn a new task every time the method `wait_to_announce` is called and cancel
/// the previous task running.
pub struct WaitToAnnounce<Block: BlockT> {
spawner: Arc<dyn SpawnNamed + Send + Sync>,
announce_block: Arc<dyn Fn(Block::Hash, Option<Vec<u8>>) + Send + Sync>,
}
impl<Block: BlockT> WaitToAnnounce<Block> {
/// Create the `WaitToAnnounce` object
pub fn new(
spawner: Arc<dyn SpawnNamed + Send + Sync>,
announce_block: Arc<dyn Fn(Block::Hash, Option<Vec<u8>>) + Send + Sync>,
) -> WaitToAnnounce<Block> {
WaitToAnnounce { spawner, announce_block }
}
/// Wait for a candidate message for the block, then announce the block. The candidate
/// message will be added as justification to the block announcement.
pub fn wait_to_announce(
&mut self,
block_hash: <Block as BlockT>::Hash,
signed_stmt_recv: oneshot::Receiver<CollationSecondedSignal>,
) {
let announce_block = self.announce_block.clone();
self.spawner.spawn(
"pezcumulus-wait-to-announce",
None,
async move {
tracing::debug!(
target: "pezcumulus-network",
"waiting for announce block in a background task...",
);
wait_to_announce::<Block>(block_hash, announce_block, signed_stmt_recv).await;
tracing::debug!(
target: "pezcumulus-network",
"block announcement finished",
);
}
.boxed(),
);
}
}
async fn wait_to_announce<Block: BlockT>(
block_hash: <Block as BlockT>::Hash,
announce_block: Arc<dyn Fn(Block::Hash, Option<Vec<u8>>) + Send + Sync>,
signed_stmt_recv: oneshot::Receiver<CollationSecondedSignal>,
) {
let signal = match signed_stmt_recv.await {
Ok(s) => s,
Err(_) => {
tracing::debug!(
target: "pezcumulus-network",
block = ?block_hash,
"Wait to announce stopped, because sender was dropped.",
);
return;
},
};
if let Ok(data) = BlockAnnounceData::try_from(&signal) {
announce_block(block_hash, Some(data.encode()));
} else {
tracing::debug!(
target: "pezcumulus-network",
?signal,
block = ?block_hash,
"Received invalid statement while waiting to announce block.",
);
}
}
/// A [`BlockAnnounceValidator`] which accepts all block announcements, as it assumes
/// sybil resistance is handled elsewhere.
#[derive(Debug, Clone)]
pub struct AssumeSybilResistance(bool);
impl AssumeSybilResistance {
/// Instantiate this block announcement validator while permissively allowing (but ignoring)
/// announcements which come tagged with seconded messages.
///
/// This is useful for backwards compatibility when upgrading nodes: old nodes will continue
/// to broadcast announcements with seconded messages, so these announcements shouldn't be
/// rejected and the peers not punished.
pub fn allow_seconded_messages() -> Self {
AssumeSybilResistance(true)
}
/// Instantiate this block announcement validator while rejecting announcements that come with
/// data.
pub fn reject_seconded_messages() -> Self {
AssumeSybilResistance(false)
}
}
impl<Block: BlockT> BlockAnnounceValidatorT<Block> for AssumeSybilResistance {
fn validate(
&mut self,
_header: &Block::Header,
data: &[u8],
) -> Pin<Box<dyn Future<Output = Result<Validation, BoxedError>> + Send>> {
let allow_seconded_messages = self.0;
let data = data.to_vec();
async move {
Ok(if data.is_empty() {
Validation::Success { is_new_best: false }
} else if !allow_seconded_messages {
Validation::Failure { disconnect: false }
} else {
match BlockAnnounceData::decode_all(&mut data.as_slice()) {
Ok(_) => Validation::Success { is_new_best: false },
Err(_) => Validation::Failure { disconnect: true },
}
})
}
.boxed()
}
}
+689
View File
@@ -0,0 +1,689 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// Pezcumulus 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.
// Pezcumulus 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 Pezcumulus. If not, see <https://www.gnu.org/licenses/>.
use super::*;
use async_trait::async_trait;
use cumulus_primitives_core::relay_chain::{BlockId, CoreIndex};
use cumulus_relay_chain_inprocess_interface::{check_block_in_chain, BlockCheckStatus};
use cumulus_relay_chain_interface::{
OverseerHandle, PHeader, ParaId, RelayChainError, RelayChainResult,
};
use cumulus_test_service::runtime::{Block, Hash, Header};
use futures::{executor::block_on, poll, task::Poll, FutureExt, Stream, StreamExt};
use parking_lot::Mutex;
use pezkuwi_node_primitives::{SignedFullStatement, Statement};
use pezkuwi_primitives::{
BlockNumber, CandidateCommitments, CandidateDescriptorV2, CandidateEvent, CollatorPair,
CommittedCandidateReceiptV2, CoreState, Hash as PHash, HeadData, InboundDownwardMessage,
InboundHrmpMessage, OccupiedCoreAssumption, PersistedValidationData, SessionIndex,
SigningContext, ValidationCodeHash, ValidatorId,
};
use pezkuwi_primitives_test_helpers::{CandidateDescriptor, CommittedCandidateReceipt};
use pezkuwi_test_client::{
Client as PClient, ClientBlockImportExt, DefaultTestClientBuilderExt, FullBackend as PBackend,
InitPezkuwiBlockBuilder, TestClientBuilder, TestClientBuilderExt,
};
use rstest::rstest;
use pezsc_client_api::{Backend, BlockchainEvents};
use pezsp_blockchain::HeaderBackend;
use pezsp_consensus::BlockOrigin;
use pezsp_core::{Pair, H256};
use pezsp_keyring::Sr25519Keyring;
use pezsp_keystore::{testing::MemoryKeystore, Keystore, KeystorePtr};
use pezsp_runtime::RuntimeAppPublic;
use pezsp_state_machine::StorageValue;
use pezsp_version::RuntimeVersion;
use std::{
borrow::Cow,
collections::{BTreeMap, VecDeque},
time::Duration,
};
fn check_error(error: crate::BoxedError, check_error: impl Fn(&BlockAnnounceError) -> bool) {
let error = *error
.downcast::<BlockAnnounceError>()
.expect("Downcasts error to `ClientError`");
if !check_error(&error) {
panic!("Invalid error: {:?}", error);
}
}
fn dummy_candidate() -> CommittedCandidateReceiptV2 {
CommittedCandidateReceiptV2 {
descriptor: CandidateDescriptorV2::new(
0u32.into(),
PHash::random(),
0.into(),
1,
PHash::random(),
PHash::random(),
PHash::random(),
pezkuwi_teyrchain_primitives::primitives::HeadData(default_header().encode()).hash(),
ValidationCodeHash::from(PHash::random()),
),
commitments: CandidateCommitments {
upward_messages: Default::default(),
horizontal_messages: Default::default(),
new_validation_code: None,
head_data: HeadData(Vec::new()),
processed_downward_messages: 0,
hrmp_watermark: 0,
},
}
}
#[derive(Clone)]
struct DummyRelayChainInterface {
data: Arc<Mutex<ApiData>>,
relay_client: Arc<PClient>,
relay_backend: Arc<PBackend>,
}
impl DummyRelayChainInterface {
fn new() -> Self {
let builder = TestClientBuilder::new();
let relay_backend = builder.backend();
Self {
data: Arc::new(Mutex::new(ApiData {
validators: vec![Sr25519Keyring::Alice.public().into()],
has_pending_availability: false,
runtime_version:
RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT,
})),
relay_client: Arc::new(builder.build()),
relay_backend,
}
}
}
#[async_trait]
impl RelayChainInterface for DummyRelayChainInterface {
async fn validators(&self, _: PHash) -> RelayChainResult<Vec<ValidatorId>> {
Ok(self.data.lock().validators.clone())
}
async fn best_block_hash(&self) -> RelayChainResult<PHash> {
Ok(self.relay_backend.blockchain().info().best_hash)
}
async fn finalized_block_hash(&self) -> RelayChainResult<PHash> {
Ok(self.relay_backend.blockchain().info().finalized_hash)
}
async fn retrieve_dmq_contents(
&self,
_: ParaId,
_: PHash,
) -> RelayChainResult<Vec<InboundDownwardMessage>> {
unimplemented!("Not needed for test")
}
async fn retrieve_all_inbound_hrmp_channel_contents(
&self,
_: ParaId,
_: PHash,
) -> RelayChainResult<BTreeMap<ParaId, Vec<InboundHrmpMessage>>> {
Ok(BTreeMap::new())
}
async fn persisted_validation_data(
&self,
_: PHash,
_: ParaId,
_: OccupiedCoreAssumption,
) -> RelayChainResult<Option<PersistedValidationData>> {
Ok(Some(PersistedValidationData {
parent_head: HeadData(default_header().encode()),
..Default::default()
}))
}
async fn validation_code_hash(
&self,
_: PHash,
_: ParaId,
_: OccupiedCoreAssumption,
) -> RelayChainResult<Option<ValidationCodeHash>> {
unimplemented!("Not needed for test")
}
async fn candidate_pending_availability(
&self,
_: PHash,
_: ParaId,
) -> RelayChainResult<Option<CommittedCandidateReceiptV2>> {
if self.data.lock().runtime_version >=
RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT
{
panic!("Should have used candidates_pending_availability instead");
}
if self.data.lock().has_pending_availability {
Ok(Some(dummy_candidate()))
} else {
Ok(None)
}
}
async fn candidates_pending_availability(
&self,
_: PHash,
_: ParaId,
) -> RelayChainResult<Vec<CommittedCandidateReceiptV2>> {
if self.data.lock().runtime_version <
RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT
{
panic!("Should have used candidate_pending_availability instead");
}
if self.data.lock().has_pending_availability {
Ok(vec![dummy_candidate()])
} else {
Ok(vec![])
}
}
async fn session_index_for_child(&self, _: PHash) -> RelayChainResult<SessionIndex> {
Ok(0)
}
async fn import_notification_stream(
&self,
) -> RelayChainResult<Pin<Box<dyn Stream<Item = PHeader> + Send>>> {
Ok(Box::pin(
self.relay_client
.import_notification_stream()
.map(|notification| notification.header),
))
}
async fn finality_notification_stream(
&self,
) -> RelayChainResult<Pin<Box<dyn Stream<Item = PHeader> + Send>>> {
Ok(Box::pin(
self.relay_client
.finality_notification_stream()
.map(|notification| notification.header),
))
}
async fn is_major_syncing(&self) -> RelayChainResult<bool> {
Ok(false)
}
fn overseer_handle(&self) -> RelayChainResult<OverseerHandle> {
unimplemented!("Not needed for test")
}
async fn get_storage_by_key(
&self,
_: PHash,
_: &[u8],
) -> RelayChainResult<Option<StorageValue>> {
unimplemented!("Not needed for test")
}
async fn prove_read(
&self,
_: PHash,
_: &Vec<Vec<u8>>,
) -> RelayChainResult<pezsc_client_api::StorageProof> {
unimplemented!("Not needed for test")
}
async fn wait_for_block(&self, hash: PHash) -> RelayChainResult<()> {
let mut listener = match check_block_in_chain(
self.relay_backend.clone(),
self.relay_client.clone(),
hash,
)? {
BlockCheckStatus::InChain => return Ok(()),
BlockCheckStatus::Unknown(listener) => listener,
};
let mut timeout = futures_timer::Delay::new(Duration::from_secs(10)).fuse();
loop {
futures::select! {
_ = timeout => return Err(RelayChainError::WaitTimeout(hash)),
evt = listener.next() => match evt {
Some(evt) if evt.hash == hash => return Ok(()),
// Not the event we waited on.
Some(_) => continue,
None => return Err(RelayChainError::ImportListenerClosed(hash)),
}
}
}
}
async fn new_best_notification_stream(
&self,
) -> RelayChainResult<Pin<Box<dyn Stream<Item = PHeader> + Send>>> {
let notifications_stream =
self.relay_client
.import_notification_stream()
.filter_map(|notification| async move {
if notification.is_new_best {
Some(notification.header)
} else {
None
}
});
Ok(Box::pin(notifications_stream))
}
async fn header(&self, block_id: BlockId) -> RelayChainResult<Option<PHeader>> {
let hash = match block_id {
BlockId::Hash(hash) => hash,
BlockId::Number(num) =>
if let Some(hash) = self.relay_client.hash(num)? {
hash
} else {
return Ok(None);
},
};
let header = self.relay_client.header(hash)?;
Ok(header)
}
async fn availability_cores(
&self,
_relay_parent: PHash,
) -> RelayChainResult<Vec<CoreState<PHash, BlockNumber>>> {
unimplemented!("Not needed for test");
}
async fn version(&self, _: PHash) -> RelayChainResult<RuntimeVersion> {
let version = self.data.lock().runtime_version;
let apis = pezsp_version::create_apis_vec!([(
<dyn pezkuwi_primitives::runtime_api::TeyrchainHost<pezkuwi_primitives::Block>>::ID,
version
)])
.into_owned()
.to_vec();
Ok(RuntimeVersion {
spec_name: Cow::Borrowed("test"),
impl_name: Cow::Borrowed("test"),
authoring_version: 1,
spec_version: 1,
impl_version: 0,
apis: Cow::Owned(apis),
transaction_version: 5,
system_version: 1,
})
}
async fn claim_queue(
&self,
_: PHash,
) -> RelayChainResult<BTreeMap<CoreIndex, VecDeque<ParaId>>> {
unimplemented!("Not needed for test");
}
async fn call_runtime_api(
&self,
_method_name: &'static str,
_hash: PHash,
_payload: &[u8],
) -> RelayChainResult<Vec<u8>> {
unimplemented!("Not needed for test")
}
async fn scheduling_lookahead(&self, _: PHash) -> RelayChainResult<u32> {
unimplemented!("Not needed for test")
}
async fn candidate_events(&self, _: PHash) -> RelayChainResult<Vec<CandidateEvent>> {
unimplemented!("Not needed for test")
}
}
fn make_validator_and_api() -> (
RequireSecondedInBlockAnnounce<Block, Arc<DummyRelayChainInterface>>,
Arc<DummyRelayChainInterface>,
) {
let relay_chain_interface = Arc::new(DummyRelayChainInterface::new());
(
RequireSecondedInBlockAnnounce::new(relay_chain_interface.clone(), ParaId::from(56)),
relay_chain_interface,
)
}
fn default_header() -> Header {
Header {
number: 1,
digest: Default::default(),
extrinsics_root: Default::default(),
parent_hash: Default::default(),
state_root: Default::default(),
}
}
/// Same as [`make_gossip_message_and_header`], but using the genesis header as relay parent.
async fn make_gossip_message_and_header_using_genesis(
api: Arc<DummyRelayChainInterface>,
validator_index: u32,
) -> (CollationSecondedSignal, Header) {
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
}
async fn make_gossip_message_and_header(
relay_chain_interface: Arc<DummyRelayChainInterface>,
relay_parent: H256,
validator_index: u32,
) -> (CollationSecondedSignal, Header) {
let keystore: KeystorePtr = Arc::new(MemoryKeystore::new());
let alice_public = Keystore::sr25519_generate_new(
&*keystore,
ValidatorId::ID,
Some(&Sr25519Keyring::Alice.to_seed()),
)
.unwrap();
let session_index = relay_chain_interface.session_index_for_child(relay_parent).await.unwrap();
let signing_context = SigningContext { parent_hash: relay_parent, session_index };
let header = default_header();
let candidate_receipt = CommittedCandidateReceipt {
commitments: CandidateCommitments {
head_data: header.encode().into(),
..Default::default()
},
descriptor: CandidateDescriptor {
para_id: 0u32.into(),
relay_parent,
collator: CollatorPair::generate().0.public(),
persisted_validation_data_hash: PHash::random(),
pov_hash: PHash::random(),
erasure_root: PHash::random(),
signature: pezsp_core::sr25519::Signature::default().into(),
para_head: pezkuwi_teyrchain_primitives::primitives::HeadData(header.encode()).hash(),
validation_code_hash: ValidationCodeHash::from(PHash::random()),
},
};
let statement = Statement::Seconded(candidate_receipt.into());
let signed = SignedFullStatement::sign(
&keystore,
statement,
&signing_context,
validator_index.into(),
&alice_public.into(),
)
.ok()
.flatten()
.expect("Signing statement");
(CollationSecondedSignal { statement: signed, relay_parent }, 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 res = block_on(validator.validate(&header, &[]));
assert_eq!(
res.unwrap(),
Validation::Success { is_new_best: false },
"validating without data with block number < best known number is always a success",
);
}
#[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 res = block_on(validator.validate(&header, &[]));
assert_eq!(
res.unwrap(),
Validation::Failure { disconnect: false },
"validation fails if no justification and block number >= best known number",
);
}
#[test]
fn valid_if_no_data_and_block_matches_best_known_block() {
let mut validator = make_validator_and_api().0;
let res = block_on(validator.validate(&default_header(), &[]));
assert_eq!(
res.unwrap(),
Validation::Success { is_new_best: true },
"validation is successful when the block hash matches the best known block",
);
}
#[test]
fn check_statement_is_encoded_correctly() {
let mut validator = make_validator_and_api().0;
let header = default_header();
let res = block_on(validator.validate(&header, &[0x42]))
.expect_err("Should fail on invalid encoded statement");
check_error(res, |error| {
matches!(
error,
BlockAnnounceError(x) if x.contains("Can not decode the `BlockAnnounceData`")
)
});
}
#[test]
fn block_announce_data_decoding_should_reject_extra_data() {
let (mut validator, api) = make_validator_and_api();
let (signal, header) = block_on(make_gossip_message_and_header_using_genesis(api, 1));
let mut data = BlockAnnounceData::try_from(&signal).unwrap().encode();
data.push(0x42);
let res = block_on(validator.validate(&header, &data)).expect_err("Should return an error ");
check_error(res, |error| {
matches!(
error,
BlockAnnounceError(x) if x.contains("Input buffer has still data left after decoding!")
)
});
}
#[derive(Encode, Decode, Debug)]
struct LegacyBlockAnnounceData {
receipt: CandidateReceipt,
statement: UncheckedSigned<CompactStatement>,
}
#[test]
fn legacy_block_announce_data_handling() {
let (_, api) = make_validator_and_api();
let (signal, _) = block_on(make_gossip_message_and_header_using_genesis(api, 1));
let receipt = if let Statement::Seconded(receipt) = signal.statement.payload() {
receipt.to_plain()
} else {
panic!("Invalid")
};
let legacy = LegacyBlockAnnounceData {
receipt: receipt.clone(),
statement: signal.statement.convert_payload().into(),
};
let data = legacy.encode();
let block_data =
BlockAnnounceData::decode(&mut &data[..]).expect("Decoding works from legacy works");
assert_eq!(receipt.descriptor.relay_parent(), block_data.relay_parent);
let data = block_data.encode();
LegacyBlockAnnounceData::decode(&mut &data[..]).expect("Decoding works");
}
#[test]
fn check_signer_is_legit_validator() {
let (mut validator, api) = make_validator_and_api();
let (signal, header) = block_on(make_gossip_message_and_header_using_genesis(api, 1));
let data = BlockAnnounceData::try_from(&signal).unwrap().encode();
let res = block_on(validator.validate(&header, &data));
assert_eq!(Validation::Failure { disconnect: true }, res.unwrap());
}
#[test]
fn check_statement_is_correctly_signed() {
let (mut validator, api) = make_validator_and_api();
let (signal, header) = block_on(make_gossip_message_and_header_using_genesis(api, 0));
let mut data = BlockAnnounceData::try_from(&signal).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;
data[last] = data[last].wrapping_add(1);
let res = block_on(validator.validate(&header, &data));
assert_eq!(Validation::Failure { disconnect: true }, res.unwrap());
}
#[tokio::test]
async fn check_statement_seconded() {
let (mut validator, relay_chain_interface) = make_validator_and_api();
let header = default_header();
let relay_parent = H256::from_low_u64_be(1);
let keystore: KeystorePtr = Arc::new(MemoryKeystore::new());
let alice_public = Keystore::sr25519_generate_new(
&*keystore,
ValidatorId::ID,
Some(&Sr25519Keyring::Alice.to_seed()),
)
.unwrap();
let session_index = relay_chain_interface.session_index_for_child(relay_parent).await.unwrap();
let signing_context = SigningContext { parent_hash: relay_parent, session_index };
let statement = Statement::Valid(Default::default());
let signed_statement = SignedFullStatement::sign(
&keystore,
statement,
&signing_context,
0.into(),
&alice_public.into(),
)
.ok()
.flatten()
.expect("Signs statement");
let data = BlockAnnounceData {
receipt: CandidateReceipt {
commitments_hash: PHash::random(),
descriptor: CandidateDescriptor {
para_head: HeadData(Vec::new()).hash(),
para_id: 0u32.into(),
relay_parent: PHash::random(),
collator: CollatorPair::generate().0.public(),
persisted_validation_data_hash: PHash::random(),
pov_hash: PHash::random(),
erasure_root: PHash::random(),
signature: pezsp_core::sr25519::Signature::default().into(),
validation_code_hash: ValidationCodeHash::from(PHash::random()),
}
.into(),
},
statement: signed_statement.convert_payload().into(),
relay_parent,
}
.encode();
let res = block_on(validator.validate(&header, &data));
assert_eq!(Validation::Failure { disconnect: true }, res.unwrap());
}
#[test]
fn check_header_match_candidate_receipt_header() {
let (mut validator, api) = make_validator_and_api();
let (signal, mut header) = block_on(make_gossip_message_and_header_using_genesis(api, 0));
let data = BlockAnnounceData::try_from(&signal).unwrap().encode();
header.number = 300;
let res = block_on(validator.validate(&header, &data));
assert_eq!(Validation::Failure { disconnect: true }, res.unwrap());
}
/// Test that ensures that we postpone the block announce verification until
/// a relay chain block is imported. This is important for when we receive a
/// block announcement before we have imported the associated relay chain block
/// which can happen on slow nodes or nodes with a slow network connection.
#[test]
fn relay_parent_not_imported_when_block_announce_is_processed() {
block_on(async move {
let (mut validator, api) = make_validator_and_api();
let client = api.relay_client.clone();
let block = client.init_pezkuwi_block_builder().build().expect("Build new block").block;
let (signal, header) = make_gossip_message_and_header(api, block.hash(), 0).await;
let data = BlockAnnounceData::try_from(&signal).unwrap().encode();
let mut validation = validator.validate(&header, &data);
// The relay chain block is not available yet, so the first poll should return
// that the future is still pending.
assert!(poll!(&mut validation).is_pending());
client.import(BlockOrigin::Own, block).await.expect("Imports the block");
assert!(matches!(
poll!(validation),
Poll::Ready(Ok(Validation::Success { is_new_best: true }))
));
});
}
/// Ensures that when we receive a block announcement without a statement included, while the block
/// is not yet included by the node checking the announcement, but the node is already backed.
#[rstest]
#[case(RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT)]
#[case(10)]
fn block_announced_without_statement_and_block_only_backed(#[case] runtime_version: u32) {
block_on(async move {
let (mut validator, api) = make_validator_and_api();
api.data.lock().has_pending_availability = true;
api.data.lock().runtime_version = runtime_version;
let header = default_header();
let validation = validator.validate(&header, &[]);
assert!(matches!(validation.await, Ok(Validation::Success { is_new_best: true })));
});
}
#[derive(Default)]
struct ApiData {
validators: Vec<ValidatorId>,
has_pending_availability: bool,
runtime_version: u32,
}