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
+78
View File
@@ -0,0 +1,78 @@
[package]
name = "pezcumulus-test-client"
version = "0.1.0"
authors.workspace = true
edition.workspace = true
publish = false
[lints]
workspace = true
[dependencies]
codec = { features = ["derive"], workspace = true }
# Bizinikiwi
pezframe-system = { workspace = true, default-features = true }
pezpallet-balances = { workspace = true, default-features = true }
pezpallet-transaction-payment = { workspace = true, default-features = true }
pezsc-block-builder = { workspace = true, default-features = true }
pezsc-consensus = { workspace = true, default-features = true }
pezsc-consensus-aura = { workspace = true, default-features = true }
pezsc-executor = { workspace = true, default-features = true }
pezsc-executor-common = { workspace = true, default-features = true }
pezsc-service = { workspace = true, default-features = true }
pezsp-api = { workspace = true, default-features = true }
pezsp-application-crypto = { workspace = true, default-features = true }
pezsp-blockchain = { workspace = true, default-features = true }
pezsp-consensus-aura = { workspace = true, default-features = true }
pezsp-core = { workspace = true, default-features = true }
pezsp-inherents = { workspace = true, default-features = true }
pezsp-io = { workspace = true, default-features = true }
pezsp-keyring = { workspace = true, default-features = true }
pezsp-keystore = { workspace = true, default-features = true }
pezsp-runtime = { workspace = true, default-features = true }
pezsp-timestamp = { workspace = true, default-features = true }
bizinikiwi-test-client = { workspace = true }
# Pezkuwi
pezkuwi-primitives = { workspace = true, default-features = true }
pezkuwi-teyrchain-primitives = { workspace = true, default-features = true }
# Pezcumulus
pezcumulus-pezpallet-weight-reclaim = { workspace = true, default-features = true }
pezcumulus-primitives-core = { workspace = true, default-features = true }
pezcumulus-primitives-proof-size-hostfunction = { workspace = true, default-features = true }
pezcumulus-primitives-teyrchain-inherent = { workspace = true, default-features = true }
pezcumulus-test-relay-sproof-builder = { workspace = true, default-features = true }
pezcumulus-test-runtime = { workspace = true }
pezcumulus-test-service = { workspace = true }
[features]
runtime-benchmarks = [
"pezcumulus-pezpallet-weight-reclaim/runtime-benchmarks",
"pezcumulus-primitives-core/runtime-benchmarks",
"pezcumulus-primitives-proof-size-hostfunction/runtime-benchmarks",
"pezcumulus-primitives-teyrchain-inherent/runtime-benchmarks",
"pezcumulus-test-relay-sproof-builder/runtime-benchmarks",
"pezcumulus-test-runtime/runtime-benchmarks",
"pezcumulus-test-service/runtime-benchmarks",
"pezframe-system/runtime-benchmarks",
"pezpallet-balances/runtime-benchmarks",
"pezpallet-transaction-payment/runtime-benchmarks",
"pezkuwi-primitives/runtime-benchmarks",
"pezkuwi-teyrchain-primitives/runtime-benchmarks",
"pezsc-block-builder/runtime-benchmarks",
"pezsc-consensus-aura/runtime-benchmarks",
"pezsc-consensus/runtime-benchmarks",
"pezsc-executor/runtime-benchmarks",
"pezsc-service/runtime-benchmarks",
"pezsp-api/runtime-benchmarks",
"pezsp-blockchain/runtime-benchmarks",
"pezsp-consensus-aura/runtime-benchmarks",
"pezsp-inherents/runtime-benchmarks",
"pezsp-io/runtime-benchmarks",
"pezsp-keyring/runtime-benchmarks",
"pezsp-runtime/runtime-benchmarks",
"pezsp-timestamp/runtime-benchmarks",
"bizinikiwi-test-client/runtime-benchmarks",
]
+287
View File
@@ -0,0 +1,287 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// 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 <http://www.gnu.org/licenses/>.
use crate::Client;
use codec::Encode;
use cumulus_primitives_core::{PersistedValidationData, TeyrchainBlockData};
use cumulus_primitives_teyrchain_inherent::{TeyrchainInherentData, INHERENT_IDENTIFIER};
use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
use cumulus_test_runtime::{Block, GetLastTimestamp, Hash, Header};
use pezkuwi_primitives::{BlockNumber as PBlockNumber, Hash as PHash};
use pezsc_block_builder::BlockBuilderBuilder;
use pezsp_api::{ProofRecorder, ProofRecorderIgnoredNodes, ProvideRuntimeApi};
use pezsp_consensus_aura::{AuraApi, Slot};
use pezsp_runtime::{traits::Header as HeaderT, Digest, DigestItem};
/// A struct containing a block builder and support data required to build test scenarios.
pub struct BlockBuilderAndSupportData<'a> {
pub block_builder: pezsc_block_builder::BlockBuilder<'a, Block, Client>,
pub persisted_validation_data: PersistedValidationData<PHash, PBlockNumber>,
}
/// An extension for the Pezcumulus test client to init a block builder.
pub trait InitBlockBuilder {
/// Init a specific block builder that works for the test runtime.
///
/// This will automatically create and push the inherents for you to make the block
/// valid for the test runtime.
///
/// You can use the relay chain state sproof builder to arrange required relay chain state or
/// just use a default one. The relay chain slot in the storage proof
/// will be adjusted to align with the teyrchain slot to pass validation.
///
/// Returns the block builder and validation data for further usage.
fn init_block_builder(
&self,
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
) -> BlockBuilderAndSupportData<'_>;
/// Init a specific block builder at a specific block that works for the test runtime.
///
/// Same as [`InitBlockBuilder::init_block_builder`] besides that it takes a
/// [`type@Hash`] to say which should be the parent block of the block that is being build.
fn init_block_builder_at(
&self,
at: Hash,
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
) -> BlockBuilderAndSupportData<'_>;
/// Init a specific block builder using the given pre-digests.
///
/// Same as [`InitBlockBuilder::init_block_builder`] besides that it takes vector of
/// [`DigestItem`]'s that are passed as pre-digest to the block builder.
fn init_block_builder_with_pre_digests(
&self,
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
pre_digests: Vec<DigestItem>,
) -> BlockBuilderAndSupportData<'_>;
/// Init a specific block builder at a specific block that works for the test runtime.
///
/// Same as [`InitBlockBuilder::init_block_builder_with_timestamp`] besides that it takes
/// `ignored_nodes` that instruct the proof recorder to not record these nodes.
fn init_block_builder_with_ignored_nodes(
&self,
at: Hash,
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
timestamp: u64,
ignored_nodes: ProofRecorderIgnoredNodes<Block>,
) -> BlockBuilderAndSupportData<'_>;
/// Init a specific block builder that works for the test runtime.
///
/// Same as [`InitBlockBuilder::init_block_builder`] besides that it takes a
/// [`type@Hash`] to say which should be the parent block of the block that is being build and
/// it will use the given `timestamp` as input for the timestamp inherent.
fn init_block_builder_with_timestamp(
&self,
at: Hash,
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
timestamp: u64,
) -> BlockBuilderAndSupportData<'_>;
}
fn init_block_builder(
client: &Client,
at: Hash,
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
mut relay_sproof_builder: RelayStateSproofBuilder,
timestamp: Option<u64>,
extra_pre_digests: Option<Vec<DigestItem>>,
ignored_nodes: Option<ProofRecorderIgnoredNodes<Block>>,
) -> BlockBuilderAndSupportData<'_> {
let timestamp = timestamp.unwrap_or_else(|| {
let last_timestamp =
client.runtime_api().get_last_timestamp(at).expect("Get last timestamp");
if last_timestamp == 0 {
if relay_sproof_builder.current_slot != 0u64 {
*relay_sproof_builder.current_slot * 6_000
} else {
std::time::SystemTime::now()
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.expect("Time is always after UNIX_EPOCH; qed")
.as_millis() as u64
}
} else {
last_timestamp + client.runtime_api().slot_duration(at).unwrap().as_millis()
}
});
let slot: Slot =
(timestamp / client.runtime_api().slot_duration(at).unwrap().as_millis()).into();
if relay_sproof_builder.current_slot == 0u64 {
relay_sproof_builder.current_slot = (timestamp / 6_000).into();
}
let pre_digests = Digest {
logs: extra_pre_digests
.unwrap_or_default()
.into_iter()
.chain(std::iter::once(DigestItem::PreRuntime(
pezsp_consensus_aura::AURA_ENGINE_ID,
slot.encode(),
)))
.collect::<Vec<_>>(),
};
let mut block_builder = BlockBuilderBuilder::new(client)
.on_parent_block(at)
.fetch_parent_block_number(client)
.unwrap()
.with_proof_recorder(Some(ProofRecorder::<Block>::with_ignored_nodes(
ignored_nodes.unwrap_or_default(),
)))
.with_inherent_digests(pre_digests)
.build()
.expect("Creates new block builder for test runtime");
let mut inherent_data = pezsp_inherents::InherentData::new();
inherent_data
.put_data(pezsp_timestamp::INHERENT_IDENTIFIER, &timestamp)
.expect("Put timestamp failed");
let (relay_parent_storage_root, relay_chain_state) =
relay_sproof_builder.into_state_root_and_proof();
let mut validation_data = validation_data.unwrap_or_default();
validation_data.relay_parent_storage_root = relay_parent_storage_root;
inherent_data
.put_data(
INHERENT_IDENTIFIER,
&TeyrchainInherentData {
validation_data: validation_data.clone(),
relay_chain_state,
downward_messages: Default::default(),
horizontal_messages: Default::default(),
relay_parent_descendants: Default::default(),
collator_peer_id: None,
},
)
.expect("Put validation function params failed");
let inherents = block_builder.create_inherents(inherent_data).expect("Creates inherents");
inherents
.into_iter()
.for_each(|ext| block_builder.push(ext).expect("Pushes inherent"));
BlockBuilderAndSupportData { block_builder, persisted_validation_data: validation_data }
}
impl InitBlockBuilder for Client {
fn init_block_builder(
&self,
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
) -> BlockBuilderAndSupportData<'_> {
let chain_info = self.chain_info();
self.init_block_builder_at(chain_info.best_hash, validation_data, relay_sproof_builder)
}
fn init_block_builder_with_pre_digests(
&self,
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
pre_digests: Vec<DigestItem>,
) -> BlockBuilderAndSupportData<'_> {
let chain_info = self.chain_info();
init_block_builder(
self,
chain_info.best_hash,
validation_data,
relay_sproof_builder,
None,
Some(pre_digests),
None,
)
}
fn init_block_builder_at(
&self,
at: Hash,
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
) -> BlockBuilderAndSupportData<'_> {
init_block_builder(self, at, validation_data, relay_sproof_builder, None, None, None)
}
fn init_block_builder_with_ignored_nodes(
&self,
at: Hash,
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
timestamp: u64,
ignored_nodes: ProofRecorderIgnoredNodes<Block>,
) -> BlockBuilderAndSupportData<'_> {
init_block_builder(
self,
at,
validation_data,
relay_sproof_builder,
Some(timestamp),
None,
Some(ignored_nodes),
)
}
fn init_block_builder_with_timestamp(
&self,
at: Hash,
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
timestamp: u64,
) -> BlockBuilderAndSupportData<'_> {
init_block_builder(
self,
at,
validation_data,
relay_sproof_builder,
Some(timestamp),
None,
None,
)
}
}
/// Extension trait for the [`BlockBuilder`](pezsc_block_builder::BlockBuilder) to build directly a
/// [`TeyrchainBlockData`].
pub trait BuildTeyrchainBlockData {
/// Directly build the [`TeyrchainBlockData`] from the block that comes out of the block
/// builder.
fn build_teyrchain_block(self, parent_state_root: Hash) -> TeyrchainBlockData<Block>;
}
impl<'a> BuildTeyrchainBlockData for pezsc_block_builder::BlockBuilder<'a, Block, Client> {
fn build_teyrchain_block(self, parent_state_root: Hash) -> TeyrchainBlockData<Block> {
let built_block = self.build().expect("Builds the block");
let storage_proof = built_block
.proof
.expect("We enabled proof recording before.")
.into_compact_proof::<<Header as HeaderT>::Hashing>(parent_state_root)
.expect("Creates the compact proof");
TeyrchainBlockData::new(vec![built_block.block], storage_proof)
}
}
+262
View File
@@ -0,0 +1,262 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// 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 <http://www.gnu.org/licenses/>.
//! A Pezcumulus test client.
mod block_builder;
pub use block_builder::*;
use codec::{Decode, Encode};
pub use cumulus_test_runtime as runtime;
use cumulus_test_runtime::AuraId;
pub use pezkuwi_teyrchain_primitives::primitives::{
BlockData, HeadData, ValidationParams, ValidationResult,
};
use runtime::{
Balance, Block, BlockHashCount, Runtime, RuntimeCall, Signature, SignedPayload, TxExtension,
UncheckedExtrinsic, VERSION,
};
use pezsc_consensus_aura::{
find_pre_digest,
standalone::{seal, slot_author},
};
pub use pezsc_executor::error::Result as ExecutorResult;
use pezsc_executor::HeapAllocStrategy;
use pezsc_executor_common::runtime_blob::RuntimeBlob;
use pezsp_api::ProvideRuntimeApi;
use pezsp_application_crypto::AppCrypto;
use pezsp_blockchain::HeaderBackend;
use pezsp_consensus_aura::AuraApi;
use pezsp_core::Pair;
use pezsp_io::TestExternalities;
use pezsp_keystore::testing::MemoryKeystore;
use pezsp_runtime::{generic::Era, traits::Header, BuildStorage, MultiAddress, SaturatedConversion};
use std::sync::Arc;
pub use bizinikiwi_test_client::*;
pub type TeyrchainBlockData = cumulus_primitives_core::TeyrchainBlockData<Block>;
/// Test client database backend.
pub type Backend = bizinikiwi_test_client::Backend<Block>;
/// Test client executor.
pub type Executor = client::LocalCallExecutor<
Block,
Backend,
WasmExecutor<(
pezsp_io::BizinikiwiHostFunctions,
cumulus_primitives_proof_size_hostfunction::storage_proof_size::HostFunctions,
)>,
>;
/// Test client builder for Pezcumulus
pub type TestClientBuilder =
bizinikiwi_test_client::TestClientBuilder<Block, Executor, Backend, GenesisParameters>;
/// LongestChain type for the test runtime/client.
pub type LongestChain = pezsc_consensus::LongestChain<Backend, Block>;
/// Test client type with `LocalExecutor` and generic Backend.
pub type Client = client::Client<Backend, Executor, Block, runtime::RuntimeApi>;
/// Parameters of test-client builder with test-runtime.
#[derive(Default)]
pub struct GenesisParameters {
pub endowed_accounts: Vec<cumulus_test_runtime::AccountId>,
pub wasm: Option<Vec<u8>>,
}
impl bizinikiwi_test_client::GenesisInit for GenesisParameters {
fn genesis_storage(&self) -> Storage {
cumulus_test_service::chain_spec::get_chain_spec_with_extra_endowed(
None,
self.endowed_accounts.clone(),
self.wasm.as_deref().unwrap_or_else(|| {
cumulus_test_runtime::WASM_BINARY.expect("WASM binary not compiled!")
}),
)
.build_storage()
.expect("Builds test runtime genesis storage")
}
}
/// A `test-runtime` extensions to [`TestClientBuilder`].
pub trait TestClientBuilderExt: Sized {
/// Build the test client.
fn build(self) -> Client {
self.build_with_longest_chain().0
}
/// Build the test client and longest chain selector.
fn build_with_longest_chain(self) -> (Client, LongestChain);
}
impl TestClientBuilderExt for TestClientBuilder {
fn build_with_longest_chain(self) -> (Client, LongestChain) {
self.build_with_native_executor(None)
}
}
/// A `TestClientBuilder` with default backend and executor.
pub trait DefaultTestClientBuilderExt: Sized {
/// Create new `TestClientBuilder`
fn new() -> Self;
}
impl DefaultTestClientBuilderExt for TestClientBuilder {
fn new() -> Self {
Self::with_default_backend()
}
}
/// Create an unsigned extrinsic from a runtime call.
pub fn generate_unsigned(function: impl Into<RuntimeCall>) -> UncheckedExtrinsic {
UncheckedExtrinsic::new_bare(function.into())
}
/// Create a signed extrinsic from a runtime call and sign
/// with the given key pair.
pub fn generate_extrinsic_with_pair(
client: &Client,
origin: pezsp_core::sr25519::Pair,
function: impl Into<RuntimeCall>,
nonce: Option<u32>,
) -> UncheckedExtrinsic {
let current_block_hash = client.info().best_hash;
let current_block = client.info().best_number.saturated_into();
let genesis_block = client.hash(0).unwrap().unwrap();
let nonce = nonce.unwrap_or_default();
let period =
BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2) as u64;
let tip = 0;
let tx_ext: TxExtension = (
pezframe_system::AuthorizeCall::<Runtime>::new(),
pezframe_system::CheckNonZeroSender::<Runtime>::new(),
pezframe_system::CheckSpecVersion::<Runtime>::new(),
pezframe_system::CheckGenesis::<Runtime>::new(),
pezframe_system::CheckEra::<Runtime>::from(Era::mortal(period, current_block)),
pezframe_system::CheckNonce::<Runtime>::from(nonce),
pezframe_system::CheckWeight::<Runtime>::new(),
pezpallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
)
.into();
let function = function.into();
let raw_payload = SignedPayload::from_raw(
function.clone(),
tx_ext.clone(),
((), (), VERSION.spec_version, genesis_block, current_block_hash, (), (), ()),
);
let signature = raw_payload.using_encoded(|e| origin.sign(e));
UncheckedExtrinsic::new_signed(
function,
MultiAddress::Id(origin.public().into()),
Signature::Sr25519(signature),
tx_ext,
)
}
/// Generate an extrinsic from the provided function call, origin and [`Client`].
pub fn generate_extrinsic(
client: &Client,
origin: pezsp_keyring::Sr25519Keyring,
function: impl Into<RuntimeCall>,
) -> UncheckedExtrinsic {
generate_extrinsic_with_pair(client, origin.into(), function, None)
}
/// Transfer some token from one account to another using a provided test [`Client`].
pub fn transfer(
client: &Client,
origin: pezsp_keyring::Sr25519Keyring,
dest: pezsp_keyring::Sr25519Keyring,
value: Balance,
) -> UncheckedExtrinsic {
let function = RuntimeCall::Balances(pezpallet_balances::Call::transfer_allow_death {
dest: MultiAddress::Id(dest.public().into()),
value,
});
generate_extrinsic(client, origin, function)
}
/// Call `validate_block` in the given `wasm_blob`.
pub fn validate_block(
validation_params: ValidationParams,
wasm_blob: &[u8],
) -> ExecutorResult<ValidationResult> {
let mut ext = TestExternalities::default();
let mut ext_ext = ext.ext();
let heap_pages = HeapAllocStrategy::Static { extra_pages: 2048 };
let executor = WasmExecutor::<(
pezsp_io::BizinikiwiHostFunctions,
cumulus_primitives_proof_size_hostfunction::storage_proof_size::HostFunctions,
)>::builder()
.with_execution_method(WasmExecutionMethod::default())
.with_max_runtime_instances(1)
.with_runtime_cache_size(2)
.with_onchain_heap_alloc_strategy(heap_pages)
.with_offchain_heap_alloc_strategy(heap_pages)
.build();
executor
.uncached_call(
RuntimeBlob::uncompress_if_needed(wasm_blob).expect("RuntimeBlob uncompress & parse"),
&mut ext_ext,
false,
"validate_block",
&validation_params.encode(),
)
.map(|v| ValidationResult::decode(&mut &v[..]).expect("Decode `ValidationResult`."))
}
fn get_keystore() -> pezsp_keystore::KeystorePtr {
let keystore = MemoryKeystore::new();
pezsp_keyring::Sr25519Keyring::iter().for_each(|key| {
keystore
.sr25519_generate_new(
pezsp_consensus_aura::sr25519::AuthorityPair::ID,
Some(&key.to_seed()),
)
.expect("Key should be created");
});
Arc::new(keystore)
}
/// Seals the given block with an AURA seal.
///
/// Assumes that the authorities of the test runtime are present in the keyring.
pub fn seal_block(mut block: Block, client: &Client) -> Block {
let teyrchain_slot =
find_pre_digest::<Block, <AuraId as AppCrypto>::Signature>(&block.header).unwrap();
let parent_hash = block.header.parent_hash;
let authorities = client.runtime_api().authorities(parent_hash).unwrap();
let expected_author = slot_author::<<AuraId as AppCrypto>::Pair>(teyrchain_slot, &authorities)
.expect("Should be able to find author");
let keystore = get_keystore();
let seal_digest = seal::<_, pezsp_consensus_aura::sr25519::AuthorityPair>(
&block.header.hash(),
expected_author,
&keystore,
)
.expect("Should be able to create seal");
block.header.digest_mut().push(seal_digest);
block
}
@@ -0,0 +1,44 @@
[package]
name = "pezcumulus-test-relay-sproof-builder"
version = "0.7.0"
authors.workspace = true
edition.workspace = true
license = "Apache-2.0"
description = "Mocked relay state proof builder for testing Pezcumulus."
homepage.workspace = true
repository.workspace = true
[lints]
workspace = true
[dependencies]
codec = { features = ["derive"], workspace = true }
# Bizinikiwi
pezsp-runtime = { workspace = true }
pezsp-state-machine = { workspace = true }
pezsp-trie = { workspace = true }
# Pezkuwi
pezkuwi-primitives = { workspace = true }
# Pezcumulus
pezcumulus-primitives-core = { workspace = true }
[features]
default = ["std"]
std = [
"codec/std",
"pezcumulus-primitives-core/std",
"pezkuwi-primitives/std",
"pezsp-runtime/std",
"pezsp-state-machine/std",
"pezsp-trie/std",
]
runtime-benchmarks = [
"pezcumulus-primitives-core/runtime-benchmarks",
"pezkuwi-primitives/runtime-benchmarks",
"pezsp-runtime/runtime-benchmarks",
"pezsp-state-machine/runtime-benchmarks",
"pezsp-trie/runtime-benchmarks",
]
@@ -0,0 +1,215 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate alloc;
use alloc::collections::btree_map::BTreeMap;
use cumulus_primitives_core::{
relay_chain, AbridgedHostConfiguration, AbridgedHrmpChannel, ParaId,
};
use pezkuwi_primitives::UpgradeGoAhead;
use pezsp_runtime::traits::HashingFor;
use pezsp_trie::PrefixedMemoryDB;
/// Builds a sproof (portmanteau of 'spoof' and 'proof') of the relay chain state.
#[derive(Clone)]
pub struct RelayStateSproofBuilder {
/// The para id of the current teyrchain.
///
/// This doesn't get into the storage proof produced by the builder, however, it is used for
/// generation of the storage image and by auxiliary methods.
///
/// It's recommended to change this value once in the very beginning of usage.
///
/// The default value is 200.
pub para_id: ParaId,
pub host_config: AbridgedHostConfiguration,
pub dmq_mqc_head: Option<relay_chain::Hash>,
pub upgrade_go_ahead: Option<UpgradeGoAhead>,
pub relay_dispatch_queue_remaining_capacity: Option<(u32, u32)>,
pub hrmp_ingress_channel_index: Option<Vec<ParaId>>,
pub hrmp_egress_channel_index: Option<Vec<ParaId>>,
pub hrmp_channels: BTreeMap<relay_chain::HrmpChannelId, AbridgedHrmpChannel>,
pub current_slot: relay_chain::Slot,
pub current_epoch: u64,
pub randomness: relay_chain::Hash,
pub additional_key_values: Vec<(Vec<u8>, Vec<u8>)>,
pub included_para_head: Option<relay_chain::HeadData>,
}
impl Default for RelayStateSproofBuilder {
fn default() -> Self {
RelayStateSproofBuilder {
para_id: ParaId::from(200),
host_config: cumulus_primitives_core::AbridgedHostConfiguration {
max_code_size: 2 * 1024 * 1024,
max_head_data_size: 1024 * 1024,
max_upward_queue_count: 8,
max_upward_queue_size: 1024,
max_upward_message_size: 256,
max_upward_message_num_per_candidate: 5,
hrmp_max_message_num_per_candidate: 5,
validation_upgrade_cooldown: 6,
validation_upgrade_delay: 6,
async_backing_params: relay_chain::AsyncBackingParams {
allowed_ancestry_len: 0,
max_candidate_depth: 0,
},
},
dmq_mqc_head: None,
upgrade_go_ahead: None,
relay_dispatch_queue_remaining_capacity: None,
hrmp_ingress_channel_index: None,
hrmp_egress_channel_index: None,
hrmp_channels: BTreeMap::new(),
current_slot: 0.into(),
current_epoch: 0u64,
randomness: relay_chain::Hash::default(),
additional_key_values: vec![],
included_para_head: None,
}
}
}
impl RelayStateSproofBuilder {
/// Returns a mutable reference to HRMP channel metadata for a channel (`sender`,
/// `self.para_id`).
///
/// If there is no channel, a new default one is created.
///
/// It also updates the `hrmp_ingress_channel_index`, creating it if needed.
pub fn upsert_inbound_channel(&mut self, sender: ParaId) -> &mut AbridgedHrmpChannel {
let in_index = self.hrmp_ingress_channel_index.get_or_insert_with(Vec::new);
if let Err(idx) = in_index.binary_search(&sender) {
in_index.insert(idx, sender);
}
self.upsert_channel(relay_chain::HrmpChannelId { sender, recipient: self.para_id })
}
/// Returns a mutable reference to HRMP channel metadata for a channel (`self.para_id`,
/// `recipient`).
///
/// If there is no channel, a new default one is created.
///
/// It also updates the `hrmp_egress_channel_index`, creating it if needed.
pub fn upsert_outbound_channel(&mut self, recipient: ParaId) -> &mut AbridgedHrmpChannel {
let in_index = self.hrmp_egress_channel_index.get_or_insert_with(Vec::new);
if let Err(idx) = in_index.binary_search(&recipient) {
in_index.insert(idx, recipient);
}
self.upsert_channel(relay_chain::HrmpChannelId { sender: self.para_id, recipient })
}
/// Creates a new default entry in the hrmp channels mapping if not exists, and returns mutable
/// reference to it.
fn upsert_channel(&mut self, id: relay_chain::HrmpChannelId) -> &mut AbridgedHrmpChannel {
self.hrmp_channels.entry(id).or_insert_with(|| AbridgedHrmpChannel {
max_capacity: 0,
max_total_size: 0,
max_message_size: 0,
msg_count: 0,
total_size: 0,
mqc_head: None,
})
}
pub fn into_state_root_and_proof(
self,
) -> (pezkuwi_primitives::Hash, pezsp_state_machine::StorageProof) {
let (db, root) =
PrefixedMemoryDB::<HashingFor<pezkuwi_primitives::Block>>::default_with_root();
let state_version = Default::default(); // for test using default.
let mut backend = pezsp_state_machine::TrieBackendBuilder::new(db, root).build();
let mut relevant_keys = Vec::new();
{
use codec::Encode as _;
let mut insert = |key: Vec<u8>, value: Vec<u8>| {
relevant_keys.push(key.clone());
backend.insert(vec![(None, vec![(key, Some(value))])], state_version);
};
insert(relay_chain::well_known_keys::ACTIVE_CONFIG.to_vec(), self.host_config.encode());
if let Some(dmq_mqc_head) = self.dmq_mqc_head {
insert(
relay_chain::well_known_keys::dmq_mqc_head(self.para_id),
dmq_mqc_head.encode(),
);
}
if let Some(para_head) = self.included_para_head {
insert(relay_chain::well_known_keys::para_head(self.para_id), para_head.encode());
}
if let Some(relay_dispatch_queue_remaining_capacity) =
self.relay_dispatch_queue_remaining_capacity
{
insert(
relay_chain::well_known_keys::relay_dispatch_queue_remaining_capacity(
self.para_id,
)
.key,
relay_dispatch_queue_remaining_capacity.encode(),
);
}
if let Some(upgrade_go_ahead) = self.upgrade_go_ahead {
insert(
relay_chain::well_known_keys::upgrade_go_ahead_signal(self.para_id),
upgrade_go_ahead.encode(),
);
}
if let Some(hrmp_ingress_channel_index) = self.hrmp_ingress_channel_index {
let mut sorted = hrmp_ingress_channel_index.clone();
sorted.sort();
assert_eq!(sorted, hrmp_ingress_channel_index);
insert(
relay_chain::well_known_keys::hrmp_ingress_channel_index(self.para_id),
hrmp_ingress_channel_index.encode(),
);
}
if let Some(hrmp_egress_channel_index) = self.hrmp_egress_channel_index {
let mut sorted = hrmp_egress_channel_index.clone();
sorted.sort();
assert_eq!(sorted, hrmp_egress_channel_index);
insert(
relay_chain::well_known_keys::hrmp_egress_channel_index(self.para_id),
hrmp_egress_channel_index.encode(),
);
}
for (channel, metadata) in self.hrmp_channels {
insert(relay_chain::well_known_keys::hrmp_channels(channel), metadata.encode());
}
insert(relay_chain::well_known_keys::EPOCH_INDEX.to_vec(), self.current_epoch.encode());
insert(
relay_chain::well_known_keys::ONE_EPOCH_AGO_RANDOMNESS.to_vec(),
self.randomness.encode(),
);
insert(relay_chain::well_known_keys::CURRENT_SLOT.to_vec(), self.current_slot.encode());
for (key, value) in self.additional_key_values {
insert(key, value);
}
}
let root = *backend.root();
let proof = pezsp_state_machine::prove_read(backend, relevant_keys).expect("prove read");
(root, proof)
}
}
+143
View File
@@ -0,0 +1,143 @@
[package]
name = "pezcumulus-test-runtime"
version = "0.1.0"
authors.workspace = true
edition.workspace = true
publish = false
[lints]
workspace = true
[dependencies]
codec = { features = ["derive"], workspace = true }
scale-info = { features = ["derive"], workspace = true }
serde_json = { workspace = true }
# Bizinikiwi
pezframe-executive = { workspace = true }
pezframe-support = { workspace = true }
pezframe-system = { workspace = true }
pezframe-system-rpc-runtime-api = { workspace = true }
pezpallet-aura = { workspace = true }
pezpallet-authorship = { workspace = true }
pezpallet-balances = { workspace = true }
pezpallet-glutton = { workspace = true }
pezpallet-message-queue = { workspace = true }
pezpallet-session = { workspace = true }
pezpallet-sudo = { workspace = true }
pezpallet-timestamp = { workspace = true }
pezpallet-transaction-payment = { workspace = true }
pezsp-api = { workspace = true }
pezsp-block-builder = { workspace = true }
pezsp-consensus-aura = { workspace = true }
pezsp-core = { workspace = true }
pezsp-genesis-builder = { workspace = true }
pezsp-inherents = { workspace = true }
pezsp-io = { workspace = true }
pezsp-keyring = { workspace = true }
pezsp-offchain = { workspace = true }
pezsp-runtime = { workspace = true }
pezsp-session = { workspace = true }
pezsp-transaction-pool = { workspace = true }
pezsp-version = { workspace = true }
# Pezcumulus
pezcumulus-pezpallet-aura-ext = { workspace = true }
pezcumulus-pezpallet-teyrchain-system = { workspace = true }
pezcumulus-pezpallet-weight-reclaim = { workspace = true }
pezcumulus-primitives-aura = { workspace = true }
pezcumulus-primitives-core = { workspace = true }
teyrchain-info = { workspace = true }
[build-dependencies]
bizinikiwi-wasm-builder = { optional = true, workspace = true, default-features = true }
[features]
default = ["std"]
std = [
"codec/std",
"pezcumulus-pezpallet-aura-ext/std",
"pezcumulus-pezpallet-teyrchain-system/std",
"pezcumulus-pezpallet-weight-reclaim/std",
"pezcumulus-primitives-aura/std",
"pezcumulus-primitives-core/std",
"pezframe-executive/std",
"pezframe-support/std",
"pezframe-system-rpc-runtime-api/std",
"pezframe-system/std",
"pezpallet-aura/std",
"pezpallet-authorship/std",
"pezpallet-balances/std",
"pezpallet-glutton/std",
"pezpallet-message-queue/std",
"pezpallet-session/std",
"pezpallet-sudo/std",
"pezpallet-timestamp/std",
"pezpallet-transaction-payment/std",
"scale-info/std",
"serde_json/std",
"pezsp-api/std",
"pezsp-block-builder/std",
"pezsp-consensus-aura/std",
"pezsp-core/std",
"pezsp-genesis-builder/std",
"pezsp-inherents/std",
"pezsp-io/std",
"pezsp-keyring/std",
"pezsp-offchain/std",
"pezsp-runtime/std",
"pezsp-session/std",
"pezsp-transaction-pool/std",
"pezsp-version/std",
"bizinikiwi-wasm-builder",
"teyrchain-info/std",
]
increment-spec-version = []
# A runtime which expects to build behind the relay chain tip.
relay-parent-offset = []
# A runtime with elastic-scaling configuration.
elastic-scaling = []
# A runtime with low slot duration of 500ms for low-latency testing with 12 cores.
elastic-scaling-500ms = []
# A runtime with a slot duration of 6s but parameters that allow multiple blocks per slot.
elastic-scaling-multi-block-slot = []
# A runtime with 12s slot duration which only authors one block per slot.
sync-backing = []
# A runtime with 6s slot duration which only authors one block per slot.
async-backing = []
# An elastic scaling runtime with 12s slots.
elastic-scaling-12s-slot = []
runtime-benchmarks = [
"pezcumulus-pezpallet-aura-ext/runtime-benchmarks",
"pezcumulus-pezpallet-teyrchain-system/runtime-benchmarks",
"pezcumulus-pezpallet-weight-reclaim/runtime-benchmarks",
"pezcumulus-primitives-aura/runtime-benchmarks",
"pezcumulus-primitives-core/runtime-benchmarks",
"pezframe-executive/runtime-benchmarks",
"pezframe-support/runtime-benchmarks",
"pezframe-system-rpc-runtime-api/runtime-benchmarks",
"pezframe-system/runtime-benchmarks",
"pezpallet-aura/runtime-benchmarks",
"pezpallet-authorship/runtime-benchmarks",
"pezpallet-balances/runtime-benchmarks",
"pezpallet-glutton/runtime-benchmarks",
"pezpallet-message-queue/runtime-benchmarks",
"pezpallet-session/runtime-benchmarks",
"pezpallet-sudo/runtime-benchmarks",
"pezpallet-timestamp/runtime-benchmarks",
"pezpallet-transaction-payment/runtime-benchmarks",
"pezsp-api/runtime-benchmarks",
"pezsp-block-builder/runtime-benchmarks",
"pezsp-consensus-aura/runtime-benchmarks",
"pezsp-genesis-builder/runtime-benchmarks",
"pezsp-inherents/runtime-benchmarks",
"pezsp-io/runtime-benchmarks",
"pezsp-keyring/runtime-benchmarks",
"pezsp-offchain/runtime-benchmarks",
"pezsp-runtime/runtime-benchmarks",
"pezsp-session/runtime-benchmarks",
"pezsp-transaction-pool/runtime-benchmarks",
"pezsp-version/runtime-benchmarks",
"bizinikiwi-wasm-builder?/runtime-benchmarks",
"teyrchain-info/runtime-benchmarks",
]
+82
View File
@@ -0,0 +1,82 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// 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 <http://www.gnu.org/licenses/>.
#[cfg(feature = "std")]
fn main() {
use bizinikiwi_wasm_builder::WasmBuilder;
WasmBuilder::init_with_defaults()
.enable_feature("async-backing")
.import_memory()
.build();
WasmBuilder::init_with_defaults()
.enable_feature("increment-spec-version")
.set_file_name("wasm_binary_spec_version_incremented.rs")
.build();
WasmBuilder::init_with_defaults()
.enable_feature("elastic-scaling")
.import_memory()
.set_file_name("wasm_binary_elastic_scaling_mvp.rs")
.build();
WasmBuilder::new()
.with_current_project()
.enable_feature("elastic-scaling")
.import_memory()
.set_file_name("wasm_binary_elastic_scaling.rs")
.build();
WasmBuilder::new()
.with_current_project()
.enable_feature("elastic-scaling-500ms")
.import_memory()
.set_file_name("wasm_binary_elastic_scaling_500ms.rs")
.build();
WasmBuilder::new()
.with_current_project()
.enable_feature("elastic-scaling-multi-block-slot")
.import_memory()
.set_file_name("wasm_binary_elastic_scaling_multi_block_slot.rs")
.build();
WasmBuilder::new()
.with_current_project()
.enable_feature("relay-parent-offset")
.import_memory()
.set_file_name("wasm_binary_relay_parent_offset.rs")
.build();
WasmBuilder::new()
.with_current_project()
.enable_feature("sync-backing")
.import_memory()
.set_file_name("wasm_binary_sync_backing.rs")
.build();
WasmBuilder::new()
.with_current_project()
.enable_feature("elastic-scaling-12s-slot")
.enable_feature("elastic-scaling")
.import_memory()
.set_file_name("wasm_binary_elastic_scaling_12s_slot.rs")
.build();
}
#[cfg(not(feature = "std"))]
fn main() {}
@@ -0,0 +1,72 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// 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 <http://www.gnu.org/licenses/>.
use super::{
AccountId, AuraConfig, AuraId, BalancesConfig, RuntimeGenesisConfig, SudoConfig,
TeyrchainInfoConfig,
};
use alloc::{vec, vec::Vec};
use cumulus_primitives_core::ParaId;
use pezframe_support::build_struct_json_patch;
use pezsp_genesis_builder::PresetId;
use pezsp_keyring::Sr25519Keyring;
fn cumulus_test_runtime(
invulnerables: Vec<AuraId>,
endowed_accounts: Vec<AccountId>,
id: ParaId,
) -> serde_json::Value {
build_struct_json_patch!(RuntimeGenesisConfig {
balances: BalancesConfig {
balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 60)).collect(),
},
sudo: SudoConfig { key: Some(Sr25519Keyring::Alice.public().into()) },
teyrchain_info: TeyrchainInfoConfig { teyrchain_id: id },
aura: AuraConfig { authorities: invulnerables },
})
}
fn testnet_genesis_with_default_endowed(self_para_id: ParaId) -> serde_json::Value {
let endowed = Sr25519Keyring::well_known().map(|x| x.to_account_id()).collect::<Vec<_>>();
let invulnerables =
Sr25519Keyring::invulnerable().map(|x| x.public().into()).collect::<Vec<_>>();
cumulus_test_runtime(invulnerables, endowed, self_para_id)
}
/// List of supported presets.
pub fn preset_names() -> Vec<PresetId> {
vec![
PresetId::from(pezsp_genesis_builder::DEV_RUNTIME_PRESET),
PresetId::from(pezsp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET),
]
}
/// Provides the JSON representation of predefined genesis config for given `id`.
pub fn get_preset(id: &PresetId) -> Option<Vec<u8>> {
let patch = match id.as_ref() {
pezsp_genesis_builder::DEV_RUNTIME_PRESET |
pezsp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET =>
testnet_genesis_with_default_endowed(100.into()),
_ => return None,
};
Some(
serde_json::to_string(&patch)
.expect("serialization to json is expected to work. qed.")
.into_bytes(),
)
}
+644
View File
@@ -0,0 +1,644 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// 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 <http://www.gnu.org/licenses/>.
#![cfg_attr(not(feature = "std"), no_std)]
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
#![recursion_limit = "256"]
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
pub mod wasm_spec_version_incremented {
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary_spec_version_incremented.rs"));
}
pub mod relay_parent_offset {
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary_relay_parent_offset.rs"));
}
pub mod elastic_scaling_500ms {
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary_elastic_scaling_500ms.rs"));
}
pub mod elastic_scaling_mvp {
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary_elastic_scaling_mvp.rs"));
}
pub mod elastic_scaling {
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary_elastic_scaling.rs"));
}
pub mod elastic_scaling_multi_block_slot {
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary_elastic_scaling_multi_block_slot.rs"));
}
pub mod sync_backing {
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary_sync_backing.rs"));
}
pub mod async_backing {
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
}
mod genesis_config_presets;
mod test_pallet;
extern crate alloc;
use alloc::{vec, vec::Vec};
use pezframe_support::{derive_impl, traits::OnRuntimeUpgrade, PalletId};
use pezsp_api::{decl_runtime_apis, impl_runtime_apis};
pub use pezsp_consensus_aura::sr25519::AuthorityId as AuraId;
use pezsp_core::{ConstBool, ConstU32, ConstU64, OpaqueMetadata};
use pezsp_runtime::{
generic, impl_opaque_keys,
traits::{BlakeTwo256, Block as BlockT, IdentifyAccount, Verify},
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, MultiAddress, MultiSignature,
};
#[cfg(feature = "std")]
use pezsp_version::NativeVersion;
use pezsp_version::RuntimeVersion;
use cumulus_primitives_core::ParaId;
// A few exports that help ease life for downstream crates.
pub use pezframe_support::{
construct_runtime,
dispatch::DispatchClass,
genesis_builder_helper::{build_state, get_preset},
parameter_types,
traits::{ConstU8, Randomness},
weights::{
constants::{
BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND,
},
ConstantMultiplier, IdentityFee, Weight,
},
StorageValue,
};
pub use pezframe_system::Call as SystemCall;
use pezframe_system::{
limits::{BlockLength, BlockWeights},
EnsureRoot,
};
pub use pezpallet_balances::Call as BalancesCall;
pub use pezpallet_glutton::Call as GluttonCall;
pub use pezpallet_sudo::Call as SudoCall;
pub use pezpallet_timestamp::{Call as TimestampCall, Now};
#[cfg(any(feature = "std", test))]
pub use pezsp_runtime::BuildStorage;
pub use pezsp_runtime::{Perbill, Permill};
pub use test_pallet::Call as TestPalletCall;
pub type SessionHandlers = ();
impl_opaque_keys! {
pub struct SessionKeys {
pub aura: Aura,
}
}
/// The para-id used in this runtime.
pub const TEYRCHAIN_ID: u32 = 100;
#[cfg(feature = "elastic-scaling-500ms")]
pub const BLOCK_PROCESSING_VELOCITY: u32 = 12;
#[cfg(all(feature = "elastic-scaling-multi-block-slot", not(feature = "elastic-scaling-500ms")))]
pub const BLOCK_PROCESSING_VELOCITY: u32 = 6;
#[cfg(all(
any(feature = "elastic-scaling", feature = "relay-parent-offset"),
not(feature = "elastic-scaling-500ms"),
not(feature = "elastic-scaling-multi-block-slot")
))]
pub const BLOCK_PROCESSING_VELOCITY: u32 = 3;
#[cfg(not(any(
feature = "elastic-scaling",
feature = "elastic-scaling-500ms",
feature = "elastic-scaling-multi-block-slot",
feature = "relay-parent-offset",
)))]
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
#[cfg(feature = "async-backing")]
const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
#[cfg(all(feature = "sync-backing", not(feature = "async-backing")))]
const UNINCLUDED_SEGMENT_CAPACITY: u32 = 1;
// The `+2` shouldn't be needed, https://github.com/pezkuwichain/pezkuwi-sdk/issues/160
#[cfg(all(not(feature = "sync-backing"), not(feature = "async-backing")))]
const UNINCLUDED_SEGMENT_CAPACITY: u32 = BLOCK_PROCESSING_VELOCITY * (2 + RELAY_PARENT_OFFSET) + 2;
#[cfg(any(feature = "sync-backing", feature = "elastic-scaling-12s-slot"))]
pub const SLOT_DURATION: u64 = 12000;
#[cfg(not(any(feature = "sync-backing", feature = "elastic-scaling-12s-slot")))]
pub const SLOT_DURATION: u64 = 6000;
const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
// The only difference between the two declarations below is the `spec_version`. With the
// `increment-spec-version` feature enabled `spec_version` should be greater than the one of without
// the `increment-spec-version` feature.
//
// The duplication here is unfortunate necessity.
//
// runtime_version macro is dumb. It accepts a const item declaration, passes it through and
// also emits runtime version custom section. It parses the expressions to extract the version
// details. Since macro kicks in early, it operates on AST. Thus you cannot use constants.
// Macros are expanded top to bottom, meaning we also cannot use `cfg` here.
#[cfg(all(not(feature = "increment-spec-version"), not(feature = "elastic-scaling")))]
#[pezsp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: alloc::borrow::Cow::Borrowed("pezcumulus-test-teyrchain"),
impl_name: alloc::borrow::Cow::Borrowed("pezcumulus-test-teyrchain"),
authoring_version: 1,
// Read the note above.
spec_version: 2,
impl_version: 1,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,
system_version: 1,
};
#[cfg(any(feature = "increment-spec-version", feature = "elastic-scaling"))]
#[pezsp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: alloc::borrow::Cow::Borrowed("pezcumulus-test-teyrchain"),
impl_name: alloc::borrow::Cow::Borrowed("pezcumulus-test-teyrchain"),
authoring_version: 1,
// Read the note above.
spec_version: 3,
impl_version: 1,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,
system_version: 1,
};
pub const EPOCH_DURATION_IN_BLOCKS: u32 = 10 * MINUTES;
// These time units are defined in number of blocks.
pub const MINUTES: BlockNumber = 60_000 / (SLOT_DURATION as BlockNumber);
pub const HOURS: BlockNumber = MINUTES * 60;
pub const DAYS: BlockNumber = HOURS * 24;
// 1 in 4 blocks (on average, not counting collisions) will be primary babe blocks.
pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4);
/// The version information used to identify this runtime when compiled natively.
#[cfg(feature = "std")]
pub fn native_version() -> NativeVersion {
NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
}
/// We assume that ~10% of the block weight is consumed by `on_initialize` handlers.
/// This is used to limit the maximal weight of a single extrinsic.
const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used
/// by Operational extrinsics.
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
/// We allow for 1 second of compute with a 6 second average block time.
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
WEIGHT_REF_TIME_PER_SECOND,
cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
);
parameter_types! {
/// Target number of blocks per relay chain slot.
pub const NumberOfBlocksPerRelaySlot: u32 = 12;
pub const BlockHashCount: BlockNumber = 250;
pub const Version: RuntimeVersion = VERSION;
pub RuntimeBlockLength: BlockLength =
BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
.base_block(BlockExecutionWeight::get())
.for_class(DispatchClass::all(), |weights| {
weights.base_extrinsic = ExtrinsicBaseWeight::get();
})
.for_class(DispatchClass::Normal, |weights| {
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
.for_class(DispatchClass::Operational, |weights| {
weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
// Operational transactions have some extra reserved space, so that they
// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
weights.reserved = Some(
MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
);
})
.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
.build_or_panic();
pub const SS58Prefix: u8 = 42;
}
#[derive_impl(pezframe_system::config_preludes::TeyrchainDefaultConfig)]
impl pezframe_system::Config for Runtime {
/// The identifier used to distinguish between accounts.
type AccountId = AccountId;
/// The index type for storing how many extrinsics an account has signed.
type Nonce = Nonce;
/// The type for hashing blocks and tries.
type Hash = Hash;
/// The block type.
type Block = Block;
/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
type BlockHashCount = BlockHashCount;
/// Runtime version.
type Version = Version;
type AccountData = pezpallet_balances::AccountData<Balance>;
type BlockWeights = RuntimeBlockWeights;
type BlockLength = RuntimeBlockLength;
type SS58Prefix = SS58Prefix;
type OnSetCode = cumulus_pallet_teyrchain_system::TeyrchainSetCode<Self>;
type MaxConsumers = pezframe_support::traits::ConstU32<16>;
type SingleBlockMigrations = SingleBlockMigrations;
}
impl cumulus_pallet_weight_reclaim::Config for Runtime {
type WeightInfo = ();
}
parameter_types! {
pub const MinimumPeriod: u64 = 0;
}
parameter_types! {
pub const PotId: PalletId = PalletId(*b"PotStake");
pub const SessionLength: BlockNumber = 10 * MINUTES;
pub const Offset: u32 = 0;
}
impl cumulus_pallet_aura_ext::Config for Runtime {}
impl pezpallet_timestamp::Config for Runtime {
/// A timestamp: milliseconds since the unix epoch.
type Moment = u64;
type OnTimestampSet = Aura;
type MinimumPeriod = MinimumPeriod;
type WeightInfo = ();
}
parameter_types! {
pub const ExistentialDeposit: u128 = 500;
pub const TransferFee: u128 = 0;
pub const CreationFee: u128 = 0;
pub const TransactionByteFee: u128 = 1;
pub const MaxReserves: u32 = 50;
}
impl pezpallet_balances::Config for Runtime {
/// The type for recording an account's balance.
type Balance = Balance;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type WeightInfo = ();
type MaxLocks = ();
type MaxReserves = MaxReserves;
type ReserveIdentifier = [u8; 8];
type RuntimeHoldReason = RuntimeHoldReason;
type RuntimeFreezeReason = RuntimeFreezeReason;
type FreezeIdentifier = ();
type MaxFreezes = ConstU32<0>;
type DoneSlashHandler = ();
}
impl pezpallet_transaction_payment::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type OnChargeTransaction = pezpallet_transaction_payment::FungibleAdapter<Balances, ()>;
type WeightToFee = IdentityFee<Balance>;
type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
type FeeMultiplierUpdate = ();
type OperationalFeeMultiplier = ConstU8<5>;
type WeightInfo = pezpallet_transaction_payment::weights::BizinikiwiWeight<Runtime>;
}
impl pezpallet_sudo::Config for Runtime {
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = pezpallet_sudo::weights::BizinikiwiWeight<Runtime>;
}
impl pezpallet_glutton::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type AdminOrigin = EnsureRoot<AccountId>;
type WeightInfo = pezpallet_glutton::weights::BizinikiwiWeight<Runtime>;
}
#[cfg(feature = "relay-parent-offset")]
const RELAY_PARENT_OFFSET: u32 = 2;
#[cfg(not(feature = "relay-parent-offset"))]
const RELAY_PARENT_OFFSET: u32 = 0;
type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
Runtime,
RELAY_CHAIN_SLOT_DURATION_MILLIS,
BLOCK_PROCESSING_VELOCITY,
UNINCLUDED_SEGMENT_CAPACITY,
>;
impl cumulus_pallet_teyrchain_system::Config for Runtime {
type WeightInfo = ();
type SelfParaId = teyrchain_info::Pallet<Runtime>;
type RuntimeEvent = RuntimeEvent;
type OnSystemEvent = ();
type OutboundXcmpMessageSource = ();
// Ignore all DMP messages by enqueueing them into `()`:
type DmpQueue = pezframe_support::traits::EnqueueWithOrigin<(), pezsp_core::ConstU8<0>>;
type ReservedDmpWeight = ();
type XcmpMessageHandler = ();
type ReservedXcmpWeight = ();
type CheckAssociatedRelayNumber =
cumulus_pallet_teyrchain_system::RelayNumberMonotonicallyIncreases;
type ConsensusHook = ConsensusHook;
type RelayParentOffset = ConstU32<RELAY_PARENT_OFFSET>;
}
impl teyrchain_info::Config for Runtime {}
impl pezpallet_aura::Config for Runtime {
type AuthorityId = AuraId;
type DisabledValidators = ();
type MaxAuthorities = ConstU32<32>;
#[cfg(feature = "sync-backing")]
type AllowMultipleBlocksPerSlot = ConstBool<false>;
#[cfg(not(feature = "sync-backing"))]
type AllowMultipleBlocksPerSlot = ConstBool<true>;
type SlotDuration = ConstU64<SLOT_DURATION>;
}
impl test_pallet::Config for Runtime {}
construct_runtime! {
pub enum Runtime
{
System: pezframe_system,
TeyrchainSystem: cumulus_pallet_teyrchain_system,
Timestamp: pezpallet_timestamp,
TeyrchainInfo: teyrchain_info,
Balances: pezpallet_balances,
Sudo: pezpallet_sudo,
TransactionPayment: pezpallet_transaction_payment,
TestPallet: test_pallet,
Glutton: pezpallet_glutton,
Aura: pezpallet_aura,
AuraExt: cumulus_pallet_aura_ext,
WeightReclaim: cumulus_pallet_weight_reclaim,
}
}
/// Index of a transaction in the chain.
pub type Nonce = u32;
/// A hash of some data used by the chain.
pub type Hash = pezsp_core::H256;
/// Balance of an account.
pub type Balance = u128;
/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
pub type Signature = MultiSignature;
/// An index to a block.
pub type BlockNumber = u32;
/// Some way of identifying an account on the chain. We intentionally make it equivalent
/// to the public key of our transaction signing scheme.
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
/// Opaque block type.
pub type NodeBlock = generic::Block<Header, pezsp_runtime::OpaqueExtrinsic>;
/// The address format for describing accounts.
pub type Address = MultiAddress<AccountId, ()>;
/// Block header type as expected by this runtime.
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// Block type as expected by this runtime.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// A Block signed with a Justification
pub type SignedBlock = generic::SignedBlock<Block>;
/// BlockId type as expected by this runtime.
pub type BlockId = generic::BlockId<Block>;
/// The extension to the basic transaction logic.
pub type TxExtension = cumulus_pallet_weight_reclaim::StorageWeightReclaim<
Runtime,
(
pezframe_system::AuthorizeCall<Runtime>,
pezframe_system::CheckNonZeroSender<Runtime>,
pezframe_system::CheckSpecVersion<Runtime>,
pezframe_system::CheckGenesis<Runtime>,
pezframe_system::CheckEra<Runtime>,
pezframe_system::CheckNonce<Runtime>,
pezframe_system::CheckWeight<Runtime>,
pezpallet_transaction_payment::ChargeTransactionPayment<Runtime>,
),
>;
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
/// Executive: handles dispatch to the various modules.
pub type Executive = pezframe_executive::Executive<
Runtime,
Block,
pezframe_system::ChainContext<Runtime>,
Runtime,
AllPalletsWithSystem,
>;
/// The payload being signed in transactions.
pub type SignedPayload = generic::SignedPayload<RuntimeCall, TxExtension>;
pub struct SingleBlockMigrations;
impl OnRuntimeUpgrade for SingleBlockMigrations {
fn on_runtime_upgrade() -> pezframe_support::weights::Weight {
assert_eq!(
pezsp_io::storage::get(test_pallet::TEST_RUNTIME_UPGRADE_KEY),
Some(vec![1, 2, 3, 4].into())
);
Weight::from_parts(1, 0)
}
}
decl_runtime_apis! {
pub trait GetLastTimestamp {
/// Returns the last timestamp of a runtime.
fn get_last_timestamp() -> u64;
}
}
impl_runtime_apis! {
impl pezsp_api::Core<Block> for Runtime {
fn version() -> RuntimeVersion {
VERSION
}
fn execute_block(block: <Block as BlockT>::LazyBlock) {
Executive::execute_block(block)
}
fn initialize_block(header: &<Block as BlockT>::Header) -> pezsp_runtime::ExtrinsicInclusionMode {
Executive::initialize_block(header)
}
}
impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
fn can_build_upon(
included_hash: <Block as BlockT>::Hash,
slot: cumulus_primitives_aura::Slot,
) -> bool {
ConsensusHook::can_build_upon(included_hash, slot)
}
}
impl cumulus_primitives_core::RelayParentOffsetApi<Block> for Runtime {
fn relay_parent_offset() -> u32 {
RELAY_PARENT_OFFSET
}
}
impl pezsp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
fn slot_duration() -> pezsp_consensus_aura::SlotDuration {
pezsp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
}
fn authorities() -> Vec<AuraId> {
pezpallet_aura::Authorities::<Runtime>::get().into_inner()
}
}
impl pezsp_api::Metadata<Block> for Runtime {
fn metadata() -> OpaqueMetadata {
OpaqueMetadata::new(Runtime::metadata().into())
}
fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
Runtime::metadata_at_version(version)
}
fn metadata_versions() -> Vec<u32> {
Runtime::metadata_versions()
}
}
impl pezframe_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
fn account_nonce(account: AccountId) -> Nonce {
System::account_nonce(account)
}
}
impl pezsp_block_builder::BlockBuilder<Block> for Runtime {
fn apply_extrinsic(
extrinsic: <Block as BlockT>::Extrinsic,
) -> ApplyExtrinsicResult {
Executive::apply_extrinsic(extrinsic)
}
fn finalize_block() -> <Block as BlockT>::Header {
Executive::finalize_block()
}
fn inherent_extrinsics(data: pezsp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
data.create_extrinsics()
}
fn check_inherents(block: <Block as BlockT>::LazyBlock, data: pezsp_inherents::InherentData) -> pezsp_inherents::CheckInherentsResult {
data.check_extrinsics(&block)
}
}
impl pezsp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
fn validate_transaction(
source: TransactionSource,
tx: <Block as BlockT>::Extrinsic,
block_hash: <Block as BlockT>::Hash,
) -> TransactionValidity {
Executive::validate_transaction(source, tx, block_hash)
}
}
impl pezsp_offchain::OffchainWorkerApi<Block> for Runtime {
fn offchain_worker(header: &<Block as BlockT>::Header) {
Executive::offchain_worker(header)
}
}
impl pezsp_session::SessionKeys<Block> for Runtime {
fn decode_session_keys(
encoded: Vec<u8>,
) -> Option<Vec<(Vec<u8>, pezsp_core::crypto::KeyTypeId)>> {
SessionKeys::decode_into_raw_public_keys(&encoded)
}
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
SessionKeys::generate(seed)
}
}
impl crate::GetLastTimestamp<Block> for Runtime {
fn get_last_timestamp() -> u64 {
Now::<Runtime>::get()
}
}
impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
TeyrchainSystem::collect_collation_info(header)
}
}
impl pezsp_genesis_builder::GenesisBuilder<Block> for Runtime {
fn build_state(config: Vec<u8>) -> pezsp_genesis_builder::Result {
build_state::<RuntimeGenesisConfig>(config)
}
fn get_preset(id: &Option<pezsp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
get_preset::<RuntimeGenesisConfig>(id, genesis_config_presets::get_preset)
}
fn preset_names() -> Vec<pezsp_genesis_builder::PresetId> {
genesis_config_presets::preset_names()
}
}
impl cumulus_primitives_core::GetTeyrchainInfo<Block> for Runtime {
fn teyrchain_id() -> ParaId {
TeyrchainInfo::teyrchain_id()
}
}
impl cumulus_primitives_core::TargetBlockRate<Block> for Runtime {
fn target_block_rate() -> u32 {
1
}
}
}
cumulus_pallet_teyrchain_system::register_validate_block! {
Runtime = Runtime,
BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
}
+123
View File
@@ -0,0 +1,123 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// 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 <http://www.gnu.org/licenses/>.
/// A special pallet that exposes dispatchables that are only useful for testing.
pub use pallet::*;
/// Some key that we set in genesis and only read in [`TestOnRuntimeUpgrade`] to ensure that
/// [`OnRuntimeUpgrade`] works as expected.
pub const TEST_RUNTIME_UPGRADE_KEY: &[u8] = b"+test_runtime_upgrade_key+";
#[pezframe_support::pallet(dev_mode)]
pub mod pallet {
use crate::test_pallet::TEST_RUNTIME_UPGRADE_KEY;
use alloc::vec;
use pezframe_support::pezpallet_prelude::*;
use pezframe_system::pezpallet_prelude::*;
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: pezframe_system::Config + cumulus_pallet_teyrchain_system::Config {}
/// A simple storage map for testing purposes.
#[pallet::storage]
pub type TestMap<T: Config> = StorageMap<_, Twox64Concat, u32, (), ValueQuery>;
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// A test dispatchable for setting a custom head data in `validate_block`.
#[pallet::weight(0)]
pub fn set_custom_validation_head_data(
_: OriginFor<T>,
custom_header: alloc::vec::Vec<u8>,
) -> DispatchResult {
cumulus_pallet_teyrchain_system::Pallet::<T>::set_custom_validation_head_data(
custom_header,
);
Ok(())
}
/// A dispatchable that first reads two values from two different child tries, asserts they
/// are the expected values (if the values exist in the state) and then writes two different
/// values to these child tries.
#[pallet::weight(0)]
pub fn read_and_write_child_tries(_: OriginFor<T>) -> DispatchResult {
let key = &b"hello"[..];
let first_trie = &b"first"[..];
let second_trie = &b"second"[..];
let first_value = "world1".encode();
let second_value = "world2".encode();
if let Some(res) = pezsp_io::default_child_storage::get(first_trie, key) {
assert_eq!(first_value, res);
}
if let Some(res) = pezsp_io::default_child_storage::get(second_trie, key) {
assert_eq!(second_value, res);
}
pezsp_io::default_child_storage::set(first_trie, key, &first_value);
pezsp_io::default_child_storage::set(second_trie, key, &second_value);
Ok(())
}
/// Reads a key and writes a big value under this key.
///
/// At genesis this `key` is empty and thus, will only be set in consequent blocks.
pub fn read_and_write_big_value(_: OriginFor<T>) -> DispatchResult {
let key = &b"really_huge_value"[..];
pezsp_io::storage::get(key);
pezsp_io::storage::set(key, &vec![0u8; 1024 * 1024 * 5]);
Ok(())
}
/// Stores `()` in `TestMap` for keys from 0 up to `max_key`.
#[pallet::weight(0)]
pub fn store_values_in_map(_: OriginFor<T>, max_key: u32) -> DispatchResult {
for i in 0..=max_key {
TestMap::<T>::insert(i, ());
}
Ok(())
}
/// Removes the value associated with `key` from `TestMap`.
#[pallet::weight(0)]
pub fn remove_value_from_map(_: OriginFor<T>, key: u32) -> DispatchResult {
TestMap::<T>::remove(key);
Ok(())
}
}
#[derive(pezframe_support::DefaultNoBound)]
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
#[serde(skip)]
pub _config: core::marker::PhantomData<T>,
}
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
pezsp_io::storage::set(TEST_RUNTIME_UPGRADE_KEY, &[1, 2, 3, 4]);
}
}
}
+179
View File
@@ -0,0 +1,179 @@
[package]
name = "pezcumulus-test-service"
version = "0.1.0"
authors.workspace = true
edition.workspace = true
publish = false
[lints]
workspace = true
[[bin]]
name = "test-teyrchain"
path = "src/main.rs"
[dependencies]
async-trait = { workspace = true }
clap = { features = ["derive"], workspace = true }
codec = { workspace = true, default-features = true }
criterion = { features = [
"async_tokio",
], workspace = true, default-features = true }
jsonrpsee = { features = ["server"], workspace = true }
prometheus = { workspace = true }
rand = { workspace = true, default-features = true }
serde = { features = ["derive"], workspace = true, default-features = true }
serde_json = { workspace = true, default-features = true }
tokio = { features = ["macros"], workspace = true, default-features = true }
tracing = { workspace = true, default-features = true }
url = { workspace = true }
# Bizinikiwi
pezframe-system = { workspace = true, default-features = true }
pezframe-system-rpc-runtime-api = { workspace = true, default-features = true }
pezpallet-transaction-payment = { workspace = true, default-features = true }
pezsc-basic-authorship = { workspace = true, default-features = true }
pezsc-block-builder = { workspace = true, default-features = true }
pezsc-chain-spec = { workspace = true, default-features = true }
pezsc-cli = { workspace = true, default-features = true }
pezsc-client-api = { workspace = true, default-features = true }
pezsc-consensus = { workspace = true, default-features = true }
pezsc-consensus-aura = { workspace = true, default-features = true }
pezsc-executor = { workspace = true, default-features = true }
pezsc-executor-common = { workspace = true, default-features = true }
pezsc-executor-wasmtime = { workspace = true, default-features = true }
pezsc-network = { workspace = true, default-features = true }
pezsc-service = { workspace = true, default-features = true }
pezsc-telemetry = { workspace = true, default-features = true }
pezsc-tracing = { workspace = true, default-features = true }
pezsc-transaction-pool = { workspace = true, default-features = true }
pezsc-transaction-pool-api = { workspace = true, default-features = true }
pezsp-api = { workspace = true, default-features = true }
pezsp-arithmetic = { workspace = true, default-features = true }
pezsp-blockchain = { workspace = true, default-features = true }
pezsp-consensus = { workspace = true, default-features = true }
pezsp-consensus-aura = { workspace = true, default-features = true }
pezsp-core = { workspace = true, default-features = true }
pezsp-genesis-builder = { workspace = true, default-features = true }
pezsp-io = { workspace = true, default-features = true }
pezsp-keyring = { workspace = true, default-features = true }
pezsp-runtime = { workspace = true }
pezsp-state-machine = { workspace = true, default-features = true }
pezsp-timestamp = { workspace = true, default-features = true }
pezsp-tracing = { workspace = true, default-features = true }
bizinikiwi-test-client = { workspace = true }
# Pezkuwi
pezkuwi-cli = { workspace = true, default-features = true }
pezkuwi-node-subsystem = { workspace = true, default-features = true }
pezkuwi-overseer = { workspace = true, default-features = true }
pezkuwi-primitives = { workspace = true, default-features = true }
pezkuwi-service = { workspace = true, default-features = true }
pezkuwi-test-service = { workspace = true }
# Pezcumulus
pezcumulus-client-cli = { workspace = true, default-features = true }
pezcumulus-client-collator = { workspace = true, default-features = true }
pezcumulus-client-consensus-aura = { workspace = true, default-features = true }
pezcumulus-client-consensus-common = { workspace = true, default-features = true }
pezcumulus-client-consensus-proposer = { workspace = true, default-features = true }
pezcumulus-client-pov-recovery = { workspace = true, default-features = true }
pezcumulus-client-service = { workspace = true, default-features = true }
pezcumulus-client-teyrchain-inherent = { workspace = true, default-features = true }
pezcumulus-pezpallet-teyrchain-system = { workspace = true }
pezcumulus-pezpallet-weight-reclaim = { workspace = true, default-features = true }
pezcumulus-primitives-core = { workspace = true, default-features = true }
pezcumulus-relay-chain-inprocess-interface = { workspace = true, default-features = true }
pezcumulus-relay-chain-interface = { workspace = true, default-features = true }
pezcumulus-relay-chain-minimal-node = { workspace = true, default-features = true }
pezcumulus-test-relay-sproof-builder = { workspace = true, default-features = true }
pezcumulus-test-runtime = { workspace = true }
pezpallet-timestamp = { workspace = true, default-features = true }
[dev-dependencies]
pezcumulus-test-client = { workspace = true }
futures = { workspace = true }
[features]
runtime-benchmarks = [
"pezcumulus-client-cli/runtime-benchmarks",
"pezcumulus-client-collator/runtime-benchmarks",
"pezcumulus-client-consensus-aura/runtime-benchmarks",
"pezcumulus-client-consensus-common/runtime-benchmarks",
"pezcumulus-client-consensus-proposer/runtime-benchmarks",
"pezcumulus-client-pov-recovery/runtime-benchmarks",
"pezcumulus-client-service/runtime-benchmarks",
"pezcumulus-client-teyrchain-inherent/runtime-benchmarks",
"pezcumulus-pezpallet-teyrchain-system/runtime-benchmarks",
"pezcumulus-pezpallet-weight-reclaim/runtime-benchmarks",
"pezcumulus-primitives-core/runtime-benchmarks",
"pezcumulus-relay-chain-inprocess-interface/runtime-benchmarks",
"pezcumulus-relay-chain-interface/runtime-benchmarks",
"pezcumulus-relay-chain-minimal-node/runtime-benchmarks",
"pezcumulus-test-client/runtime-benchmarks",
"pezcumulus-test-relay-sproof-builder/runtime-benchmarks",
"pezcumulus-test-runtime/runtime-benchmarks",
"pezframe-system-rpc-runtime-api/runtime-benchmarks",
"pezframe-system/runtime-benchmarks",
"pezpallet-timestamp/runtime-benchmarks",
"pezpallet-transaction-payment/runtime-benchmarks",
"pezkuwi-cli/runtime-benchmarks",
"pezkuwi-node-subsystem/runtime-benchmarks",
"pezkuwi-overseer/runtime-benchmarks",
"pezkuwi-primitives/runtime-benchmarks",
"pezkuwi-service/runtime-benchmarks",
"pezkuwi-test-service/runtime-benchmarks",
"pezsc-basic-authorship/runtime-benchmarks",
"pezsc-block-builder/runtime-benchmarks",
"pezsc-chain-spec/runtime-benchmarks",
"pezsc-cli/runtime-benchmarks",
"pezsc-client-api/runtime-benchmarks",
"pezsc-consensus-aura/runtime-benchmarks",
"pezsc-consensus/runtime-benchmarks",
"pezsc-executor-wasmtime/runtime-benchmarks",
"pezsc-executor/runtime-benchmarks",
"pezsc-network/runtime-benchmarks",
"pezsc-service/runtime-benchmarks",
"pezsc-tracing/runtime-benchmarks",
"pezsc-transaction-pool-api/runtime-benchmarks",
"pezsc-transaction-pool/runtime-benchmarks",
"pezsp-api/runtime-benchmarks",
"pezsp-blockchain/runtime-benchmarks",
"pezsp-consensus-aura/runtime-benchmarks",
"pezsp-consensus/runtime-benchmarks",
"pezsp-genesis-builder/runtime-benchmarks",
"pezsp-io/runtime-benchmarks",
"pezsp-keyring/runtime-benchmarks",
"pezsp-runtime/runtime-benchmarks",
"pezsp-state-machine/runtime-benchmarks",
"pezsp-timestamp/runtime-benchmarks",
"bizinikiwi-test-client/runtime-benchmarks",
]
[[bench]]
name = "transaction_throughput"
harness = false
[[bench]]
name = "block_import"
harness = false
[[bench]]
name = "block_production"
harness = false
[[bench]]
name = "block_production_glutton"
harness = false
[[bench]]
name = "block_import_glutton"
harness = false
[[bench]]
name = "validate_block"
harness = false
[[bench]]
name = "validate_block_glutton"
harness = false
@@ -0,0 +1,101 @@
// This file is part of Pezcumulus.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use criterion::{criterion_group, criterion_main, BatchSize, Criterion, Throughput};
use pezsc_block_builder::BlockBuilderBuilder;
use pezsc_client_api::UsageProvider;
use core::time::Duration;
use cumulus_primitives_core::ParaId;
use pezsp_api::{Core, ProvideRuntimeApi};
use pezsp_keyring::Sr25519Keyring::{Alice, Bob};
use cumulus_test_service::bench_utils as utils;
fn benchmark_block_import(c: &mut Criterion) {
pezsp_tracing::try_init_simple();
let runtime = tokio::runtime::Runtime::new().expect("creating tokio runtime doesn't fail; qed");
let para_id = ParaId::from(cumulus_test_runtime::TEYRCHAIN_ID);
let tokio_handle = runtime.handle();
// Create enough accounts to fill the block with transactions.
// Each account should only be included in one transfer.
let (src_accounts, dst_accounts, account_ids) = utils::create_benchmark_accounts();
for bench_parameters in &[(true, Alice), (false, Bob)] {
let node = runtime.block_on(
cumulus_test_service::TestNodeBuilder::new(
para_id,
tokio_handle.clone(),
bench_parameters.1,
)
// Preload all accounts with funds for the transfers
.endowed_accounts(account_ids.clone())
.import_proof_recording(bench_parameters.0)
.build(),
);
let client = node.client;
let backend = node.backend;
let (max_transfer_count, extrinsics) =
utils::create_benchmarking_transfer_extrinsics(&client, &src_accounts, &dst_accounts);
let parent_hash = client.usage_info().chain.best_hash;
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(parent_hash)
.fetch_parent_block_number(&*client)
.unwrap()
.build()
.unwrap();
for extrinsic in extrinsics {
block_builder.push(extrinsic).unwrap();
}
let benchmark_block = block_builder.build().unwrap();
let mut group = c.benchmark_group("Block import");
group.sample_size(20);
group.measurement_time(Duration::from_secs(120));
group.throughput(Throughput::Elements(max_transfer_count as u64));
group.bench_function(
format!(
"(transfers = {max_transfer_count}, proof_recording = {}) block import",
bench_parameters.0
),
|b| {
b.iter_batched(
|| {
backend.reset_trie_cache();
benchmark_block.block.clone()
},
|block| {
client.runtime_api().execute_block(parent_hash, block.into()).unwrap();
},
BatchSize::SmallInput,
)
},
);
}
}
criterion_group!(benches, benchmark_block_import);
criterion_main!(benches);
@@ -0,0 +1,112 @@
// This file is part of Pezcumulus.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
use pezsp_api::{Core, ProvideRuntimeApi};
use pezsp_arithmetic::{
traits::{One, Zero},
FixedPointNumber,
};
use core::time::Duration;
use cumulus_primitives_core::ParaId;
use pezsc_block_builder::BlockBuilderBuilder;
use pezsp_keyring::Sr25519Keyring::{Alice, Bob, Charlie, Ferdie};
use cumulus_test_service::bench_utils as utils;
fn benchmark_block_import(c: &mut Criterion) {
pezsp_tracing::try_init_simple();
let runtime = tokio::runtime::Runtime::new().expect("creating tokio runtime doesn't fail; qed");
let para_id = ParaId::from(100);
let tokio_handle = runtime.handle();
let mut initialize_glutton_pallet = true;
for (compute_ratio, storage_ratio, proof_on_import, keyring_identity) in &[
(One::one(), Zero::zero(), true, Alice),
(One::one(), One::one(), true, Bob),
(One::one(), Zero::zero(), false, Charlie),
(One::one(), One::one(), false, Ferdie),
] {
let node = runtime.block_on(
cumulus_test_service::TestNodeBuilder::new(
para_id,
tokio_handle.clone(),
*keyring_identity,
)
.import_proof_recording(*proof_on_import)
.build(),
);
let client = node.client;
let backend = node.backend;
let mut group = c.benchmark_group("Block import");
group.sample_size(20);
group.measurement_time(Duration::from_secs(120));
let block = utils::set_glutton_parameters(
&client,
initialize_glutton_pallet,
compute_ratio,
storage_ratio,
);
initialize_glutton_pallet = false;
runtime.block_on(utils::import_block(&client, &block, false));
// Build the block we will use for benchmarking
let parent_hash = client.chain_info().best_hash;
let parent_header = client.header(parent_hash).expect("Just fetched this hash.").unwrap();
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(parent_hash)
.fetch_parent_block_number(&*client)
.unwrap()
.build()
.unwrap();
block_builder
.push(utils::extrinsic_set_validation_data(parent_header.clone()).clone())
.unwrap();
block_builder.push(utils::extrinsic_set_time(&client)).unwrap();
let benchmark_block = block_builder.build().unwrap();
group.bench_function(
format!(
"(compute = {:?} %, storage = {:?} %) block import",
compute_ratio.saturating_mul_int(100),
storage_ratio.saturating_mul_int(100)
),
|b| {
b.iter_batched(
|| {
backend.reset_trie_cache();
benchmark_block.block.clone()
},
|block| {
client.runtime_api().execute_block(parent_hash, block.into()).unwrap();
},
BatchSize::SmallInput,
)
},
);
}
}
criterion_group!(benches, benchmark_block_import);
criterion_main!(benches);
@@ -0,0 +1,122 @@
// This file is part of Pezcumulus.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use criterion::{criterion_group, criterion_main, BatchSize, Criterion, Throughput};
use pezsc_client_api::UsageProvider;
use core::time::Duration;
use cumulus_primitives_core::ParaId;
use pezsc_block_builder::BlockBuilderBuilder;
use pezsp_keyring::Sr25519Keyring::Alice;
use cumulus_test_service::bench_utils as utils;
fn benchmark_block_production(c: &mut Criterion) {
pezsp_tracing::try_init_simple();
let runtime = tokio::runtime::Runtime::new().expect("creating tokio runtime doesn't fail; qed");
let tokio_handle = runtime.handle();
// Create enough accounts to fill the block with transactions.
// Each account should only be included in one transfer.
let (src_accounts, dst_accounts, account_ids) = utils::create_benchmark_accounts();
let para_id = ParaId::from(100);
let alice = runtime.block_on(
cumulus_test_service::TestNodeBuilder::new(para_id, tokio_handle.clone(), Alice)
// Preload all accounts with funds for the transfers
.endowed_accounts(account_ids)
.build(),
);
let client = alice.client;
let parent_hash = client.usage_info().chain.best_hash;
let parent_header = client.header(parent_hash).expect("Just fetched this hash.").unwrap();
let set_validation_data_extrinsic = utils::extrinsic_set_validation_data(parent_header);
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap();
block_builder.push(utils::extrinsic_set_time(&client)).unwrap();
block_builder.push(set_validation_data_extrinsic).unwrap();
let built_block = block_builder.build().unwrap();
runtime.block_on(utils::import_block(&client, &built_block.block, false));
let (max_transfer_count, extrinsics) =
utils::create_benchmarking_transfer_extrinsics(&client, &src_accounts, &dst_accounts);
let mut group = c.benchmark_group("Block production");
group.sample_size(20);
group.measurement_time(Duration::from_secs(120));
group.throughput(Throughput::Elements(max_transfer_count as u64));
let chain = client.chain_info();
group.bench_function(
format!("(proof = true, transfers = {}) block production", max_transfer_count),
|b| {
b.iter_batched(
|| extrinsics.clone(),
|extrinsics| {
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(chain.best_hash)
.with_parent_block_number(chain.best_number)
.enable_proof_recording()
.build()
.unwrap();
for extrinsic in extrinsics {
block_builder.push(extrinsic).unwrap();
}
block_builder.build().unwrap()
},
BatchSize::SmallInput,
)
},
);
group.bench_function(
format!("(proof = false, transfers = {}) block production", max_transfer_count),
|b| {
b.iter_batched(
|| extrinsics.clone(),
|extrinsics| {
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(chain.best_hash)
.with_parent_block_number(chain.best_number)
.build()
.unwrap();
for extrinsic in extrinsics {
block_builder.push(extrinsic).unwrap();
}
block_builder.build().unwrap()
},
BatchSize::SmallInput,
)
},
);
}
criterion_group!(benches, benchmark_block_production);
criterion_main!(benches);
@@ -0,0 +1,120 @@
// This file is part of Pezcumulus.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
use pezsp_arithmetic::{
traits::{One, Zero},
FixedPointNumber,
};
use core::time::Duration;
use cumulus_primitives_core::ParaId;
use pezsc_block_builder::BlockBuilderBuilder;
use pezsp_keyring::Sr25519Keyring::Alice;
use cumulus_test_service::bench_utils as utils;
fn benchmark_block_production_compute(c: &mut Criterion) {
pezsp_tracing::try_init_simple();
let runtime = tokio::runtime::Runtime::new().expect("creating tokio runtime doesn't fail; qed");
let tokio_handle = runtime.handle();
let para_id = ParaId::from(100);
let alice = runtime.block_on(
cumulus_test_service::TestNodeBuilder::new(para_id, tokio_handle.clone(), Alice).build(),
);
let client = alice.client;
let mut group = c.benchmark_group("Block production");
group.sample_size(20);
group.measurement_time(Duration::from_secs(120));
let mut initialize_glutton_pallet = true;
for (compute_ratio, storage_ratio) in &[(One::one(), Zero::zero()), (One::one(), One::one())] {
let block = utils::set_glutton_parameters(
&client,
initialize_glutton_pallet,
compute_ratio,
storage_ratio,
);
runtime.block_on(utils::import_block(&client, &block, false));
initialize_glutton_pallet = false;
let best_hash = client.chain_info().best_hash;
let best_number = client.chain_info().best_number;
let parent_header = client.header(best_hash).expect("Just fetched this hash.").unwrap();
let set_validation_data_extrinsic = utils::extrinsic_set_validation_data(parent_header);
let set_time_extrinsic = utils::extrinsic_set_time(&client);
group.bench_function(
format!(
"(compute = {:?} %, storage = {:?} %) block import",
compute_ratio.saturating_mul_int(100),
storage_ratio.saturating_mul_int(100)
),
|b| {
b.iter_batched(
|| (set_validation_data_extrinsic.clone(), set_time_extrinsic.clone()),
|(validation_data, time)| {
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(best_hash)
.with_parent_block_number(best_number)
.enable_proof_recording()
.build()
.unwrap();
block_builder.push(validation_data).unwrap();
block_builder.push(time).unwrap();
block_builder.build().unwrap()
},
BatchSize::SmallInput,
)
},
);
group.bench_function(
format!(
"(compute = {:?} %, storage = {:?} %) block import",
compute_ratio.saturating_mul_int(100),
storage_ratio.saturating_mul_int(100)
),
|b| {
b.iter_batched(
|| (set_validation_data_extrinsic.clone(), set_time_extrinsic.clone()),
|(validation_data, time)| {
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(best_hash)
.with_parent_block_number(best_number)
.build()
.unwrap();
block_builder.push(validation_data).unwrap();
block_builder.push(time).unwrap();
block_builder.build().unwrap()
},
BatchSize::SmallInput,
)
},
);
}
}
criterion_group!(benches, benchmark_block_production_compute);
criterion_main!(benches);
@@ -0,0 +1,246 @@
// This file is part of Pezcumulus.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program 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.
// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
use criterion::{criterion_group, criterion_main, BatchSize, Criterion, Throughput};
use cumulus_client_cli::get_raw_genesis_header;
use cumulus_test_runtime::{AccountId, BalancesCall, ExistentialDeposit, SudoCall};
use futures::{future, StreamExt};
use pezsc_transaction_pool_api::{TransactionPool as _, TransactionSource, TransactionStatus};
use pezsp_core::{crypto::Pair, sr25519};
use pezsp_runtime::OpaqueExtrinsic;
use cumulus_primitives_core::ParaId;
use cumulus_test_service::{construct_extrinsic, fetch_nonce, Client, Keyring::*, TransactionPool};
use pezkuwi_primitives::HeadData;
fn create_accounts(num: usize) -> Vec<sr25519::Pair> {
(0..num)
.map(|i| {
Pair::from_string(&format!("{}/{}", Alice.to_seed(), i), None)
.expect("Creates account pair")
})
.collect()
}
/// Create the extrinsics that will initialize the accounts from the sudo account (Alice).
///
/// `start_nonce` is the current nonce of Alice.
fn create_account_extrinsics(client: &Client, accounts: &[sr25519::Pair]) -> Vec<OpaqueExtrinsic> {
let start_nonce = fetch_nonce(client, Alice.public());
accounts
.iter()
.enumerate()
.flat_map(|(i, a)| {
vec![
// Reset the nonce by removing any funds
construct_extrinsic(
client,
SudoCall::sudo {
call: Box::new(
BalancesCall::force_set_balance {
who: AccountId::from(a.public()).into(),
new_free: 0,
}
.into(),
),
},
Alice.pair(),
Some(start_nonce + (i as u32) * 2),
),
// Give back funds
construct_extrinsic(
client,
SudoCall::sudo {
call: Box::new(
BalancesCall::force_set_balance {
who: AccountId::from(a.public()).into(),
new_free: 1_000_000_000_000 * ExistentialDeposit::get(),
}
.into(),
),
},
Alice.pair(),
Some(start_nonce + (i as u32) * 2 + 1),
),
]
})
.map(OpaqueExtrinsic::from)
.collect()
}
fn create_benchmark_extrinsics(
client: &Client,
accounts: &[sr25519::Pair],
extrinsics_per_account: usize,
) -> Vec<OpaqueExtrinsic> {
accounts
.iter()
.flat_map(|account| {
(0..extrinsics_per_account).map(move |nonce| {
construct_extrinsic(
client,
BalancesCall::transfer_allow_death {
dest: Bob.to_account_id().into(),
value: ExistentialDeposit::get(),
},
account.clone(),
Some(nonce as u32),
)
})
})
.map(OpaqueExtrinsic::from)
.collect()
}
async fn submit_tx_and_wait_for_inclusion(
tx_pool: &TransactionPool,
tx: OpaqueExtrinsic,
client: &Client,
wait_for_finalized: bool,
) {
let best_hash = client.chain_info().best_hash;
let mut watch = tx_pool
.submit_and_watch(best_hash, TransactionSource::External, tx.clone())
.await
.expect("Submits tx to pool")
.fuse();
loop {
match watch.select_next_some().await {
TransactionStatus::Finalized(_) => break,
TransactionStatus::InBlock(_) if !wait_for_finalized => break,
_ => {},
}
}
}
fn transaction_throughput_benchmarks(c: &mut Criterion) {
pezsp_tracing::try_init_simple();
let mut builder = pezsc_cli::LoggerBuilder::new("");
builder.with_colors(false);
let _ = builder.init();
let para_id = ParaId::from(100);
let runtime = tokio::runtime::Runtime::new().expect("Creates tokio runtime");
let tokio_handle = runtime.handle();
// Start alice
let alice = cumulus_test_service::run_relay_chain_validator_node(
tokio_handle.clone(),
Alice,
|| {},
vec![],
None,
);
// Start bob
let bob = cumulus_test_service::run_relay_chain_validator_node(
tokio_handle.clone(),
Bob,
|| {},
vec![alice.addr.clone()],
None,
);
// Run charlie as teyrchain collator
let charlie = runtime.block_on(
cumulus_test_service::TestNodeBuilder::new(para_id, tokio_handle.clone(), Charlie)
.enable_collator()
.connect_to_relay_chain_nodes(vec![&alice, &bob])
.build(),
);
// Register teyrchain
runtime
.block_on(
alice.register_teyrchain(
para_id,
cumulus_test_service::runtime::WASM_BINARY
.expect("You need to build the WASM binary to run this test!")
.to_vec(),
HeadData(
get_raw_genesis_header(charlie.client.clone())
.expect("Unable to get genesis HeadData."),
),
),
)
.unwrap();
// Run dave as teyrchain collator
let dave = runtime.block_on(
cumulus_test_service::TestNodeBuilder::new(para_id, tokio_handle.clone(), Dave)
.enable_collator()
.connect_to_teyrchain_node(&charlie)
.connect_to_relay_chain_nodes(vec![&alice, &bob])
.build(),
);
runtime.block_on(dave.wait_for_blocks(1));
let mut group = c.benchmark_group("Transaction pool");
let account_num = 10;
let extrinsics_per_account = 20;
group.sample_size(10);
group.throughput(Throughput::Elements(account_num as u64 * extrinsics_per_account as u64));
let accounts = create_accounts(account_num);
let mut counter = 1;
let benchmark_handle = tokio_handle.clone();
group.bench_function(
format!("{} transfers from {} accounts", account_num * extrinsics_per_account, account_num),
|b| {
b.iter_batched(
|| {
let prepare_extrinsics = create_account_extrinsics(&dave.client, &accounts);
benchmark_handle.block_on(future::join_all(
prepare_extrinsics.into_iter().map(|tx| {
submit_tx_and_wait_for_inclusion(
&dave.transaction_pool,
tx,
&dave.client,
true,
)
}),
));
create_benchmark_extrinsics(&dave.client, &accounts, extrinsics_per_account)
},
|extrinsics| {
benchmark_handle.block_on(future::join_all(extrinsics.into_iter().map(|tx| {
submit_tx_and_wait_for_inclusion(
&dave.transaction_pool,
tx,
&dave.client,
false,
)
})));
println!("Finished {}", counter);
counter += 1;
},
BatchSize::SmallInput,
)
},
);
}
criterion_group!(benches, transaction_throughput_benchmarks);
criterion_main!(benches);
@@ -0,0 +1,180 @@
// This file is part of Pezcumulus.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use codec::{Decode, Encode};
use core::time::Duration;
use criterion::{criterion_group, criterion_main, BatchSize, Criterion, Throughput};
use cumulus_primitives_core::{
relay_chain::AccountId, ParaId, PersistedValidationData, ValidationParams,
};
use cumulus_test_client::{
generate_extrinsic_with_pair, BuildTeyrchainBlockData, InitBlockBuilder, TestClientBuilder,
ValidationResult,
};
use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
use cumulus_test_runtime::{BalancesCall, Block, Header, UncheckedExtrinsic};
use cumulus_test_service::bench_utils as utils;
use pezkuwi_primitives::HeadData;
use pezsc_block_builder::BlockBuilderBuilder;
use pezsc_client_api::UsageProvider;
use pezsc_executor_common::wasm_runtime::WasmModule;
use pezsp_blockchain::{ApplyExtrinsicFailed::Validity, Error::ApplyExtrinsicFailed};
use pezsp_core::{sr25519, Pair};
use pezsp_runtime::{
traits::Header as HeaderT,
transaction_validity::{InvalidTransaction, TransactionValidityError},
};
fn create_extrinsics(
client: &cumulus_test_client::Client,
src_accounts: &[sr25519::Pair],
dst_accounts: &[sr25519::Pair],
) -> (usize, Vec<UncheckedExtrinsic>) {
// Add as many transfer extrinsics as possible into a single block.
let mut block_builder = BlockBuilderBuilder::new(client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap();
let mut max_transfer_count = 0;
let mut extrinsics = Vec::new();
for (src, dst) in src_accounts.iter().zip(dst_accounts.iter()) {
let extrinsic: UncheckedExtrinsic = generate_extrinsic_with_pair(
client,
src.clone(),
BalancesCall::transfer_keep_alive {
dest: AccountId::from(dst.public()).into(),
value: 10000,
},
None,
);
match block_builder.push(extrinsic.clone()) {
Ok(_) => {},
Err(ApplyExtrinsicFailed(Validity(TransactionValidityError::Invalid(
InvalidTransaction::ExhaustsResources,
)))) => break,
Err(error) => panic!("{}", error),
}
extrinsics.push(extrinsic);
max_transfer_count += 1;
}
(max_transfer_count, extrinsics)
}
fn benchmark_block_validation(c: &mut Criterion) {
pezsp_tracing::try_init_simple();
// Create enough accounts to fill the block with transactions.
// Each account should only be included in one transfer.
let (src_accounts, dst_accounts, account_ids) = utils::create_benchmark_accounts();
let para_id = ParaId::from(cumulus_test_runtime::TEYRCHAIN_ID);
let mut test_client_builder = TestClientBuilder::with_default_backend();
let genesis_init = test_client_builder.genesis_init_mut();
*genesis_init =
cumulus_test_client::GenesisParameters { endowed_accounts: account_ids, wasm: None };
let client = test_client_builder.build_with_native_executor(None).0;
let (max_transfer_count, extrinsics) = create_extrinsics(&client, &src_accounts, &dst_accounts);
let parent_hash = client.usage_info().chain.best_hash;
let parent_header = client.header(parent_hash).expect("Just fetched this hash.").unwrap();
let validation_data = PersistedValidationData {
relay_parent_number: 1,
parent_head: parent_header.encode().into(),
..Default::default()
};
let sproof_builder = RelayStateSproofBuilder {
included_para_head: Some(parent_header.clone().encode().into()),
para_id,
..Default::default()
};
let cumulus_test_client::BlockBuilderAndSupportData { mut block_builder, .. } =
client.init_block_builder(Some(validation_data), sproof_builder.clone());
for extrinsic in extrinsics {
block_builder.push(extrinsic).unwrap();
}
let teyrchain_block = block_builder.build_teyrchain_block(*parent_header.state_root());
let proof_size_in_kb = teyrchain_block.proof().encoded_size() as f64 / 1024f64;
let runtime = utils::get_wasm_module();
let (relay_parent_storage_root, _) = sproof_builder.into_state_root_and_proof();
let encoded_params = ValidationParams {
block_data: cumulus_test_client::BlockData(teyrchain_block.encode()),
parent_head: HeadData(parent_header.encode()),
relay_parent_number: 1,
relay_parent_storage_root,
}
.encode();
// This is not strictly necessary for this benchmark, but
// let us make sure that the result of `validate_block` is what
// we expect.
verify_expected_result(&runtime, &encoded_params, teyrchain_block.blocks()[0].clone());
let mut group = c.benchmark_group("Block validation");
group.sample_size(20);
group.measurement_time(Duration::from_secs(120));
group.throughput(Throughput::Elements(max_transfer_count as u64));
group.bench_function(
format!(
"(transfers = {}, proof_size = {}kb) block validation",
max_transfer_count, proof_size_in_kb
),
|b| {
b.iter_batched(
|| runtime.new_instance().unwrap(),
|mut instance| {
instance.call_export("validate_block", &encoded_params).unwrap();
},
BatchSize::SmallInput,
)
},
);
}
fn verify_expected_result(
runtime: &Box<dyn WasmModule>,
encoded_params: &[u8],
teyrchain_block: Block,
) {
let res = runtime
.new_instance()
.unwrap()
.call_export("validate_block", encoded_params)
.expect("Call `validate_block`.");
let validation_result =
ValidationResult::decode(&mut &res[..]).expect("Decode `ValidationResult`.");
let header =
Header::decode(&mut &validation_result.head_data.0[..]).expect("Decodes `Header`.");
assert_eq!(teyrchain_block.header, header);
}
criterion_group!(benches, benchmark_block_validation);
criterion_main!(benches);
@@ -0,0 +1,212 @@
// This file is part of Pezcumulus.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use codec::{Decode, Encode};
use core::time::Duration;
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
use cumulus_primitives_core::{relay_chain::AccountId, PersistedValidationData, ValidationParams};
use cumulus_test_client::{
generate_extrinsic_with_pair, BlockBuilderAndSupportData, BuildTeyrchainBlockData, Client,
InitBlockBuilder, TestClientBuilder, TeyrchainBlockData, ValidationResult,
};
use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
use cumulus_test_runtime::{Block, GluttonCall, Header, SudoCall};
use pezkuwi_primitives::HeadData;
use pezsc_client_api::UsageProvider;
use pezsc_consensus::{BlockImport, BlockImportParams, ForkChoiceStrategy, ImportResult, StateAction};
use pezsc_executor_common::wasm_runtime::WasmModule;
use pezsp_api::ProvideRuntimeApi;
use pezframe_system_rpc_runtime_api::AccountNonceApi;
use pezsp_arithmetic::{
traits::{One, Zero},
FixedU64,
};
use pezsp_consensus::BlockOrigin;
use pezsp_keyring::Sr25519Keyring::Alice;
use pezsp_runtime::traits::Header as HeaderT;
use cumulus_test_service::bench_utils as utils;
async fn import_block(
client: &cumulus_test_client::Client,
built: cumulus_test_runtime::Block,
import_existing: bool,
) {
let mut params = BlockImportParams::new(BlockOrigin::File, built.header.clone());
params.body = Some(built.extrinsics.clone());
params.state_action = StateAction::Execute;
params.fork_choice = Some(ForkChoiceStrategy::LongestChain);
params.import_existing = import_existing;
let import_result = client.import_block(params).await;
assert!(matches!(import_result, Ok(ImportResult::Imported(_))));
}
fn benchmark_block_validation(c: &mut Criterion) {
pezsp_tracing::try_init_simple();
let runtime = tokio::runtime::Runtime::new().expect("creating tokio runtime doesn't fail; qed");
let endowed_accounts = vec![AccountId::from(Alice.public())];
let mut test_client_builder = TestClientBuilder::with_default_backend();
let genesis_init = test_client_builder.genesis_init_mut();
*genesis_init = cumulus_test_client::GenesisParameters { endowed_accounts, wasm: None };
let client = test_client_builder.build_with_native_executor(None).0;
let mut group = c.benchmark_group("Block validation");
group.sample_size(20);
group.measurement_time(Duration::from_secs(120));
// In the first iteration we want to initialize the glutton pallet.
let mut is_first = true;
for (compute_ratio, storage_ratio) in &[(One::one(), Zero::zero()), (One::one(), One::one())] {
let teyrchain_block =
set_glutton_parameters(&client, is_first, compute_ratio, storage_ratio);
is_first = false;
runtime.block_on(import_block(&client, teyrchain_block.blocks()[0].clone(), false));
// Build benchmark block
let parent_hash = client.usage_info().chain.best_hash;
let parent_header = client.header(parent_hash).expect("Just fetched this hash.").unwrap();
let validation_data = PersistedValidationData {
relay_parent_number: 1,
parent_head: parent_header.encode().into(),
..Default::default()
};
let BlockBuilderAndSupportData { block_builder, .. } =
client.init_block_builder(Some(validation_data), Default::default());
let teyrchain_block = block_builder.build_teyrchain_block(*parent_header.state_root());
let proof_size_in_kb = teyrchain_block.proof().encoded_size() as f64 / 1024f64;
runtime.block_on(import_block(&client, teyrchain_block.blocks()[0].clone(), false));
let runtime = utils::get_wasm_module();
let sproof_builder: RelayStateSproofBuilder = Default::default();
let (relay_parent_storage_root, _) = sproof_builder.clone().into_state_root_and_proof();
let encoded_params = ValidationParams {
block_data: cumulus_test_client::BlockData(teyrchain_block.clone().encode()),
parent_head: HeadData(parent_header.encode()),
relay_parent_number: 1,
relay_parent_storage_root,
}
.encode();
// This is not strictly necessary for this benchmark, but
// let us make sure that the result of `validate_block` is what
// we expect.
verify_expected_result(&runtime, &encoded_params, teyrchain_block.blocks()[0].clone());
group.bench_function(
format!(
"(compute = {:?}, storage = {:?}, proof_size = {}kb) block validation",
compute_ratio, storage_ratio, proof_size_in_kb
),
|b| {
b.iter_batched(
|| runtime.new_instance().unwrap(),
|mut instance| {
instance.call_export("validate_block", &encoded_params).unwrap();
},
BatchSize::SmallInput,
)
},
);
}
}
fn verify_expected_result(runtime: &Box<dyn WasmModule>, encoded_params: &[u8], block: Block) {
let res = runtime
.new_instance()
.unwrap()
.call_export("validate_block", encoded_params)
.expect("Call `validate_block`.");
let validation_result =
ValidationResult::decode(&mut &res[..]).expect("Decode `ValidationResult`.");
let header =
Header::decode(&mut &validation_result.head_data.0[..]).expect("Decodes `Header`.");
assert_eq!(block.header, header);
}
fn set_glutton_parameters(
client: &Client,
initialize: bool,
compute_ratio: &FixedU64,
storage_ratio: &FixedU64,
) -> TeyrchainBlockData {
let parent_hash = client.usage_info().chain.best_hash;
let parent_header = client.header(parent_hash).expect("Just fetched this hash.").unwrap();
let mut last_nonce = client
.runtime_api()
.account_nonce(parent_hash, Alice.into())
.expect("Fetching account nonce works; qed");
let validation_data = PersistedValidationData {
relay_parent_number: 1,
parent_head: parent_header.encode().into(),
..Default::default()
};
let mut extrinsics = vec![];
if initialize {
extrinsics.push(generate_extrinsic_with_pair(
client,
Alice.into(),
SudoCall::sudo {
call: Box::new(
GluttonCall::initialize_pallet { new_count: 5000, witness_count: None }.into(),
),
},
Some(last_nonce),
));
last_nonce += 1;
}
let set_compute = generate_extrinsic_with_pair(
client,
Alice.into(),
SudoCall::sudo {
call: Box::new(GluttonCall::set_compute { compute: *compute_ratio }.into()),
},
Some(last_nonce),
);
last_nonce += 1;
extrinsics.push(set_compute);
let set_storage = generate_extrinsic_with_pair(
client,
Alice.into(),
SudoCall::sudo {
call: Box::new(GluttonCall::set_storage { storage: *storage_ratio }.into()),
},
Some(last_nonce),
);
extrinsics.push(set_storage);
let BlockBuilderAndSupportData { mut block_builder, .. } =
client.init_block_builder(Some(validation_data), Default::default());
for extrinsic in extrinsics {
block_builder.push(extrinsic).unwrap();
}
block_builder.build_teyrchain_block(*parent_header.state_root())
}
criterion_group!(benches, benchmark_block_validation);
criterion_main!(benches);
+287
View File
@@ -0,0 +1,287 @@
// This file is part of Pezcumulus.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use codec::Encode;
use pezsc_block_builder::BlockBuilderBuilder;
use crate::{construct_extrinsic, Client as TestClient};
use cumulus_pallet_teyrchain_system::teyrchain_inherent::{
BasicTeyrchainInherentData, InboundMessagesData,
};
use cumulus_primitives_core::{relay_chain::AccountId, PersistedValidationData};
use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
use cumulus_test_runtime::{
BalancesCall, GluttonCall, NodeBlock, SudoCall, UncheckedExtrinsic, WASM_BINARY,
};
use pezframe_system_rpc_runtime_api::AccountNonceApi;
use pezkuwi_primitives::HeadData;
use pezsc_client_api::UsageProvider;
use pezsc_consensus::{
block_import::{BlockImportParams, ForkChoiceStrategy},
BlockImport, ImportResult, StateAction,
};
use pezsc_executor::DEFAULT_HEAP_ALLOC_STRATEGY;
use pezsc_executor_common::runtime_blob::RuntimeBlob;
use pezsp_api::ProvideRuntimeApi;
use pezsp_blockchain::{ApplyExtrinsicFailed::Validity, Error::ApplyExtrinsicFailed};
use pezsp_consensus::BlockOrigin;
use pezsp_core::{sr25519, Pair};
use pezsp_keyring::Sr25519Keyring::Alice;
use pezsp_runtime::{
transaction_validity::{InvalidTransaction, TransactionValidityError},
AccountId32, FixedU64, MultiAddress, OpaqueExtrinsic,
};
/// Accounts to use for transfer transactions. Enough for 5000 transactions.
const NUM_ACCOUNTS: usize = 10000;
/// Create accounts by deriving from Alice
pub fn create_benchmark_accounts() -> (Vec<sr25519::Pair>, Vec<sr25519::Pair>, Vec<AccountId32>) {
let accounts: Vec<sr25519::Pair> = (0..NUM_ACCOUNTS)
.map(|idx| {
Pair::from_string(&format!("{}/{}", Alice.to_seed(), idx), None)
.expect("Creates account pair")
})
.collect();
let account_ids = accounts
.iter()
.map(|account| AccountId::from(account.public()))
.collect::<Vec<AccountId>>();
let (src_accounts, dst_accounts) = accounts.split_at(NUM_ACCOUNTS / 2);
(src_accounts.to_vec(), dst_accounts.to_vec(), account_ids)
}
/// Create a timestamp extrinsic ahead by `MinimumPeriod` of the last known timestamp
pub fn extrinsic_set_time(client: &TestClient) -> OpaqueExtrinsic {
let best_number = client.usage_info().chain.best_number;
let timestamp = best_number as u64 * cumulus_test_runtime::MinimumPeriod::get();
cumulus_test_runtime::UncheckedExtrinsic::new_bare(
cumulus_test_runtime::RuntimeCall::Timestamp(pezpallet_timestamp::Call::set {
now: timestamp,
}),
)
.into()
}
/// Create a set validation data extrinsic
pub fn extrinsic_set_validation_data(
parent_header: cumulus_test_runtime::Header,
) -> OpaqueExtrinsic {
let parent_head = HeadData(parent_header.encode());
let sproof_builder = RelayStateSproofBuilder {
para_id: cumulus_test_runtime::TEYRCHAIN_ID.into(),
included_para_head: parent_head.clone().into(),
..Default::default()
};
let (relay_parent_storage_root, relay_chain_state) = sproof_builder.into_state_root_and_proof();
let data = BasicTeyrchainInherentData {
validation_data: PersistedValidationData {
parent_head,
relay_parent_number: 10,
relay_parent_storage_root,
max_pov_size: 10000,
},
relay_chain_state,
relay_parent_descendants: Default::default(),
collator_peer_id: None,
};
let inbound_messages_data = InboundMessagesData {
downward_messages: Default::default(),
horizontal_messages: Default::default(),
};
cumulus_test_runtime::UncheckedExtrinsic::new_bare(
cumulus_test_runtime::RuntimeCall::TeyrchainSystem(
cumulus_pallet_teyrchain_system::Call::set_validation_data {
data,
inbound_messages_data,
},
),
)
.into()
}
/// Import block into the given client and make sure the import was successful
pub async fn import_block(client: &TestClient, block: &NodeBlock, import_existing: bool) {
let mut params = BlockImportParams::new(BlockOrigin::File, block.header.clone());
params.body = Some(block.extrinsics.clone());
params.state_action = StateAction::Execute;
params.fork_choice = Some(ForkChoiceStrategy::LongestChain);
params.import_existing = import_existing;
let import_result = client.import_block(params).await;
assert!(
matches!(import_result, Ok(ImportResult::Imported(_))),
"Unexpected block import result: {:?}!",
import_result
);
}
/// Creates transfer extrinsics pair-wise from elements of `src_accounts` to `dst_accounts`.
pub fn create_benchmarking_transfer_extrinsics(
client: &TestClient,
src_accounts: &[sr25519::Pair],
dst_accounts: &[sr25519::Pair],
) -> (usize, Vec<OpaqueExtrinsic>) {
let chain = client.usage_info().chain;
// Add as many transfer extrinsics as possible into a single block.
let mut block_builder = BlockBuilderBuilder::new(client)
.on_parent_block(chain.best_hash)
.with_parent_block_number(chain.best_number)
.build()
.expect("Creates block builder");
let mut max_transfer_count = 0;
let mut extrinsics = Vec::new();
// Every block needs one timestamp extrinsic.
let time_ext = extrinsic_set_time(client);
extrinsics.push(time_ext);
// Every block needs tone set_validation_data extrinsic.
let parent_hash = client.usage_info().chain.best_hash;
let parent_header = client.header(parent_hash).expect("Just fetched this hash.").unwrap();
let set_validation_data_extrinsic = extrinsic_set_validation_data(parent_header);
extrinsics.push(set_validation_data_extrinsic);
for (src, dst) in src_accounts.iter().zip(dst_accounts.iter()) {
let extrinsic: UncheckedExtrinsic = construct_extrinsic(
client,
BalancesCall::transfer_keep_alive {
dest: MultiAddress::Id(AccountId::from(dst.public())),
value: 10000,
},
src.clone(),
Some(0),
);
match block_builder.push(extrinsic.clone().into()) {
Ok(_) => {},
Err(ApplyExtrinsicFailed(Validity(TransactionValidityError::Invalid(
InvalidTransaction::ExhaustsResources,
)))) => break,
Err(error) => panic!("{}", error),
}
extrinsics.push(extrinsic.into());
max_transfer_count += 1;
}
if max_transfer_count >= src_accounts.len() {
panic!("Block could fit more transfers, increase NUM_ACCOUNTS to generate more accounts.");
}
(max_transfer_count, extrinsics)
}
/// Prepare pezcumulus test runtime for execution
pub fn get_wasm_module() -> Box<dyn pezsc_executor_common::wasm_runtime::WasmModule> {
let blob = RuntimeBlob::uncompress_if_needed(
WASM_BINARY.expect("You need to build the WASM binaries to run the benchmark!"),
)
.unwrap();
let config = pezsc_executor_wasmtime::Config {
allow_missing_func_imports: true,
cache_path: None,
semantics: pezsc_executor_wasmtime::Semantics {
heap_alloc_strategy: DEFAULT_HEAP_ALLOC_STRATEGY,
instantiation_strategy: pezsc_executor::WasmtimeInstantiationStrategy::PoolingCopyOnWrite,
deterministic_stack_limit: None,
canonicalize_nans: false,
parallel_compilation: true,
wasm_multi_value: false,
wasm_bulk_memory: false,
wasm_reference_types: false,
wasm_simd: false,
},
};
Box::new(
pezsc_executor_wasmtime::create_runtime::<pezsp_io::BizinikiwiHostFunctions>(blob, config)
.expect("Unable to create wasm module."),
)
}
/// Create a block containing setup extrinsics for the glutton pallet.
pub fn set_glutton_parameters(
client: &TestClient,
initialize: bool,
compute_ratio: &FixedU64,
storage_ratio: &FixedU64,
) -> NodeBlock {
let parent_hash = client.usage_info().chain.best_hash;
let parent_header = client.header(parent_hash).expect("Just fetched this hash.").unwrap();
let mut last_nonce = client
.runtime_api()
.account_nonce(parent_hash, Alice.into())
.expect("Fetching account nonce works; qed");
let mut extrinsics = vec![];
if initialize {
// Initialize the pallet
extrinsics.push(construct_extrinsic(
client,
SudoCall::sudo {
call: Box::new(
GluttonCall::initialize_pallet { new_count: 5000, witness_count: None }.into(),
),
},
Alice.into(),
Some(last_nonce),
));
last_nonce += 1;
}
// Set compute weight that should be consumed per block
let set_compute = construct_extrinsic(
client,
SudoCall::sudo {
call: Box::new(GluttonCall::set_compute { compute: *compute_ratio }.into()),
},
Alice.into(),
Some(last_nonce),
);
last_nonce += 1;
extrinsics.push(set_compute);
// Set storage weight that should be consumed per block
let set_storage = construct_extrinsic(
client,
SudoCall::sudo {
call: Box::new(GluttonCall::set_storage { storage: *storage_ratio }.into()),
},
Alice.into(),
Some(last_nonce),
);
extrinsics.push(set_storage);
let chain = client.usage_info().chain;
let mut block_builder = BlockBuilderBuilder::new(client)
.on_parent_block(chain.best_hash)
.with_parent_block_number(chain.best_number)
.build()
.unwrap();
block_builder.push(extrinsic_set_time(client)).unwrap();
block_builder.push(extrinsic_set_validation_data(parent_header)).unwrap();
for extrinsic in extrinsics {
block_builder.push(extrinsic.into()).unwrap();
}
let built_block = block_builder.build().unwrap();
built_block.block
}
+153
View File
@@ -0,0 +1,153 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// 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 <http://www.gnu.org/licenses/>.
#![allow(missing_docs)]
use cumulus_client_service::TeyrchainHostFunctions;
use cumulus_primitives_core::ParaId;
use cumulus_test_runtime::AccountId;
use pezsc_chain_spec::GenesisConfigBuilderRuntimeCaller;
use pezsc_service::{ChainType, GenericChainSpec};
use serde_json::json;
/// Get the chain spec for a specific teyrchain ID.
/// The given accounts are initialized with funds in addition
/// to the default known accounts.
pub fn get_chain_spec_with_extra_endowed(
id: Option<ParaId>,
extra_endowed_accounts: Vec<AccountId>,
code: &[u8],
) -> GenericChainSpec {
let runtime_caller = GenesisConfigBuilderRuntimeCaller::<TeyrchainHostFunctions>::new(code);
let mut development_preset = runtime_caller
.get_named_preset(Some(&pezsp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET.to_string()))
.expect("development preset is available on test runtime; qed");
// Extract existing balances
let existing_balances = development_preset
.get("balances")
.and_then(|b| b.get("balances"))
.and_then(|b| b.as_array())
.cloned()
.unwrap_or_default();
// Create new balances by combining existing and extra accounts
let mut all_balances = existing_balances;
all_balances.extend(extra_endowed_accounts.into_iter().map(|a| json!([a, 1u64 << 60])));
let mut patch_json = json!({
"balances": {
"balances": all_balances,
},
});
if let Some(id) = id {
// Merge teyrchain ID if given, otherwise use the one from the preset.
pezsc_chain_spec::json_merge(
&mut patch_json,
json!({
"teyrchainInfo": {
"teyrchainId": id,
},
}),
);
};
pezsc_chain_spec::json_merge(&mut development_preset, patch_json.into());
GenericChainSpec::builder(code, None)
.with_name("Local Testnet")
.with_id(pezsp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET)
.with_chain_type(ChainType::Local)
.with_genesis_config_patch(development_preset)
.build()
}
/// Get the chain spec for a specific teyrchain ID.
pub fn get_chain_spec(id: Option<ParaId>) -> GenericChainSpec {
get_chain_spec_with_extra_endowed(
id,
Default::default(),
cumulus_test_runtime::WASM_BINARY.expect("WASM binary was not built, please build it!"),
)
}
/// Get the chain spec for a specific teyrchain ID.
pub fn get_elastic_scaling_chain_spec(id: Option<ParaId>) -> GenericChainSpec {
get_chain_spec_with_extra_endowed(
id,
Default::default(),
cumulus_test_runtime::elastic_scaling::WASM_BINARY
.expect("WASM binary was not built, please build it!"),
)
}
pub fn get_relay_parent_offset_chain_spec(id: Option<ParaId>) -> GenericChainSpec {
get_chain_spec_with_extra_endowed(
id,
Default::default(),
cumulus_test_runtime::relay_parent_offset::WASM_BINARY
.expect("WASM binary was not built, please build it!"),
)
}
/// Get the chain spec for a specific teyrchain ID.
pub fn get_elastic_scaling_500ms_chain_spec(id: Option<ParaId>) -> GenericChainSpec {
get_chain_spec_with_extra_endowed(
id,
Default::default(),
cumulus_test_runtime::elastic_scaling_500ms::WASM_BINARY
.expect("WASM binary was not built, please build it!"),
)
}
/// Get the chain spec for a specific teyrchain ID.
pub fn get_elastic_scaling_mvp_chain_spec(id: Option<ParaId>) -> GenericChainSpec {
get_chain_spec_with_extra_endowed(
id,
Default::default(),
cumulus_test_runtime::elastic_scaling_mvp::WASM_BINARY
.expect("WASM binary was not built, please build it!"),
)
}
pub fn get_elastic_scaling_multi_block_slot_chain_spec(id: Option<ParaId>) -> GenericChainSpec {
get_chain_spec_with_extra_endowed(
id,
Default::default(),
cumulus_test_runtime::elastic_scaling_multi_block_slot::WASM_BINARY
.expect("WASM binary was not built, please build it!"),
)
}
pub fn get_sync_backing_chain_spec(id: Option<ParaId>) -> GenericChainSpec {
get_chain_spec_with_extra_endowed(
id,
Default::default(),
cumulus_test_runtime::sync_backing::WASM_BINARY
.expect("WASM binary was not built, please build it!"),
)
}
pub fn get_async_backing_chain_spec(id: Option<ParaId>) -> GenericChainSpec {
get_chain_spec_with_extra_endowed(
id,
Default::default(),
cumulus_test_runtime::async_backing::WASM_BINARY
.expect("WASM binary was not built, please build it!"),
)
}
+374
View File
@@ -0,0 +1,374 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// 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 <http://www.gnu.org/licenses/>.
use clap::ValueEnum;
use cumulus_client_cli::{ExportGenesisHeadCommand, ExportGenesisWasmCommand};
use pezkuwi_service::{ChainSpec, ParaId, PrometheusConfig};
use pezsc_cli::{
CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams, NetworkParams,
Result as CliResult, RpcEndpoint, SharedParams, BizinikiwiCli,
};
use pezsc_service::BasePath;
use std::{
fmt::{Display, Formatter},
path::PathBuf,
};
#[derive(Debug, clap::Parser)]
#[command(
version,
propagate_version = true,
args_conflicts_with_subcommands = true,
subcommand_negates_reqs = true
)]
pub struct TestCollatorCli {
#[command(subcommand)]
pub subcommand: Option<Subcommand>,
#[command(flatten)]
pub run: cumulus_client_cli::RunCmd,
/// Relay chain arguments
#[arg(raw = true)]
pub relaychain_args: Vec<String>,
#[arg(long)]
pub disable_block_announcements: bool,
#[arg(long)]
pub fail_pov_recovery: bool,
/// Authoring style to use.
#[arg(long, default_value_t = AuthoringPolicy::Lookahead)]
pub authoring: AuthoringPolicy,
}
/// Collator implementation to use.
#[derive(PartialEq, Debug, ValueEnum, Clone, Copy)]
pub enum AuthoringPolicy {
/// Use the lookahead collator. Builds blocks once per relay chain block,
/// builds on relay chain forks.
Lookahead,
/// Use the slot-based collator which can handle elastic-scaling. Builds blocks based on time
/// and can utilize multiple cores, always builds on the best relay chain block available.
SlotBased,
}
impl Display for AuthoringPolicy {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
AuthoringPolicy::Lookahead => write!(f, "lookahead"),
AuthoringPolicy::SlotBased => write!(f, "slot-based"),
}
}
}
#[derive(Debug, clap::Subcommand)]
pub enum Subcommand {
/// Build a chain specification.
/// DEPRECATED: `build-spec` command will be removed after 1/04/2026. Use `export-chain-spec`
/// command instead.
#[deprecated(
note = "build-spec command will be removed after 1/04/2026. Use export-chain-spec command instead"
)]
BuildSpec(pezsc_cli::BuildSpecCmd),
/// Export the chain specification.
ExportChainSpec(pezsc_cli::ExportChainSpecCmd),
/// Export the genesis state of the teyrchain.
#[command(alias = "export-genesis-state")]
ExportGenesisHead(ExportGenesisHeadCommand),
/// Export the genesis wasm of the teyrchain.
ExportGenesisWasm(ExportGenesisWasmCommand),
}
#[derive(Debug)]
pub struct RelayChainCli {
/// The actual relay chain cli object.
pub base: pezkuwi_cli::RunCmd,
/// Optional chain id that should be passed to the relay chain.
pub chain_id: Option<String>,
/// The base path that should be used by the relay chain.
pub base_path: Option<PathBuf>,
}
impl RelayChainCli {
/// Parse the relay chain CLI parameters using the para chain `Configuration`.
pub fn new<'a>(
para_config: &pezsc_service::Configuration,
relay_chain_args: impl Iterator<Item = &'a String>,
) -> Self {
let base_path = para_config.base_path.path().join("pezkuwi");
Self {
base_path: Some(base_path),
chain_id: None,
base: clap::Parser::parse_from(relay_chain_args),
}
}
}
impl CliConfiguration<Self> for RelayChainCli {
fn shared_params(&self) -> &SharedParams {
self.base.base.shared_params()
}
fn import_params(&self) -> Option<&ImportParams> {
self.base.base.import_params()
}
fn network_params(&self) -> Option<&NetworkParams> {
self.base.base.network_params()
}
fn keystore_params(&self) -> Option<&KeystoreParams> {
self.base.base.keystore_params()
}
fn base_path(&self) -> CliResult<Option<BasePath>> {
Ok(self
.shared_params()
.base_path()?
.or_else(|| self.base_path.clone().map(Into::into)))
}
fn rpc_addr(&self, default_listen_port: u16) -> CliResult<Option<Vec<RpcEndpoint>>> {
self.base.base.rpc_addr(default_listen_port)
}
fn prometheus_config(
&self,
default_listen_port: u16,
chain_spec: &Box<dyn ChainSpec>,
) -> CliResult<Option<PrometheusConfig>> {
self.base.base.prometheus_config(default_listen_port, chain_spec)
}
fn init<F>(
&self,
_support_url: &String,
_impl_version: &String,
_logger_hook: F,
) -> CliResult<()>
where
F: FnOnce(&mut pezsc_cli::LoggerBuilder),
{
unreachable!("PezkuwiCli is never initialized; qed");
}
fn chain_id(&self, is_dev: bool) -> CliResult<String> {
let chain_id = self.base.base.chain_id(is_dev)?;
Ok(if chain_id.is_empty() { self.chain_id.clone().unwrap_or_default() } else { chain_id })
}
fn role(&self, is_dev: bool) -> CliResult<pezsc_service::Role> {
self.base.base.role(is_dev)
}
fn transaction_pool(
&self,
is_dev: bool,
) -> CliResult<pezsc_service::config::TransactionPoolOptions> {
self.base.base.transaction_pool(is_dev)
}
fn trie_cache_maximum_size(&self) -> CliResult<Option<usize>> {
self.base.base.trie_cache_maximum_size()
}
fn rpc_methods(&self) -> CliResult<pezsc_service::config::RpcMethods> {
self.base.base.rpc_methods()
}
fn rpc_max_connections(&self) -> CliResult<u32> {
self.base.base.rpc_max_connections()
}
fn rpc_cors(&self, is_dev: bool) -> CliResult<Option<Vec<String>>> {
self.base.base.rpc_cors(is_dev)
}
fn default_heap_pages(&self) -> CliResult<Option<u64>> {
self.base.base.default_heap_pages()
}
fn force_authoring(&self) -> CliResult<bool> {
self.base.base.force_authoring()
}
fn disable_grandpa(&self) -> CliResult<bool> {
self.base.base.disable_grandpa()
}
fn max_runtime_instances(&self) -> CliResult<Option<usize>> {
self.base.base.max_runtime_instances()
}
fn announce_block(&self) -> CliResult<bool> {
self.base.base.announce_block()
}
fn telemetry_endpoints(
&self,
chain_spec: &Box<dyn ChainSpec>,
) -> CliResult<Option<pezsc_telemetry::TelemetryEndpoints>> {
self.base.base.telemetry_endpoints(chain_spec)
}
fn node_name(&self) -> CliResult<String> {
self.base.base.node_name()
}
}
impl DefaultConfigurationValues for RelayChainCli {
fn p2p_listen_port() -> u16 {
30334
}
fn rpc_listen_port() -> u16 {
9945
}
fn prometheus_listen_port() -> u16 {
9616
}
}
impl BizinikiwiCli for TestCollatorCli {
fn impl_name() -> String {
"Pezcumulus zombienet test teyrchain".into()
}
fn impl_version() -> String {
String::new()
}
fn description() -> String {
format!(
"Pezcumulus zombienet test teyrchain\n\nThe command-line arguments provided first will be \
passed to the teyrchain node, while the arguments provided after -- will be passed \
to the relaychain node.\n\n\
{} [teyrchain-args] -- [relaychain-args]",
Self::executable_name()
)
}
fn author() -> String {
env!("CARGO_PKG_AUTHORS").into()
}
fn support_url() -> String {
"https://github.com/pezkuwichain/pezkuwi-sdk/issues/new".into()
}
fn copyright_start_year() -> i32 {
2017
}
fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn pezsc_service::ChainSpec>, String> {
Ok(match id {
"" => {
tracing::info!("Using default test service chain spec.");
Box::new(cumulus_test_service::get_chain_spec(Some(ParaId::from(2000)))) as Box<_>
},
"elastic-scaling-mvp" => {
tracing::info!("Using elastic-scaling mvp chain spec.");
Box::new(cumulus_test_service::get_elastic_scaling_mvp_chain_spec(Some(
ParaId::from(2100),
))) as Box<_>
},
"elastic-scaling" => {
tracing::info!("Using elastic-scaling chain spec.");
Box::new(cumulus_test_service::get_elastic_scaling_chain_spec(Some(ParaId::from(
2200,
)))) as Box<_>
},
"elastic-scaling-500ms" => {
tracing::info!("Using elastic-scaling 500ms chain spec.");
Box::new(cumulus_test_service::get_elastic_scaling_500ms_chain_spec(Some(
ParaId::from(2300),
))) as Box<_>
},
"elastic-scaling-multi-block-slot" => {
tracing::info!("Using elastic-scaling multi-block-slot chain spec.");
Box::new(cumulus_test_service::get_elastic_scaling_multi_block_slot_chain_spec(
Some(ParaId::from(2400)),
)) as Box<_>
},
"sync-backing" => {
tracing::info!("Using sync backing chain spec.");
Box::new(cumulus_test_service::get_sync_backing_chain_spec(Some(ParaId::from(
2500,
)))) as Box<_>
},
"async-backing" => {
tracing::info!("Using async backing chain spec.");
Box::new(cumulus_test_service::get_async_backing_chain_spec(Some(ParaId::from(
2500,
)))) as Box<_>
},
"relay-parent-offset" => Box::new(
cumulus_test_service::get_relay_parent_offset_chain_spec(Some(ParaId::from(2600))),
) as Box<_>,
path => {
let chain_spec: pezsc_chain_spec::GenericChainSpec =
pezsc_chain_spec::GenericChainSpec::from_json_file(path.into())?;
Box::new(chain_spec)
},
})
}
}
impl BizinikiwiCli for RelayChainCli {
fn impl_name() -> String {
"Pezkuwi collator".into()
}
fn impl_version() -> String {
String::new()
}
fn description() -> String {
format!(
"Pezkuwi collator\n\nThe command-line arguments provided first will be \
passed to the teyrchain node, while the arguments provided after -- will be passed \
to the relay chain node.\n\n\
{} [teyrchain-args] -- [relay_chain-args]",
Self::executable_name()
)
}
fn author() -> String {
env!("CARGO_PKG_AUTHORS").into()
}
fn support_url() -> String {
"https://github.com/pezkuwichain/pezkuwi-sdk/issues/new".into()
}
fn copyright_start_year() -> i32 {
2017
}
fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn pezsc_service::ChainSpec>, String> {
<pezkuwi_cli::Cli as BizinikiwiCli>::from_iter([RelayChainCli::executable_name()].iter())
.load_spec(id)
}
}
+996
View File
@@ -0,0 +1,996 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// 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 <http://www.gnu.org/licenses/>.
//! Crate used for testing with Pezcumulus.
#![warn(missing_docs)]
/// Utilities used for benchmarking
pub mod bench_utils;
pub mod chain_spec;
use cumulus_client_collator::service::CollatorService;
use cumulus_client_consensus_aura::{
collators::{
lookahead::{self as aura, Params as AuraParams},
slot_based::{
self as slot_based, Params as SlotBasedParams, SlotBasedBlockImport,
SlotBasedBlockImportHandle,
},
},
ImportQueueParams,
};
use prometheus::Registry;
use runtime::AccountId;
use pezsc_executor::{HeapAllocStrategy, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY};
use pezsp_consensus_aura::sr25519::AuthorityPair;
use std::{
collections::HashSet,
future::Future,
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
time::Duration,
};
use url::Url;
use crate::runtime::Weight;
use cumulus_client_cli::{CollatorOptions, RelayChainMode};
use cumulus_client_consensus_common::TeyrchainBlockImport as TTeyrchainBlockImport;
use cumulus_client_pov_recovery::{RecoveryDelayRange, RecoveryHandle};
use cumulus_client_service::{
build_network, prepare_node_config, start_relay_chain_tasks, BuildNetworkParams,
CollatorSybilResistance, DARecoveryProfile, StartRelayChainTasksParams,
TeyrchainTracingExecuteBlock,
};
use cumulus_primitives_core::{relay_chain::ValidationCode, GetTeyrchainInfo, ParaId};
use cumulus_relay_chain_inprocess_interface::RelayChainInProcessInterface;
use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult};
use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node_with_rpc;
use cumulus_test_runtime::{Hash, NodeBlock as Block, RuntimeApi};
use pezframe_system_rpc_runtime_api::AccountNonceApi;
use pezkuwi_node_subsystem::{errors::RecoveryError, messages::AvailabilityRecoveryMessage};
use pezkuwi_overseer::Handle as OverseerHandle;
use pezkuwi_primitives::{CandidateHash, CollatorPair};
use pezkuwi_service::ProvideRuntimeApi;
use pezsc_consensus::ImportQueue;
use pezsc_network::{
config::{FullNetworkConfiguration, TransportConfig},
multiaddr,
service::traits::NetworkService,
NetworkBackend, NetworkBlock, NetworkStateInfo,
};
use pezsc_service::{
config::{
BlocksPruning, DatabaseSource, ExecutorConfiguration, KeystoreConfig, MultiaddrWithPeerId,
NetworkConfiguration, OffchainWorkerConfig, PruningMode, RpcBatchRequestConfig,
RpcConfiguration, RpcEndpoint, WasmExecutionMethod,
},
BasePath, ChainSpec as ChainSpecService, Configuration, Error as ServiceError,
PartialComponents, Role, RpcHandlers, TFullBackend, TFullClient, TaskManager,
};
use pezsp_arithmetic::traits::SaturatedConversion;
use pezsp_blockchain::HeaderBackend;
use pezsp_core::Pair;
use pezsp_keyring::Sr25519Keyring;
use pezsp_runtime::{codec::Encode, generic, MultiAddress};
use pezsp_state_machine::BasicExternalities;
use std::sync::Arc;
use bizinikiwi_test_client::{
BlockchainEventsExt, RpcHandlersExt, RpcTransactionError, RpcTransactionOutput,
};
pub use chain_spec::*;
pub use cumulus_test_runtime as runtime;
pub use pezsp_keyring::Sr25519Keyring as Keyring;
const LOG_TARGET: &str = "pezcumulus-test-service";
/// The signature of the announce block fn.
pub type AnnounceBlockFn = Arc<dyn Fn(Hash, Option<Vec<u8>>) + Send + Sync>;
type HostFunctions =
(pezsp_io::BizinikiwiHostFunctions, cumulus_client_service::storage_proof_size::HostFunctions);
/// The client type being used by the test service.
pub type Client = TFullClient<runtime::NodeBlock, runtime::RuntimeApi, WasmExecutor<HostFunctions>>;
/// The backend type being used by the test service.
pub type Backend = TFullBackend<Block>;
/// The block-import type being used by the test service.
pub type TeyrchainBlockImport =
TTeyrchainBlockImport<Block, SlotBasedBlockImport<Block, Arc<Client>, Client>, Backend>;
/// Transaction pool type used by the test service
pub type TransactionPool = Arc<pezsc_transaction_pool::TransactionPoolHandle<Block, Client>>;
/// Recovery handle that fails regularly to simulate unavailable povs.
pub struct FailingRecoveryHandle {
overseer_handle: OverseerHandle,
counter: u32,
failed_hashes: HashSet<CandidateHash>,
}
impl FailingRecoveryHandle {
/// Create a new FailingRecoveryHandle
pub fn new(overseer_handle: OverseerHandle) -> Self {
Self { overseer_handle, counter: 0, failed_hashes: Default::default() }
}
}
#[async_trait::async_trait]
impl RecoveryHandle for FailingRecoveryHandle {
async fn send_recovery_msg(
&mut self,
message: AvailabilityRecoveryMessage,
origin: &'static str,
) {
let AvailabilityRecoveryMessage::RecoverAvailableData(ref receipt, _, _, _, _) = message;
let candidate_hash = receipt.hash();
// For every 3rd block we immediately signal unavailability to trigger
// a retry. The same candidate is never failed multiple times to ensure progress.
if self.counter % 3 == 0 && self.failed_hashes.insert(candidate_hash) {
tracing::info!(target: LOG_TARGET, ?candidate_hash, "Failing pov recovery.");
let AvailabilityRecoveryMessage::RecoverAvailableData(_, _, _, _, back_sender) =
message;
back_sender
.send(Err(RecoveryError::Unavailable))
.expect("Return channel should work here.");
} else {
self.overseer_handle.send_msg(message, origin).await;
}
self.counter += 1;
}
}
/// Assembly of PartialComponents (enough to run chain ops subcommands)
pub type Service = PartialComponents<
Client,
Backend,
(),
pezsc_consensus::import_queue::BasicQueue<Block>,
pezsc_transaction_pool::TransactionPoolHandle<Block, Client>,
(TeyrchainBlockImport, SlotBasedBlockImportHandle<Block>),
>;
/// Starts a `ServiceBuilder` for a full service.
///
/// Use this macro if you don't actually need the full service, but just the builder in order to
/// be able to perform chain operations.
pub fn new_partial(
config: &mut Configuration,
enable_import_proof_record: bool,
) -> Result<Service, pezsc_service::Error> {
let heap_pages = config
.executor
.default_heap_pages
.map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static { extra_pages: h as _ });
let executor = WasmExecutor::builder()
.with_execution_method(config.executor.wasm_method)
.with_onchain_heap_alloc_strategy(heap_pages)
.with_offchain_heap_alloc_strategy(heap_pages)
.with_max_runtime_instances(config.executor.max_runtime_instances)
.with_runtime_cache_size(config.executor.runtime_cache_size)
.build();
let (client, backend, keystore_container, task_manager) =
pezsc_service::new_full_parts_record_import::<Block, RuntimeApi, _>(
config,
None,
executor,
enable_import_proof_record,
)?;
let client = Arc::new(client);
let (block_import, slot_based_handle) =
SlotBasedBlockImport::new(client.clone(), client.clone());
let block_import = TeyrchainBlockImport::new(block_import, backend.clone());
let transaction_pool = Arc::from(
pezsc_transaction_pool::Builder::new(
task_manager.spawn_essential_handle(),
client.clone(),
config.role.is_authority().into(),
)
.with_options(config.transaction_pool.clone())
.with_prometheus(config.prometheus_registry())
.build(),
);
let slot_duration = pezsc_consensus_aura::slot_duration(&*client)?;
let import_queue = cumulus_client_consensus_aura::import_queue::<AuthorityPair, _, _, _, _, _>(
ImportQueueParams {
block_import: block_import.clone(),
client: client.clone(),
create_inherent_data_providers: move |_, ()| async move {
let timestamp = pezsp_timestamp::InherentDataProvider::from_system_time();
let slot =
pezsp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
*timestamp,
slot_duration,
);
Ok((slot, timestamp))
},
spawner: &task_manager.spawn_essential_handle(),
registry: None,
telemetry: None,
},
)?;
let params = PartialComponents {
backend,
client,
import_queue,
keystore_container,
task_manager,
transaction_pool,
select_chain: (),
other: (block_import, slot_based_handle),
};
Ok(params)
}
async fn build_relay_chain_interface(
relay_chain_config: Configuration,
teyrchain_prometheus_registry: Option<&Registry>,
collator_key: Option<CollatorPair>,
collator_options: CollatorOptions,
task_manager: &mut TaskManager,
) -> RelayChainResult<Arc<dyn RelayChainInterface + 'static>> {
let relay_chain_node = match collator_options.relay_chain_mode {
cumulus_client_cli::RelayChainMode::Embedded => pezkuwi_test_service::new_full(
relay_chain_config,
if let Some(ref key) = collator_key {
pezkuwi_service::IsTeyrchainNode::Collator(key.clone())
} else {
pezkuwi_service::IsTeyrchainNode::Collator(CollatorPair::generate().0)
},
None,
pezkuwi_service::CollatorOverseerGen,
Some("Relaychain"),
)
.map_err(|e| RelayChainError::Application(Box::new(e) as Box<_>))?,
cumulus_client_cli::RelayChainMode::ExternalRpc(rpc_target_urls) =>
return build_minimal_relay_chain_node_with_rpc(
relay_chain_config,
teyrchain_prometheus_registry,
task_manager,
rpc_target_urls,
)
.await
.map(|r| r.0),
};
task_manager.add_child(relay_chain_node.task_manager);
tracing::info!("Using inprocess node.");
Ok(Arc::new(RelayChainInProcessInterface::new(
relay_chain_node.client.clone(),
relay_chain_node.backend.clone(),
relay_chain_node.sync_service.clone(),
relay_chain_node.overseer_handle.ok_or(RelayChainError::GenericError(
"Overseer should be running in full node.".to_string(),
))?,
)))
}
/// Start a node with the given teyrchain `Configuration` and relay chain `Configuration`.
///
/// This is the actual implementation that is abstract over the executor and the runtime api.
#[pezsc_tracing::logging::prefix_logs_with("Teyrchain")]
pub async fn start_node_impl<RB, Net: NetworkBackend<Block, Hash>>(
teyrchain_config: Configuration,
collator_key: Option<CollatorPair>,
relay_chain_config: Configuration,
wrap_announce_block: Option<Box<dyn FnOnce(AnnounceBlockFn) -> AnnounceBlockFn>>,
fail_pov_recovery: bool,
rpc_ext_builder: RB,
collator_options: CollatorOptions,
proof_recording_during_import: bool,
use_slot_based_collator: bool,
) -> pezsc_service::error::Result<(
TaskManager,
Arc<Client>,
Arc<dyn NetworkService>,
RpcHandlers,
TransactionPool,
Arc<Backend>,
)>
where
RB: Fn(Arc<Client>) -> Result<jsonrpsee::RpcModule<()>, pezsc_service::Error> + Send + 'static,
{
let mut teyrchain_config = prepare_node_config(teyrchain_config);
let params = new_partial(&mut teyrchain_config, proof_recording_during_import)?;
let transaction_pool = params.transaction_pool.clone();
let mut task_manager = params.task_manager;
let client = params.client.clone();
let backend = params.backend.clone();
let block_import = params.other.0;
let slot_based_handle = params.other.1;
let relay_chain_interface = build_relay_chain_interface(
relay_chain_config,
teyrchain_config.prometheus_registry(),
collator_key.clone(),
collator_options.clone(),
&mut task_manager,
)
.await
.map_err(|e| pezsc_service::Error::Application(Box::new(e) as Box<_>))?;
let import_queue_service = params.import_queue.service();
let prometheus_registry = teyrchain_config.prometheus_registry().cloned();
let net_config = FullNetworkConfiguration::<Block, Hash, Net>::new(
&teyrchain_config.network,
prometheus_registry.clone(),
);
let best_hash = client.chain_info().best_hash;
let para_id = client
.runtime_api()
.teyrchain_id(best_hash)
.map_err(|e| pezsc_service::Error::Application(Box::new(e) as Box<_>))?;
tracing::info!("Teyrchain id: {:?}", para_id);
let (network, system_rpc_tx, tx_handler_controller, sync_service) =
build_network(BuildNetworkParams {
teyrchain_config: &teyrchain_config,
net_config,
client: client.clone(),
transaction_pool: transaction_pool.clone(),
para_id,
spawn_handle: task_manager.spawn_handle(),
relay_chain_interface: relay_chain_interface.clone(),
import_queue: params.import_queue,
metrics: Net::register_notification_metrics(
teyrchain_config.prometheus_config.as_ref().map(|config| &config.registry),
),
sybil_resistance_level: CollatorSybilResistance::Resistant,
})
.await?;
let keystore = params.keystore_container.keystore();
let rpc_builder = {
let client = client.clone();
Box::new(move |_| rpc_ext_builder(client.clone()))
};
let rpc_handlers = pezsc_service::spawn_tasks(pezsc_service::SpawnTasksParams {
rpc_builder,
client: client.clone(),
transaction_pool: transaction_pool.clone(),
task_manager: &mut task_manager,
config: teyrchain_config,
keystore: keystore.clone(),
backend: backend.clone(),
network: network.clone(),
sync_service: sync_service.clone(),
system_rpc_tx,
tx_handler_controller,
telemetry: None,
tracing_execute_block: Some(Arc::new(TeyrchainTracingExecuteBlock::new(client.clone()))),
})?;
let announce_block = {
let sync_service = sync_service.clone();
Arc::new(move |hash, data| sync_service.announce_block(hash, data))
};
let announce_block = wrap_announce_block
.map(|w| (w)(announce_block.clone()))
.unwrap_or_else(|| announce_block);
let overseer_handle = relay_chain_interface
.overseer_handle()
.map_err(|e| pezsc_service::Error::Application(Box::new(e)))?;
let recovery_handle: Box<dyn RecoveryHandle> = if fail_pov_recovery {
Box::new(FailingRecoveryHandle::new(overseer_handle.clone()))
} else {
Box::new(overseer_handle.clone())
};
let relay_chain_slot_duration = Duration::from_secs(6);
start_relay_chain_tasks(StartRelayChainTasksParams {
client: client.clone(),
announce_block: announce_block.clone(),
para_id,
relay_chain_interface: relay_chain_interface.clone(),
task_manager: &mut task_manager,
// Increase speed of recovery for testing purposes.
da_recovery_profile: DARecoveryProfile::Other(RecoveryDelayRange {
min: Duration::from_secs(1),
max: Duration::from_secs(5),
}),
import_queue: import_queue_service,
relay_chain_slot_duration,
recovery_handle,
sync_service: sync_service.clone(),
prometheus_registry: None,
})?;
let collator_peer_id = network.local_peer_id();
if let Some(collator_key) = collator_key {
let proposer = pezsc_basic_authorship::ProposerFactory::with_proof_recording(
task_manager.spawn_handle(),
client.clone(),
transaction_pool.clone(),
prometheus_registry.as_ref(),
None,
);
let collator_service = CollatorService::new(
client.clone(),
Arc::new(task_manager.spawn_handle()),
announce_block,
client.clone(),
);
let client_for_aura = client.clone();
if use_slot_based_collator {
tracing::info!(target: LOG_TARGET, "Starting block authoring with slot based authoring.");
let params = SlotBasedParams {
create_inherent_data_providers: move |_, ()| async move { Ok(()) },
block_import,
para_client: client.clone(),
para_backend: backend.clone(),
relay_client: relay_chain_interface,
code_hash_provider: move |block_hash| {
client_for_aura.code_at(block_hash).ok().map(|c| ValidationCode::from(c).hash())
},
keystore,
collator_key,
relay_chain_slot_duration,
para_id,
proposer,
collator_service,
authoring_duration: Duration::from_millis(2000),
reinitialize: false,
slot_offset: Duration::from_secs(1),
block_import_handle: slot_based_handle,
spawner: task_manager.spawn_essential_handle(),
export_pov: None,
max_pov_percentage: None,
collator_peer_id,
};
slot_based::run::<Block, AuthorityPair, _, _, _, _, _, _, _, _, _>(params);
} else {
tracing::info!(target: LOG_TARGET, "Starting block authoring with lookahead collator.");
let params = AuraParams {
create_inherent_data_providers: move |_, ()| async move { Ok(()) },
block_import,
para_client: client.clone(),
para_backend: backend.clone(),
relay_client: relay_chain_interface,
code_hash_provider: move |block_hash| {
client_for_aura.code_at(block_hash).ok().map(|c| ValidationCode::from(c).hash())
},
keystore,
collator_key,
collator_peer_id,
para_id,
overseer_handle,
relay_chain_slot_duration,
proposer,
collator_service,
authoring_duration: Duration::from_millis(2000),
reinitialize: false,
max_pov_percentage: None,
};
let fut = aura::run::<Block, AuthorityPair, _, _, _, _, _, _, _, _>(params);
task_manager.spawn_essential_handle().spawn("aura", None, fut);
}
}
Ok((task_manager, client, network, rpc_handlers, transaction_pool, backend))
}
/// A Pezcumulus test node instance used for testing.
pub struct TestNode {
/// TaskManager's instance.
pub task_manager: TaskManager,
/// Client's instance.
pub client: Arc<Client>,
/// Node's network.
pub network: Arc<dyn NetworkService>,
/// The `MultiaddrWithPeerId` to this node. This is useful if you want to pass it as "boot
/// node" to other nodes.
pub addr: MultiaddrWithPeerId,
/// RPCHandlers to make RPC queries.
pub rpc_handlers: RpcHandlers,
/// Node's transaction pool
pub transaction_pool: TransactionPool,
/// Node's backend
pub backend: Arc<Backend>,
}
/// A builder to create a [`TestNode`].
pub struct TestNodeBuilder {
para_id: ParaId,
tokio_handle: tokio::runtime::Handle,
key: Sr25519Keyring,
collator_key: Option<CollatorPair>,
teyrchain_nodes: Vec<MultiaddrWithPeerId>,
teyrchain_nodes_exclusive: bool,
relay_chain_nodes: Vec<MultiaddrWithPeerId>,
wrap_announce_block: Option<Box<dyn FnOnce(AnnounceBlockFn) -> AnnounceBlockFn>>,
storage_update_func_teyrchain: Option<Box<dyn Fn()>>,
storage_update_func_relay_chain: Option<Box<dyn Fn()>>,
relay_chain_mode: RelayChainMode,
endowed_accounts: Vec<AccountId>,
record_proof_during_import: bool,
}
impl TestNodeBuilder {
/// Create a new instance of `Self`.
///
/// `para_id` - The teyrchain id this node is running for.
/// `tokio_handle` - The tokio handler to use.
/// `key` - The key that will be used to generate the name and that will be passed as
/// `dev_seed`.
pub fn new(para_id: ParaId, tokio_handle: tokio::runtime::Handle, key: Sr25519Keyring) -> Self {
TestNodeBuilder {
key,
para_id,
tokio_handle,
collator_key: None,
teyrchain_nodes: Vec::new(),
teyrchain_nodes_exclusive: false,
relay_chain_nodes: Vec::new(),
wrap_announce_block: None,
storage_update_func_teyrchain: None,
storage_update_func_relay_chain: None,
endowed_accounts: Default::default(),
relay_chain_mode: RelayChainMode::Embedded,
record_proof_during_import: true,
}
}
/// Enable collator for this node.
pub fn enable_collator(mut self) -> Self {
let collator_key = CollatorPair::generate().0;
self.collator_key = Some(collator_key);
self
}
/// Instruct the node to exclusively connect to registered teyrchain nodes.
///
/// Teyrchain nodes can be registered using [`Self::connect_to_teyrchain_node`] and
/// [`Self::connect_to_teyrchain_nodes`].
pub fn exclusively_connect_to_registered_teyrchain_nodes(mut self) -> Self {
self.teyrchain_nodes_exclusive = true;
self
}
/// Make the node connect to the given teyrchain node.
///
/// By default the node will not be connected to any node or will be able to discover any other
/// node.
pub fn connect_to_teyrchain_node(mut self, node: &TestNode) -> Self {
self.teyrchain_nodes.push(node.addr.clone());
self
}
/// Make the node connect to the given teyrchain nodes.
///
/// By default the node will not be connected to any node or will be able to discover any other
/// node.
pub fn connect_to_teyrchain_nodes<'a>(
mut self,
nodes: impl IntoIterator<Item = &'a TestNode>,
) -> Self {
self.teyrchain_nodes.extend(nodes.into_iter().map(|n| n.addr.clone()));
self
}
/// Make the node connect to the given relay chain node.
///
/// By default the node will not be connected to any node or will be able to discover any other
/// node.
pub fn connect_to_relay_chain_node(
mut self,
node: &pezkuwi_test_service::PezkuwiTestNode,
) -> Self {
self.relay_chain_nodes.push(node.addr.clone());
self
}
/// Make the node connect to the given relay chain nodes.
///
/// By default the node will not be connected to any node or will be able to discover any other
/// node.
pub fn connect_to_relay_chain_nodes<'a>(
mut self,
nodes: impl IntoIterator<Item = &'a pezkuwi_test_service::PezkuwiTestNode>,
) -> Self {
self.relay_chain_nodes.extend(nodes.into_iter().map(|n| n.addr.clone()));
self
}
/// Wrap the announce block function of this node.
pub fn wrap_announce_block(
mut self,
wrap: impl FnOnce(AnnounceBlockFn) -> AnnounceBlockFn + 'static,
) -> Self {
self.wrap_announce_block = Some(Box::new(wrap));
self
}
/// Allows accessing the teyrchain storage before the test node is built.
pub fn update_storage_teyrchain(mut self, updater: impl Fn() + 'static) -> Self {
self.storage_update_func_teyrchain = Some(Box::new(updater));
self
}
/// Allows accessing the relay chain storage before the test node is built.
pub fn update_storage_relay_chain(mut self, updater: impl Fn() + 'static) -> Self {
self.storage_update_func_relay_chain = Some(Box::new(updater));
self
}
/// Connect to full node via RPC.
pub fn use_external_relay_chain_node_at_url(mut self, network_address: Url) -> Self {
self.relay_chain_mode = RelayChainMode::ExternalRpc(vec![network_address]);
self
}
/// Connect to full node via RPC.
pub fn use_external_relay_chain_node_at_port(mut self, port: u16) -> Self {
let mut localhost_url =
Url::parse("ws://localhost").expect("Should be able to parse localhost Url");
localhost_url.set_port(Some(port)).expect("Should be able to set port");
self.relay_chain_mode = RelayChainMode::ExternalRpc(vec![localhost_url]);
self
}
/// Accounts which will have an initial balance.
pub fn endowed_accounts(mut self, accounts: Vec<AccountId>) -> TestNodeBuilder {
self.endowed_accounts = accounts;
self
}
/// Record proofs during import.
pub fn import_proof_recording(mut self, should_record_proof: bool) -> TestNodeBuilder {
self.record_proof_during_import = should_record_proof;
self
}
/// Build the [`TestNode`].
pub async fn build(self) -> TestNode {
let teyrchain_config = node_config(
self.storage_update_func_teyrchain.unwrap_or_else(|| Box::new(|| ())),
self.tokio_handle.clone(),
self.key,
self.teyrchain_nodes,
self.teyrchain_nodes_exclusive,
self.para_id,
self.collator_key.is_some(),
self.endowed_accounts,
)
.expect("could not generate Configuration");
let mut relay_chain_config = pezkuwi_test_service::node_config(
self.storage_update_func_relay_chain.unwrap_or_else(|| Box::new(|| ())),
self.tokio_handle,
self.key,
self.relay_chain_nodes,
false,
);
let collator_options = CollatorOptions {
relay_chain_mode: self.relay_chain_mode,
embedded_dht_bootnode: true,
dht_bootnode_discovery: true,
};
relay_chain_config.network.node_name =
format!("{} (relay chain)", relay_chain_config.network.node_name);
let (task_manager, client, network, rpc_handlers, transaction_pool, backend) =
match relay_chain_config.network.network_backend {
pezsc_network::config::NetworkBackendType::Libp2p =>
start_node_impl::<_, pezsc_network::NetworkWorker<_, _>>(
teyrchain_config,
self.collator_key,
relay_chain_config,
self.wrap_announce_block,
false,
|_| Ok(jsonrpsee::RpcModule::new(())),
collator_options,
self.record_proof_during_import,
false,
)
.await
.expect("could not create Pezcumulus test service"),
pezsc_network::config::NetworkBackendType::Litep2p =>
start_node_impl::<_, pezsc_network::Litep2pNetworkBackend>(
teyrchain_config,
self.collator_key,
relay_chain_config,
self.wrap_announce_block,
false,
|_| Ok(jsonrpsee::RpcModule::new(())),
collator_options,
self.record_proof_during_import,
false,
)
.await
.expect("could not create Pezcumulus test service"),
};
let peer_id = network.local_peer_id();
let multiaddr = pezkuwi_test_service::get_listen_address(network.clone()).await;
let addr = MultiaddrWithPeerId { multiaddr, peer_id };
TestNode { task_manager, client, network, addr, rpc_handlers, transaction_pool, backend }
}
}
/// Create a Pezcumulus `Configuration`.
///
/// By default a TCP socket will be used, therefore you need to provide nodes if you want the
/// node to be connected to other nodes.
///
/// If `nodes_exclusive` is `true`, the node will only connect to the given `nodes` and not to any
/// other node.
///
/// The `storage_update_func` can be used to make adjustments to the runtime genesis.
pub fn node_config(
storage_update_func: impl Fn(),
tokio_handle: tokio::runtime::Handle,
key: Sr25519Keyring,
nodes: Vec<MultiaddrWithPeerId>,
nodes_exclusive: bool,
para_id: ParaId,
is_collator: bool,
endowed_accounts: Vec<AccountId>,
) -> Result<Configuration, ServiceError> {
let base_path = BasePath::new_temp_dir()?;
let root = base_path.path().join(format!("cumulus_test_service_{}", key));
let role = if is_collator { Role::Authority } else { Role::Full };
let key_seed = key.to_seed();
let mut spec = Box::new(chain_spec::get_chain_spec_with_extra_endowed(
Some(para_id),
endowed_accounts,
cumulus_test_runtime::WASM_BINARY.expect("WASM binary was not built, please build it!"),
));
let mut storage = spec.as_storage_builder().build_storage().expect("could not build storage");
BasicExternalities::execute_with_storage(&mut storage, storage_update_func);
spec.set_storage(storage);
let mut network_config = NetworkConfiguration::new(
format!("{} (teyrchain)", key_seed),
"network/test/0.1",
Default::default(),
None,
);
if nodes_exclusive {
network_config.default_peers_set.reserved_nodes = nodes;
network_config.default_peers_set.non_reserved_mode =
pezsc_network::config::NonReservedPeerMode::Deny;
} else {
network_config.boot_nodes = nodes;
}
network_config.allow_non_globals_in_dht = true;
let addr: multiaddr::Multiaddr = "/ip4/127.0.0.1/tcp/0".parse().expect("valid address; qed");
network_config.listen_addresses.push(addr.clone());
network_config.transport =
TransportConfig::Normal { enable_mdns: false, allow_private_ip: true };
Ok(Configuration {
impl_name: "pezcumulus-test-node".to_string(),
impl_version: "0.1".to_string(),
role,
tokio_handle,
transaction_pool: Default::default(),
network: network_config,
keystore: KeystoreConfig::InMemory,
database: DatabaseSource::RocksDb { path: root.join("db"), cache_size: 128 },
trie_cache_maximum_size: Some(64 * 1024 * 1024),
warm_up_trie_cache: None,
state_pruning: Some(PruningMode::ArchiveAll),
blocks_pruning: BlocksPruning::KeepAll,
chain_spec: spec,
executor: ExecutorConfiguration {
wasm_method: WasmExecutionMethod::Compiled {
instantiation_strategy:
pezsc_executor_wasmtime::InstantiationStrategy::PoolingCopyOnWrite,
},
..ExecutorConfiguration::default()
},
rpc: RpcConfiguration {
addr: None,
max_connections: Default::default(),
cors: None,
methods: Default::default(),
max_request_size: Default::default(),
max_response_size: Default::default(),
id_provider: None,
max_subs_per_conn: Default::default(),
port: 9945,
message_buffer_capacity: Default::default(),
batch_config: RpcBatchRequestConfig::Unlimited,
rate_limit: None,
rate_limit_whitelisted_ips: Default::default(),
rate_limit_trust_proxy_headers: Default::default(),
request_logger_limit: 1024,
},
prometheus_config: None,
telemetry_endpoints: None,
offchain_worker: OffchainWorkerConfig { enabled: true, indexing_enabled: false },
force_authoring: false,
disable_grandpa: false,
dev_key_seed: Some(key_seed),
tracing_targets: None,
tracing_receiver: Default::default(),
announce_block: true,
data_path: root,
base_path,
wasm_runtime_overrides: None,
})
}
impl TestNode {
/// Wait for `count` blocks to be imported in the node and then exit. This function will not
/// return if no blocks are ever created, thus you should restrict the maximum amount of time of
/// the test execution.
pub fn wait_for_blocks(&self, count: usize) -> impl Future<Output = ()> {
self.client.wait_for_blocks(count)
}
/// Send an extrinsic to this node.
pub async fn send_extrinsic(
&self,
function: impl Into<runtime::RuntimeCall>,
caller: Sr25519Keyring,
) -> Result<RpcTransactionOutput, RpcTransactionError> {
let extrinsic = construct_extrinsic(&self.client, function, caller.pair(), Some(0));
self.rpc_handlers.send_transaction(extrinsic.into()).await
}
/// Register a teyrchain at this relay chain.
pub async fn schedule_upgrade(&self, validation: Vec<u8>) -> Result<(), RpcTransactionError> {
let call = pezframe_system::Call::set_code { code: validation };
self.send_extrinsic(
runtime::SudoCall::sudo_unchecked_weight {
call: Box::new(call.into()),
weight: Weight::from_parts(1_000, 0),
},
Sr25519Keyring::Alice,
)
.await
.map(drop)
}
}
/// Fetch account nonce for key pair
pub fn fetch_nonce(client: &Client, account: pezsp_core::sr25519::Public) -> u32 {
let best_hash = client.chain_info().best_hash;
client
.runtime_api()
.account_nonce(best_hash, account.into())
.expect("Fetching account nonce works; qed")
}
/// Construct an extrinsic that can be applied to the test runtime.
pub fn construct_extrinsic(
client: &Client,
function: impl Into<runtime::RuntimeCall>,
caller: pezsp_core::sr25519::Pair,
nonce: Option<u32>,
) -> runtime::UncheckedExtrinsic {
let function = function.into();
let current_block_hash = client.info().best_hash;
let current_block = client.info().best_number.saturated_into();
let genesis_block = client.hash(0).unwrap().unwrap();
let nonce = nonce.unwrap_or_else(|| fetch_nonce(client, caller.public()));
let period = runtime::BlockHashCount::get()
.checked_next_power_of_two()
.map(|c| c / 2)
.unwrap_or(2) as u64;
let tip = 0;
let tx_ext: runtime::TxExtension = (
pezframe_system::AuthorizeCall::<runtime::Runtime>::new(),
pezframe_system::CheckNonZeroSender::<runtime::Runtime>::new(),
pezframe_system::CheckSpecVersion::<runtime::Runtime>::new(),
pezframe_system::CheckGenesis::<runtime::Runtime>::new(),
pezframe_system::CheckEra::<runtime::Runtime>::from(generic::Era::mortal(
period,
current_block,
)),
pezframe_system::CheckNonce::<runtime::Runtime>::from(nonce),
pezframe_system::CheckWeight::<runtime::Runtime>::new(),
pezpallet_transaction_payment::ChargeTransactionPayment::<runtime::Runtime>::from(tip),
)
.into();
let raw_payload = runtime::SignedPayload::from_raw(
function.clone(),
tx_ext.clone(),
((), (), runtime::VERSION.spec_version, genesis_block, current_block_hash, (), (), ()),
);
let signature = raw_payload.using_encoded(|e| caller.sign(e));
runtime::UncheckedExtrinsic::new_signed(
function,
MultiAddress::Id(caller.public().into()),
runtime::Signature::Sr25519(signature),
tx_ext,
)
}
/// Run a relay-chain validator node.
///
/// This is essentially a wrapper around
/// [`run_validator_node`](pezkuwi_test_service::run_validator_node).
pub fn run_relay_chain_validator_node(
tokio_handle: tokio::runtime::Handle,
key: Sr25519Keyring,
storage_update_func: impl Fn(),
boot_nodes: Vec<MultiaddrWithPeerId>,
port: Option<u16>,
) -> pezkuwi_test_service::PezkuwiTestNode {
let mut config = pezkuwi_test_service::node_config(
storage_update_func,
tokio_handle.clone(),
key,
boot_nodes,
true,
);
if let Some(port) = port {
config.rpc.addr = Some(vec![RpcEndpoint {
batch_config: config.rpc.batch_config,
cors: config.rpc.cors.clone(),
listen_addr: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port)),
max_connections: config.rpc.max_connections,
max_payload_in_mb: config.rpc.max_request_size,
max_payload_out_mb: config.rpc.max_response_size,
max_subscriptions_per_connection: config.rpc.max_subs_per_conn,
max_buffer_capacity_per_connection: config.rpc.message_buffer_capacity,
rpc_methods: config.rpc.methods,
rate_limit: config.rpc.rate_limit,
rate_limit_trust_proxy_headers: config.rpc.rate_limit_trust_proxy_headers,
rate_limit_whitelisted_ips: config.rpc.rate_limit_whitelisted_ips.clone(),
retry_random_port: true,
is_optional: false,
}]);
}
let mut workers_path = std::env::current_exe().unwrap();
workers_path.pop();
workers_path.pop();
tokio_handle.block_on(async move {
pezkuwi_test_service::run_validator_node(config, Some(workers_path)).await
})
}
+145
View File
@@ -0,0 +1,145 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// 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 <http://www.gnu.org/licenses/>.
mod cli;
use std::sync::Arc;
use cli::{AuthoringPolicy, RelayChainCli, Subcommand, TestCollatorCli};
use cumulus_primitives_core::relay_chain::CollatorPair;
use cumulus_test_service::{new_partial, AnnounceBlockFn};
use pezsc_cli::{CliConfiguration, BizinikiwiCli};
use pezsp_core::Pair;
pub fn wrap_announce_block() -> Box<dyn FnOnce(AnnounceBlockFn) -> AnnounceBlockFn> {
tracing::info!("Block announcements disabled.");
Box::new(|_| {
// Never announce any block
Arc::new(|_, _| {})
})
}
fn main() -> Result<(), pezsc_cli::Error> {
let cli = TestCollatorCli::from_args();
match &cli.subcommand {
#[allow(deprecated)]
Some(Subcommand::BuildSpec(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run(config.chain_spec, config.network))
},
Some(Subcommand::ExportChainSpec(cmd)) => {
let chain_spec = cli.load_spec(&cmd.chain)?;
cmd.run(chain_spec)
},
Some(Subcommand::ExportGenesisHead(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|mut config| {
let partial = new_partial(&mut config, false)?;
cmd.run(partial.client)
})
},
Some(Subcommand::ExportGenesisWasm(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run(&*config.chain_spec))
},
None => {
let log_filters = cli.run.normalize().log_filters();
let mut builder = pezsc_cli::LoggerBuilder::new(log_filters.unwrap_or_default());
builder.with_colors(false);
let _ = builder.init();
let collator_options = cli.run.collator_options();
let tokio_runtime = pezsc_cli::build_runtime()?;
let tokio_handle = tokio_runtime.handle();
let teyrchain_config = cli
.run
.normalize()
.create_configuration(&cli, tokio_handle.clone())
.expect("Should be able to generate config");
let relay_chain_cli = RelayChainCli::new(
&teyrchain_config,
[RelayChainCli::executable_name()].iter().chain(cli.relaychain_args.iter()),
);
let tokio_handle = teyrchain_config.tokio_handle.clone();
let relay_chain_config = BizinikiwiCli::create_configuration(
&relay_chain_cli,
&relay_chain_cli,
tokio_handle,
)
.map_err(|err| format!("Relay chain argument error: {}", err))?;
tracing::info!(
"Is collating: {}",
if teyrchain_config.role.is_authority() { "yes" } else { "no" }
);
if cli.fail_pov_recovery {
tracing::info!("PoV recovery failure enabled");
}
let collator_key =
teyrchain_config.role.is_authority().then(|| CollatorPair::generate().0);
let use_slot_based_collator = cli.authoring == AuthoringPolicy::SlotBased;
let (mut task_manager, _, _, _, _, _) = tokio_runtime
.block_on(async move {
match relay_chain_config.network.network_backend {
pezsc_network::config::NetworkBackendType::Libp2p =>
cumulus_test_service::start_node_impl::<
_,
pezsc_network::NetworkWorker<_, _>,
>(
teyrchain_config,
collator_key,
relay_chain_config,
cli.disable_block_announcements.then(wrap_announce_block),
cli.fail_pov_recovery,
|_| Ok(jsonrpsee::RpcModule::new(())),
collator_options,
true,
use_slot_based_collator,
)
.await,
pezsc_network::config::NetworkBackendType::Litep2p =>
cumulus_test_service::start_node_impl::<
_,
pezsc_network::Litep2pNetworkBackend,
>(
teyrchain_config,
collator_key,
relay_chain_config,
cli.disable_block_announcements.then(wrap_announce_block),
cli.fail_pov_recovery,
|_| Ok(jsonrpsee::RpcModule::new(())),
collator_options,
true,
use_slot_based_collator,
)
.await,
}
})
.expect("could not create Pezcumulus test service");
tokio_runtime
.block_on(task_manager.future())
.expect("Could not run service to completion");
Ok(())
},
}
}