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

Commit

Permalink
Replace parachain/parathread boolean by enum (#6198)
Browse files Browse the repository at this point in the history
* Replace parachain/parathread boolean by enum

* Address PR comments

* Update dependencies

* ParaType -> ParaKind

* Swap enum field order to avoid migration

* Rename paratype field to parakind

* Manual en-/decocing of Parakind

* Manual TypeInfo for ParaKind

* rename field back to parachain

* minor

* Update runtime/parachains/src/paras/mod.rs

Co-authored-by: Andrei Sandu <54316454+sandreim@users.noreply.github.com>

* Manual serde Serialize and Deserialize for ParaKind

* cargo fmt

* Update runtime/parachains/src/paras/mod.rs

Co-authored-by: Andronik <write@reusable.software>

* Add test for serde_json encoding/decoding

* Move serde_json dep to dev-deps

Co-authored-by: Andrei Sandu <54316454+sandreim@users.noreply.github.com>
Co-authored-by: Andronik <write@reusable.software>
  • Loading branch information
3 people committed Nov 1, 2022
1 parent 9804140 commit 7176670
Show file tree
Hide file tree
Showing 13 changed files with 240 additions and 101 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions node/test/service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use polkadot_node_subsystem::messages::{CollationGenerationMessage, CollatorProt
use polkadot_overseer::Handle;
use polkadot_primitives::v2::{Balance, CollatorPair, HeadData, Id as ParaId, ValidationCode};
use polkadot_runtime_common::BlockHashCount;
use polkadot_runtime_parachains::paras::ParaGenesisArgs;
use polkadot_runtime_parachains::paras::{ParaGenesisArgs, ParaKind};
use polkadot_service::{
ClientHandle, Error, ExecuteWithClient, FullClient, IsCollator, NewFull, PrometheusConfig,
};
Expand Down Expand Up @@ -305,7 +305,7 @@ impl PolkadotTestNode {
genesis: ParaGenesisArgs {
genesis_head: genesis_head.into(),
validation_code: validation_code.into(),
parachain: true,
para_kind: ParaKind::Parachain,
},
};

Expand Down
7 changes: 4 additions & 3 deletions runtime/common/src/paras_registrar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ use sp_std::{prelude::*, result};
use crate::traits::{OnSwap, Registrar};
pub use pallet::*;
use parity_scale_codec::{Decode, Encode};
use runtime_parachains::paras::ParaKind;
use scale_info::TypeInfo;
use sp_runtime::{
traits::{CheckedSub, Saturating},
Expand Down Expand Up @@ -570,7 +571,7 @@ impl<T: Config> Pallet<T> {
};
ensure!(paras::Pallet::<T>::lifecycle(id).is_none(), Error::<T>::AlreadyRegistered);
let (genesis, deposit) =
Self::validate_onboarding_data(genesis_head, validation_code, false)?;
Self::validate_onboarding_data(genesis_head, validation_code, ParaKind::Parathread)?;
let deposit = deposit_override.unwrap_or(deposit);

if let Some(additional) = deposit.checked_sub(&deposited) {
Expand Down Expand Up @@ -613,7 +614,7 @@ impl<T: Config> Pallet<T> {
fn validate_onboarding_data(
genesis_head: HeadData,
validation_code: ValidationCode,
parachain: bool,
para_kind: ParaKind,
) -> Result<(ParaGenesisArgs, BalanceOf<T>), sp_runtime::DispatchError> {
let config = configuration::Pallet::<T>::config();
ensure!(validation_code.0.len() > 0, Error::<T>::EmptyCode);
Expand All @@ -628,7 +629,7 @@ impl<T: Config> Pallet<T> {
.saturating_add(per_byte_fee.saturating_mul((genesis_head.0.len() as u32).into()))
.saturating_add(per_byte_fee.saturating_mul((validation_code.0.len() as u32).into()));

Ok((ParaGenesisArgs { genesis_head, validation_code, parachain }, deposit))
Ok((ParaGenesisArgs { genesis_head, validation_code, para_kind }, deposit))
}

/// Swap a parachain and parathread, which involves scheduling an appropriate lifecycle update.
Expand Down
1 change: 1 addition & 0 deletions runtime/parachains/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ test-helpers = { package = "polkadot-primitives-test-helpers", path = "../../pri
sp-tracing = { git = "https://github.com/paritytech/substrate", branch = "master" }
thousands = "0.2.0"
assert_matches = "1"
serde_json = "1.0.85"

[features]
default = ["std"]
Expand Down
3 changes: 2 additions & 1 deletion runtime/parachains/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

use crate::{
configuration, inclusion, initializer, paras,
paras::ParaKind,
paras_inherent::{self},
scheduler, session_info, shared,
};
Expand Down Expand Up @@ -345,7 +346,7 @@ impl<T: paras_inherent::Config> BenchBuilder<T> {
paras::ParaGenesisArgs {
genesis_head: Self::mock_head_data(),
validation_code: mock_validation_code(),
parachain: true,
para_kind: ParaKind::Parachain,
},
)
.unwrap();
Expand Down
4 changes: 2 additions & 2 deletions runtime/parachains/src/hrmp/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
use crate::{
configuration::Pallet as Configuration,
hrmp::{Pallet as Hrmp, *},
paras::{Pallet as Paras, ParachainsCache},
paras::{Pallet as Paras, ParaKind, ParachainsCache},
shared::Pallet as Shared,
};
use frame_support::{assert_ok, traits::Currency};
Expand All @@ -31,7 +31,7 @@ fn register_parachain_with_balance<T: Config>(id: ParaId, balance: BalanceOf<T>)
&mut parachains,
id,
&crate::paras::ParaGenesisArgs {
parachain: true,
para_kind: ParaKind::Parachain,
genesis_head: vec![1].into(),
validation_code: vec![1].into(),
},
Expand Down
11 changes: 7 additions & 4 deletions runtime/parachains/src/hrmp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,12 @@
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.

use super::*;
use crate::mock::{
new_test_ext, Configuration, Hrmp, MockGenesisConfig, Paras, ParasShared,
RuntimeEvent as MockEvent, RuntimeOrigin, System, Test,
use crate::{
mock::{
new_test_ext, Configuration, Hrmp, MockGenesisConfig, Paras, ParasShared,
RuntimeEvent as MockEvent, RuntimeOrigin, System, Test,
},
paras::ParaKind,
};
use frame_support::{assert_noop, assert_ok, traits::Currency as _};
use primitives::v2::BlockNumber;
Expand Down Expand Up @@ -130,7 +133,7 @@ fn register_parachain_with_balance(id: ParaId, balance: Balance) {
assert_ok!(Paras::schedule_para_initialize(
id,
crate::paras::ParaGenesisArgs {
parachain: true,
para_kind: ParaKind::Parachain,
genesis_head: vec![1].into(),
validation_code: vec![1].into(),
},
Expand Down
46 changes: 35 additions & 11 deletions runtime/parachains/src/inclusion/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use crate::{
new_test_ext, Configuration, MockGenesisConfig, ParaInclusion, Paras, ParasShared, System,
Test,
},
paras::ParaGenesisArgs,
paras::{ParaGenesisArgs, ParaKind},
paras_inherent::DisputedBitfield,
scheduler::AssignmentKind,
};
Expand Down Expand Up @@ -51,18 +51,18 @@ fn default_config() -> HostConfiguration<BlockNumber> {
config
}

pub(crate) fn genesis_config(paras: Vec<(ParaId, bool)>) -> MockGenesisConfig {
pub(crate) fn genesis_config(paras: Vec<(ParaId, ParaKind)>) -> MockGenesisConfig {
MockGenesisConfig {
paras: paras::GenesisConfig {
paras: paras
.into_iter()
.map(|(id, is_chain)| {
.map(|(id, para_kind)| {
(
id,
ParaGenesisArgs {
genesis_head: Vec::new().into(),
validation_code: dummy_validation_code(),
parachain: is_chain,
para_kind,
},
)
})
Expand Down Expand Up @@ -310,7 +310,11 @@ fn collect_pending_cleans_up_pending() {
let chain_b = ParaId::from(2_u32);
let thread_a = ParaId::from(3_u32);

let paras = vec![(chain_a, true), (chain_b, true), (thread_a, false)];
let paras = vec![
(chain_a, ParaKind::Parachain),
(chain_b, ParaKind::Parachain),
(thread_a, ParaKind::Parathread),
];
new_test_ext(genesis_config(paras)).execute_with(|| {
let default_candidate = TestCandidateBuilder::default().build();
<PendingAvailability<Test>>::insert(
Expand Down Expand Up @@ -368,7 +372,11 @@ fn bitfield_checks() {
let chain_b = ParaId::from(2_u32);
let thread_a = ParaId::from(3_u32);

let paras = vec![(chain_a, true), (chain_b, true), (thread_a, false)];
let paras = vec![
(chain_a, ParaKind::Parachain),
(chain_b, ParaKind::Parachain),
(thread_a, ParaKind::Parathread),
];
let validators = vec![
Sr25519Keyring::Alice,
Sr25519Keyring::Bob,
Expand Down Expand Up @@ -711,7 +719,11 @@ fn supermajority_bitfields_trigger_availability() {
let chain_b = ParaId::from(2_u32);
let thread_a = ParaId::from(3_u32);

let paras = vec![(chain_a, true), (chain_b, true), (thread_a, false)];
let paras = vec![
(chain_a, ParaKind::Parachain),
(chain_b, ParaKind::Parachain),
(thread_a, ParaKind::Parathread),
];
let validators = vec![
Sr25519Keyring::Alice,
Sr25519Keyring::Bob,
Expand Down Expand Up @@ -899,7 +911,11 @@ fn candidate_checks() {
// The block number of the relay-parent for testing.
const RELAY_PARENT_NUM: BlockNumber = 4;

let paras = vec![(chain_a, true), (chain_b, true), (thread_a, false)];
let paras = vec![
(chain_a, ParaKind::Parachain),
(chain_b, ParaKind::Parachain),
(thread_a, ParaKind::Parathread),
];
let validators = vec![
Sr25519Keyring::Alice,
Sr25519Keyring::Bob,
Expand Down Expand Up @@ -1442,7 +1458,11 @@ fn backing_works() {
// The block number of the relay-parent for testing.
const RELAY_PARENT_NUM: BlockNumber = 4;

let paras = vec![(chain_a, true), (chain_b, true), (thread_a, false)];
let paras = vec![
(chain_a, ParaKind::Parachain),
(chain_b, ParaKind::Parachain),
(thread_a, ParaKind::Parathread),
];
let validators = vec![
Sr25519Keyring::Alice,
Sr25519Keyring::Bob,
Expand Down Expand Up @@ -1722,7 +1742,7 @@ fn can_include_candidate_with_ok_code_upgrade() {
// The block number of the relay-parent for testing.
const RELAY_PARENT_NUM: BlockNumber = 4;

let paras = vec![(chain_a, true)];
let paras = vec![(chain_a, ParaKind::Parachain)];
let validators = vec![
Sr25519Keyring::Alice,
Sr25519Keyring::Bob,
Expand Down Expand Up @@ -1827,7 +1847,11 @@ fn session_change_wipes() {
let chain_b = ParaId::from(2_u32);
let thread_a = ParaId::from(3_u32);

let paras = vec![(chain_a, true), (chain_b, true), (thread_a, false)];
let paras = vec![
(chain_a, ParaKind::Parachain),
(chain_b, ParaKind::Parachain),
(thread_a, ParaKind::Parathread),
];
let validators = vec![
Sr25519Keyring::Alice,
Sr25519Keyring::Bob,
Expand Down
3 changes: 2 additions & 1 deletion runtime/parachains/src/initializer/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use crate::mock::{
use primitives::v2::{HeadData, Id as ParaId};
use test_helpers::dummy_validation_code;

use crate::paras::ParaKind;
use frame_support::{
assert_ok,
traits::{OnFinalize, OnInitialize},
Expand Down Expand Up @@ -90,7 +91,7 @@ fn scheduled_cleanup_performed() {
let c = ParaId::from(123);

let mock_genesis = crate::paras::ParaGenesisArgs {
parachain: true,
para_kind: ParaKind::Parachain,
genesis_head: HeadData(vec![4, 5, 6]),
validation_code: dummy_validation_code(),
};
Expand Down
4 changes: 2 additions & 2 deletions runtime/parachains/src/paras/benchmarking/pvf_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ where
&mut parachains,
id,
&ParaGenesisArgs {
parachain: true,
para_kind: ParaKind::Parachain,
genesis_head: HeadData(vec![1, 2, 3, 4]),
validation_code: old_validation_code,
},
Expand All @@ -159,7 +159,7 @@ where
let r = Pallet::<T>::schedule_para_initialize(
id,
ParaGenesisArgs {
parachain: true,
para_kind: ParaKind::Parachain,
genesis_head: HeadData(vec![1, 2, 3, 4]),
validation_code: validation_code(),
},
Expand Down
85 changes: 77 additions & 8 deletions runtime/parachains/src/paras/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ use primitives::v2::{
ConsensusLog, HeadData, Id as ParaId, PvfCheckStatement, SessionIndex, UpgradeGoAhead,
UpgradeRestriction, ValidationCode, ValidationCodeHash, ValidatorSignature,
};
use scale_info::TypeInfo;
use scale_info::{Type, TypeInfo};
use sp_core::RuntimeDebug;
use sp_runtime::{
traits::{AppVerify, One, Saturating},
Expand Down Expand Up @@ -291,8 +291,76 @@ pub struct ParaGenesisArgs {
pub genesis_head: HeadData,
/// The initial validation code to use.
pub validation_code: ValidationCode,
/// True if parachain, false if parathread.
pub parachain: bool,
/// Parachain or Parathread.
#[cfg_attr(feature = "std", serde(rename = "parachain"))]
pub para_kind: ParaKind,
}

/// Distinguishes between Parachain and Parathread
#[derive(PartialEq, Eq, Clone, RuntimeDebug)]
pub enum ParaKind {
Parathread,
Parachain,
}

#[cfg(feature = "std")]
impl Serialize for ParaKind {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
ParaKind::Parachain => serializer.serialize_bool(true),
ParaKind::Parathread => serializer.serialize_bool(false),
}
}
}

#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for ParaKind {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
match serde::de::Deserialize::deserialize(deserializer) {
Ok(true) => Ok(ParaKind::Parachain),
Ok(false) => Ok(ParaKind::Parathread),
_ => Err(serde::de::Error::custom("invalid ParaKind serde representation")),
}
}
}

// Manual encoding, decoding, and TypeInfo as the parakind field in ParaGenesisArgs used to be a bool
impl Encode for ParaKind {
fn size_hint(&self) -> usize {
true.size_hint()
}

fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
match self {
ParaKind::Parachain => true.using_encoded(f),
ParaKind::Parathread => false.using_encoded(f),
}
}
}

impl Decode for ParaKind {
fn decode<I: parity_scale_codec::Input>(
input: &mut I,
) -> Result<Self, parity_scale_codec::Error> {
match bool::decode(input) {
Ok(true) => Ok(ParaKind::Parachain),
Ok(false) => Ok(ParaKind::Parathread),
_ => Err("Invalid ParaKind representation".into()),
}
}
}

impl TypeInfo for ParaKind {
type Identity = bool;
fn type_info() -> Type {
bool::type_info()
}
}

/// This enum describes a reason why a particular PVF pre-checking vote was initiated. When the
Expand Down Expand Up @@ -2021,11 +2089,12 @@ impl<T: Config> Pallet<T> {
id: ParaId,
genesis_data: &ParaGenesisArgs,
) {
if genesis_data.parachain {
parachains.add(id);
ParaLifecycles::<T>::insert(&id, ParaLifecycle::Parachain);
} else {
ParaLifecycles::<T>::insert(&id, ParaLifecycle::Parathread);
match genesis_data.para_kind {
ParaKind::Parachain => {
parachains.add(id);
ParaLifecycles::<T>::insert(&id, ParaLifecycle::Parachain);
},
ParaKind::Parathread => ParaLifecycles::<T>::insert(&id, ParaLifecycle::Parathread),
}

// HACK: see the notice in `schedule_para_initialize`.
Expand Down
Loading

0 comments on commit 7176670

Please sign in to comment.