diff --git a/bridges/bin/rialto/node/src/chain_spec.rs b/bridges/bin/rialto/node/src/chain_spec.rs index 5c7b79e24190..4c00ff75efd2 100644 --- a/bridges/bin/rialto/node/src/chain_spec.rs +++ b/bridges/bin/rialto/node/src/chain_spec.rs @@ -16,7 +16,7 @@ use beefy_primitives::crypto::AuthorityId as BeefyId; use bp_rialto::derive_account_from_millau_id; -use polkadot_primitives::v1::{AssignmentId, ValidatorId}; +use polkadot_primitives::v2::{AssignmentId, ValidatorId}; use rialto_runtime::{ AccountId, BabeConfig, BalancesConfig, BeefyConfig, BridgeMillauMessagesConfig, ConfigurationConfig, GenesisConfig, GrandpaConfig, SessionConfig, SessionKeys, Signature, @@ -250,8 +250,8 @@ fn testnet_genesis( validation_upgrade_frequency: 1u32, validation_upgrade_delay: 1, code_retention_period: 1200, - max_code_size: polkadot_primitives::v1::MAX_CODE_SIZE, - max_pov_size: polkadot_primitives::v1::MAX_POV_SIZE, + max_code_size: polkadot_primitives::v2::MAX_CODE_SIZE, + max_pov_size: polkadot_primitives::v2::MAX_POV_SIZE, max_head_data_size: 32 * 1024, group_rotation_frequency: 20, chain_availability_period: 4, diff --git a/bridges/bin/rialto/node/src/overseer.rs b/bridges/bin/rialto/node/src/overseer.rs index bd38ceca65dc..8a97d472eb6e 100644 --- a/bridges/bin/rialto/node/src/overseer.rs +++ b/bridges/bin/rialto/node/src/overseer.rs @@ -36,7 +36,7 @@ use polkadot_overseer::{ metrics::Metrics as OverseerMetrics, BlockInfo, MetricsTrait, Overseer, InitializedOverseerBuilder, OverseerConnector, OverseerHandle, }; -use polkadot_primitives::v1::ParachainHost; +use polkadot_primitives::v2::ParachainHost; use sc_authority_discovery::Service as AuthorityDiscoveryService; use sc_client_api::AuxStore; use sc_keystore::LocalKeystore; diff --git a/bridges/bin/rialto/node/src/service.rs b/bridges/bin/rialto/node/src/service.rs index e5e9458b22c2..df0fc58a5b5c 100644 --- a/bridges/bin/rialto/node/src/service.rs +++ b/bridges/bin/rialto/node/src/service.rs @@ -29,7 +29,7 @@ use polkadot_node_core_chain_selection::Config as ChainSelectionConfig; use polkadot_node_core_dispute_coordinator::Config as DisputeCoordinatorConfig; use polkadot_node_network_protocol::request_response::IncomingRequest; use polkadot_overseer::{BlockInfo, OverseerConnector}; -use polkadot_primitives::v1::BlockId; +use polkadot_primitives::v2::BlockId; use rialto_runtime::{self, opaque::Block, RuntimeApi}; use sc_client_api::ExecutorProvider; use sc_executor::{NativeElseWasmExecutor, NativeExecutionDispatch}; @@ -43,7 +43,7 @@ use std::{sync::Arc, time::Duration}; use substrate_prometheus_endpoint::Registry; pub use polkadot_overseer::Handle; -pub use polkadot_primitives::v1::ParachainHost; +pub use polkadot_primitives::v2::ParachainHost; pub use sc_client_api::AuxStore; pub use sp_authority_discovery::AuthorityDiscoveryApi; pub use sp_blockchain::HeaderBackend; diff --git a/bridges/bin/rialto/runtime/src/lib.rs b/bridges/bin/rialto/runtime/src/lib.rs index 75f7eabe8d27..b306c6eb7ebf 100644 --- a/bridges/bin/rialto/runtime/src/lib.rs +++ b/bridges/bin/rialto/runtime/src/lib.rs @@ -747,64 +747,64 @@ impl_runtime_apis! { } } - impl polkadot_primitives::v1::ParachainHost for Runtime { - fn validators() -> Vec { - polkadot_runtime_parachains::runtime_api_impl::v1::validators::() + impl polkadot_primitives::v2::ParachainHost for Runtime { + fn validators() -> Vec { + polkadot_runtime_parachains::runtime_api_impl::v2::validators::() } fn validator_groups() -> ( - Vec>, - polkadot_primitives::v1::GroupRotationInfo, + Vec>, + polkadot_primitives::v2::GroupRotationInfo, ) { - polkadot_runtime_parachains::runtime_api_impl::v1::validator_groups::() + polkadot_runtime_parachains::runtime_api_impl::v2::validator_groups::() } - fn availability_cores() -> Vec> { - polkadot_runtime_parachains::runtime_api_impl::v1::availability_cores::() + fn availability_cores() -> Vec> { + polkadot_runtime_parachains::runtime_api_impl::v2::availability_cores::() } fn persisted_validation_data( - para_id: polkadot_primitives::v1::Id, - assumption: polkadot_primitives::v1::OccupiedCoreAssumption, + para_id: polkadot_primitives::v2::Id, + assumption: polkadot_primitives::v2::OccupiedCoreAssumption, ) - -> Option> { - polkadot_runtime_parachains::runtime_api_impl::v1::persisted_validation_data::(para_id, assumption) + -> Option> { + polkadot_runtime_parachains::runtime_api_impl::v2::persisted_validation_data::(para_id, assumption) } fn assumed_validation_data( - para_id: polkadot_primitives::v1::Id, + para_id: polkadot_primitives::v2::Id, expected_persisted_validation_data_hash: Hash, - ) -> Option<(polkadot_primitives::v1::PersistedValidationData, polkadot_primitives::v1::ValidationCodeHash)> { - polkadot_runtime_parachains::runtime_api_impl::v1::assumed_validation_data::(para_id, expected_persisted_validation_data_hash) + ) -> Option<(polkadot_primitives::v2::PersistedValidationData, polkadot_primitives::v2::ValidationCodeHash)> { + polkadot_runtime_parachains::runtime_api_impl::v2::assumed_validation_data::(para_id, expected_persisted_validation_data_hash) } fn check_validation_outputs( - para_id: polkadot_primitives::v1::Id, - outputs: polkadot_primitives::v1::CandidateCommitments, + para_id: polkadot_primitives::v2::Id, + outputs: polkadot_primitives::v2::CandidateCommitments, ) -> bool { - polkadot_runtime_parachains::runtime_api_impl::v1::check_validation_outputs::(para_id, outputs) + polkadot_runtime_parachains::runtime_api_impl::v2::check_validation_outputs::(para_id, outputs) } - fn session_index_for_child() -> polkadot_primitives::v1::SessionIndex { - polkadot_runtime_parachains::runtime_api_impl::v1::session_index_for_child::() + fn session_index_for_child() -> polkadot_primitives::v2::SessionIndex { + polkadot_runtime_parachains::runtime_api_impl::v2::session_index_for_child::() } fn validation_code( - para_id: polkadot_primitives::v1::Id, - assumption: polkadot_primitives::v1::OccupiedCoreAssumption, + para_id: polkadot_primitives::v2::Id, + assumption: polkadot_primitives::v2::OccupiedCoreAssumption, ) - -> Option { - polkadot_runtime_parachains::runtime_api_impl::v1::validation_code::(para_id, assumption) + -> Option { + polkadot_runtime_parachains::runtime_api_impl::v2::validation_code::(para_id, assumption) } fn candidate_pending_availability( - para_id: polkadot_primitives::v1::Id, - ) -> Option> { - polkadot_runtime_parachains::runtime_api_impl::v1::candidate_pending_availability::(para_id) + para_id: polkadot_primitives::v2::Id, + ) -> Option> { + polkadot_runtime_parachains::runtime_api_impl::v2::candidate_pending_availability::(para_id) } - fn candidate_events() -> Vec> { - polkadot_runtime_parachains::runtime_api_impl::v1::candidate_events::(|ev| { + fn candidate_events() -> Vec> { + polkadot_runtime_parachains::runtime_api_impl::v2::candidate_events::(|ev| { match ev { Event::Inclusion(ev) => { Some(ev) @@ -814,36 +814,36 @@ impl_runtime_apis! { }) } - fn session_info(index: polkadot_primitives::v1::SessionIndex) -> Option { - polkadot_runtime_parachains::runtime_api_impl::v1::session_info::(index) + fn session_info(index: polkadot_primitives::v2::SessionIndex) -> Option { + polkadot_runtime_parachains::runtime_api_impl::v2::session_info::(index) } fn dmq_contents( - recipient: polkadot_primitives::v1::Id, - ) -> Vec> { - polkadot_runtime_parachains::runtime_api_impl::v1::dmq_contents::(recipient) + recipient: polkadot_primitives::v2::Id, + ) -> Vec> { + polkadot_runtime_parachains::runtime_api_impl::v2::dmq_contents::(recipient) } fn inbound_hrmp_channels_contents( - recipient: polkadot_primitives::v1::Id - ) -> BTreeMap>> { - polkadot_runtime_parachains::runtime_api_impl::v1::inbound_hrmp_channels_contents::(recipient) + recipient: polkadot_primitives::v2::Id + ) -> BTreeMap>> { + polkadot_runtime_parachains::runtime_api_impl::v2::inbound_hrmp_channels_contents::(recipient) } fn validation_code_by_hash( - hash: polkadot_primitives::v1::ValidationCodeHash, - ) -> Option { - polkadot_runtime_parachains::runtime_api_impl::v1::validation_code_by_hash::(hash) + hash: polkadot_primitives::v2::ValidationCodeHash, + ) -> Option { + polkadot_runtime_parachains::runtime_api_impl::v2::validation_code_by_hash::(hash) } - fn on_chain_votes() -> Option> { - polkadot_runtime_parachains::runtime_api_impl::v1::on_chain_votes::() + fn on_chain_votes() -> Option> { + polkadot_runtime_parachains::runtime_api_impl::v2::on_chain_votes::() } } impl sp_authority_discovery::AuthorityDiscoveryApi for Runtime { fn authorities() -> Vec { - polkadot_runtime_parachains::runtime_api_impl::v1::relevant_authority_ids::() + polkadot_runtime_parachains::runtime_api_impl::v2::relevant_authority_ids::() } } diff --git a/bridges/bin/rialto/runtime/src/parachains.rs b/bridges/bin/rialto/runtime/src/parachains.rs index 332a3387ac69..60c5cf449ca2 100644 --- a/bridges/bin/rialto/runtime/src/parachains.rs +++ b/bridges/bin/rialto/runtime/src/parachains.rs @@ -20,7 +20,7 @@ use crate::{AccountId, Balance, Balances, BlockNumber, Event, Origin, Registrar, use frame_support::{parameter_types, weights::Weight}; use frame_system::EnsureRoot; -use polkadot_primitives::v1::ValidatorIndex; +use polkadot_primitives::v2::ValidatorIndex; use polkadot_runtime_common::{paras_registrar, paras_sudo_wrapper, slots}; use polkadot_runtime_parachains::{ configuration as parachains_configuration, dmp as parachains_dmp, hrmp as parachains_hrmp, diff --git a/bridges/relays/bin-substrate/src/cli/register_parachain.rs b/bridges/relays/bin-substrate/src/cli/register_parachain.rs index fecc431148eb..eae20ffb868a 100644 --- a/bridges/relays/bin-substrate/src/cli/register_parachain.rs +++ b/bridges/relays/bin-substrate/src/cli/register_parachain.rs @@ -106,8 +106,8 @@ impl RegisterParachain { let para_id: ParaId = relay_client .storage_value(StorageKey(para_id_key.to_vec()), None) .await? - .unwrap_or(polkadot_primitives::v1::LOWEST_PUBLIC_ID) - .max(polkadot_primitives::v1::LOWEST_PUBLIC_ID); + .unwrap_or(polkadot_primitives::v2::LOWEST_PUBLIC_ID) + .max(polkadot_primitives::v2::LOWEST_PUBLIC_ID); log::info!(target: "bridge", "Going to reserve parachain id: {:?}", para_id); // step 1: reserve a parachain id diff --git a/core-primitives/src/lib.rs b/core-primitives/src/lib.rs index c00548e57c3c..d1b21256f046 100644 --- a/core-primitives/src/lib.rs +++ b/core-primitives/src/lib.rs @@ -149,7 +149,7 @@ pub struct OutboundHrmpMessage { pub data: sp_std::vec::Vec, } -/// `V1` primitives. -pub mod v1 { +/// `V2` primitives. +pub mod v2 { pub use super::*; } diff --git a/erasure-coding/src/lib.rs b/erasure-coding/src/lib.rs index 7edb5bb24a55..e9020faebfad 100644 --- a/erasure-coding/src/lib.rs +++ b/erasure-coding/src/lib.rs @@ -28,7 +28,7 @@ use std::convert::TryFrom; use parity_scale_codec::{Decode, Encode}; use polkadot_node_primitives::{AvailableData, Proof}; -use polkadot_primitives::v0::{self, BlakeTwo256, Hash as H256, HashT}; +use polkadot_primitives::v2::{BlakeTwo256, Hash as H256, HashT}; use sp_core::Blake2Hasher; use thiserror::Error; use trie::{ @@ -115,16 +115,6 @@ fn code_params(n_validators: usize) -> Result { }) } -/// Obtain erasure-coded chunks for v0 `AvailableData`, one for each validator. -/// -/// Works only up to 65536 validators, and `n_validators` must be non-zero. -pub fn obtain_chunks_v0( - n_validators: usize, - data: &v0::AvailableData, -) -> Result>, Error> { - obtain_chunks(n_validators, data) -} - /// Obtain erasure-coded chunks for v1 `AvailableData`, one for each validator. /// /// Works only up to 65536 validators, and `n_validators` must be non-zero. @@ -151,20 +141,6 @@ pub fn obtain_chunks(n_validators: usize, data: &T) -> Result(n_validators: usize, chunks: I) -> Result -where - I: IntoIterator, -{ - reconstruct(n_validators, chunks) -} - /// Reconstruct the v1 available data from a set of chunks. /// /// Provide an iterator containing chunk data and the corresponding index. @@ -370,7 +346,7 @@ impl<'a, I: Iterator> parity_scale_codec::Input for ShardInput< #[cfg(test)] mod tests { use super::*; - use polkadot_primitives::v0::{AvailableData, BlockData, OmittedValidationData, PoVBlock}; + use polkadot_node_primitives::{AvailableData, BlockData, PoV}; // In order to adequately compute the number of entries in the Merkle // trie, we must account for the fixed 16-ary trie structure. @@ -383,10 +359,9 @@ mod tests { #[test] fn round_trip_works() { - let pov_block = PoVBlock { block_data: BlockData((0..255).collect()) }; + let pov = PoV { block_data: BlockData((0..255).collect()) }; - let available_data = - AvailableData { pov_block, omitted_validation: OmittedValidationData::default() }; + let available_data = AvailableData { pov: pov.into(), validation_data: Default::default() }; let chunks = obtain_chunks(10, &available_data).unwrap(); assert_eq!(chunks.len(), 10); @@ -411,11 +386,9 @@ mod tests { fn generate_trie_and_generate_proofs(magnitude: u32) { let n_validators = 2_u32.pow(magnitude) as usize; - let pov_block = - PoVBlock { block_data: BlockData(vec![2; n_validators / KEY_INDEX_NIBBLE_SIZE]) }; + let pov = PoV { block_data: BlockData(vec![2; n_validators / KEY_INDEX_NIBBLE_SIZE]) }; - let available_data = - AvailableData { pov_block, omitted_validation: OmittedValidationData::default() }; + let available_data = AvailableData { pov: pov.into(), validation_data: Default::default() }; let chunks = obtain_chunks(magnitude as usize, &available_data).unwrap(); diff --git a/node/client/src/lib.rs b/node/client/src/lib.rs index cbf84d609a8c..e33cd096053b 100644 --- a/node/client/src/lib.rs +++ b/node/client/src/lib.rs @@ -19,9 +19,8 @@ //! Provides the [`AbstractClient`] trait that is a super trait that combines all the traits the client implements. //! There is also the [`Client`] enum that combines all the different clients into one common structure. -use polkadot_primitives::{ - v1::{AccountId, Balance, Block, BlockNumber, Hash, Header, Nonce}, - v2::ParachainHost, +use polkadot_primitives::v2::{ + AccountId, Balance, Block, BlockNumber, Hash, Header, Nonce, ParachainHost, }; use sc_client_api::{AuxStore, Backend as BackendT, BlockchainEvents, KeyIterator, UsageProvider}; use sc_executor::NativeElseWasmExecutor; diff --git a/node/collation-generation/src/lib.rs b/node/collation-generation/src/lib.rs index ae0a127a6420..5cb888e100b4 100644 --- a/node/collation-generation/src/lib.rs +++ b/node/collation-generation/src/lib.rs @@ -31,7 +31,7 @@ use polkadot_node_subsystem_util::{ request_availability_cores, request_persisted_validation_data, request_validation_code, request_validation_code_hash, request_validators, }; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ collator_signature_payload, CandidateCommitments, CandidateDescriptor, CandidateReceipt, CoreState, Hash, Id as ParaId, OccupiedCoreAssumption, PersistedValidationData, ValidationCodeHash, diff --git a/node/collation-generation/src/tests.rs b/node/collation-generation/src/tests.rs index 75b0a9a79742..90e241877147 100644 --- a/node/collation-generation/src/tests.rs +++ b/node/collation-generation/src/tests.rs @@ -32,7 +32,7 @@ mod handle_new_activations { use polkadot_node_subsystem_test_helpers::{ subsystem_test_harness, TestSubsystemContextHandle, }; - use polkadot_primitives::v1::{ + use polkadot_primitives::v2::{ CollatorPair, Id as ParaId, PersistedValidationData, ScheduledCore, ValidationCode, }; use std::pin::Pin; diff --git a/node/core/approval-voting/src/approval_checking.rs b/node/core/approval-voting/src/approval_checking.rs index 99af51b11867..b513c18895b3 100644 --- a/node/core/approval-voting/src/approval_checking.rs +++ b/node/core/approval-voting/src/approval_checking.rs @@ -18,7 +18,7 @@ use bitvec::{order::Lsb0 as BitOrderLsb0, slice::BitSlice}; use polkadot_node_primitives::approval::DelayTranche; -use polkadot_primitives::v1::ValidatorIndex; +use polkadot_primitives::v2::ValidatorIndex; use crate::{ persisted_entries::{ApprovalEntry, CandidateEntry, TrancheEntry}, @@ -460,7 +460,7 @@ mod tests { use crate::{approval_db, BTreeMap}; use ::test_helpers::{dummy_candidate_receipt, dummy_hash}; use bitvec::{bitvec, order::Lsb0 as BitOrderLsb0, vec::BitVec}; - use polkadot_primitives::v1::GroupIndex; + use polkadot_primitives::v2::GroupIndex; #[test] fn pending_is_not_approved() { diff --git a/node/core/approval-voting/src/approval_db/v1/mod.rs b/node/core/approval-voting/src/approval_db/v1/mod.rs index 36c8044c6b31..fa39819977ff 100644 --- a/node/core/approval-voting/src/approval_db/v1/mod.rs +++ b/node/core/approval-voting/src/approval_db/v1/mod.rs @@ -20,7 +20,7 @@ use parity_scale_codec::{Decode, Encode}; use polkadot_node_primitives::approval::{AssignmentCert, DelayTranche}; use polkadot_node_subsystem::{SubsystemError, SubsystemResult}; use polkadot_node_subsystem_util::database::{DBTransaction, Database}; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ BlockNumber, CandidateHash, CandidateReceipt, CoreIndex, GroupIndex, Hash, SessionIndex, ValidatorIndex, ValidatorSignature, }; diff --git a/node/core/approval-voting/src/approval_db/v1/tests.rs b/node/core/approval-voting/src/approval_db/v1/tests.rs index d7d0e31ab93d..df4da8a84626 100644 --- a/node/core/approval-voting/src/approval_db/v1/tests.rs +++ b/node/core/approval-voting/src/approval_db/v1/tests.rs @@ -22,7 +22,7 @@ use crate::{ ops::{add_block_entry, canonicalize, force_approve, NewCandidateInfo}, }; use polkadot_node_subsystem_util::database::Database; -use polkadot_primitives::v1::Id as ParaId; +use polkadot_primitives::v2::Id as ParaId; use std::{collections::HashMap, sync::Arc}; use ::test_helpers::{dummy_candidate_receipt, dummy_candidate_receipt_bad_sig, dummy_hash}; diff --git a/node/core/approval-voting/src/backend.rs b/node/core/approval-voting/src/backend.rs index e5f57de70d30..3a21fba34875 100644 --- a/node/core/approval-voting/src/backend.rs +++ b/node/core/approval-voting/src/backend.rs @@ -22,7 +22,7 @@ //! before any commit to the underlying storage is made. use polkadot_node_subsystem::SubsystemResult; -use polkadot_primitives::v1::{BlockNumber, CandidateHash, Hash}; +use polkadot_primitives::v2::{BlockNumber, CandidateHash, Hash}; use std::collections::HashMap; diff --git a/node/core/approval-voting/src/criteria.rs b/node/core/approval-voting/src/criteria.rs index dc4ce82152c0..7630a038a944 100644 --- a/node/core/approval-voting/src/criteria.rs +++ b/node/core/approval-voting/src/criteria.rs @@ -20,9 +20,8 @@ use parity_scale_codec::{Decode, Encode}; use polkadot_node_primitives::approval::{ self as approval_types, AssignmentCert, AssignmentCertKind, DelayTranche, RelayVRFStory, }; -use polkadot_primitives::{ - v1::{AssignmentId, AssignmentPair, CandidateHash, CoreIndex, GroupIndex, ValidatorIndex}, - v2::SessionInfo, +use polkadot_primitives::v2::{ + AssignmentId, AssignmentPair, CandidateHash, CoreIndex, GroupIndex, SessionInfo, ValidatorIndex, }; use sc_keystore::LocalKeystore; use sp_application_crypto::ByteArray; @@ -537,7 +536,7 @@ fn is_in_backing_group( mod tests { use super::*; use polkadot_node_primitives::approval::{VRFOutput, VRFProof}; - use polkadot_primitives::v1::{Hash, ASSIGNMENT_KEY_TYPE_ID}; + use polkadot_primitives::v2::{Hash, ASSIGNMENT_KEY_TYPE_ID}; use sp_application_crypto::sr25519; use sp_core::crypto::Pair as PairT; use sp_keyring::sr25519::Keyring as Sr25519Keyring; diff --git a/node/core/approval-voting/src/import.rs b/node/core/approval-voting/src/import.rs index b79854010b35..86152bfb55b2 100644 --- a/node/core/approval-voting/src/import.rs +++ b/node/core/approval-voting/src/import.rs @@ -43,7 +43,7 @@ use polkadot_node_subsystem_util::{ determine_new_blocks, rolling_session_window::{RollingSessionWindow, SessionWindowUpdate}, }; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ BlockNumber, CandidateEvent, CandidateHash, CandidateReceipt, ConsensusLog, CoreIndex, GroupIndex, Hash, Header, SessionIndex, }; @@ -584,7 +584,7 @@ pub(crate) mod tests { use polkadot_node_subsystem::messages::AllMessages; use polkadot_node_subsystem_test_helpers::make_subsystem_context; use polkadot_node_subsystem_util::database::Database; - use polkadot_primitives::{v1::ValidatorIndex, v2::SessionInfo}; + use polkadot_primitives::v2::{SessionInfo, ValidatorIndex}; pub(crate) use sp_consensus_babe::{ digests::{CompatibleDigestItem, PreDigest, SecondaryVRFPreDigest}, AllowedSlots, BabeEpochConfiguration, Epoch as BabeEpoch, @@ -646,21 +646,21 @@ pub(crate) mod tests { _config: &criteria::Config, _leaving_cores: Vec<( CandidateHash, - polkadot_primitives::v1::CoreIndex, - polkadot_primitives::v1::GroupIndex, + polkadot_primitives::v2::CoreIndex, + polkadot_primitives::v2::GroupIndex, )>, - ) -> HashMap { + ) -> HashMap { HashMap::new() } fn check_assignment_cert( &self, - _claimed_core_index: polkadot_primitives::v1::CoreIndex, - _validator_index: polkadot_primitives::v1::ValidatorIndex, + _claimed_core_index: polkadot_primitives::v2::CoreIndex, + _validator_index: polkadot_primitives::v2::ValidatorIndex, _config: &criteria::Config, _relay_vrf_story: polkadot_node_primitives::approval::RelayVRFStory, _assignment: &polkadot_node_primitives::approval::AssignmentCert, - _backing_group: polkadot_primitives::v1::GroupIndex, + _backing_group: polkadot_primitives::v2::GroupIndex, ) -> Result { Ok(0) } diff --git a/node/core/approval-voting/src/lib.rs b/node/core/approval-voting/src/lib.rs index 86d5023a09ee..7d0a4a1e573a 100644 --- a/node/core/approval-voting/src/lib.rs +++ b/node/core/approval-voting/src/lib.rs @@ -50,13 +50,10 @@ use polkadot_node_subsystem_util::{ }, TimeoutExt, }; -use polkadot_primitives::{ - v1::{ - ApprovalVote, BlockNumber, CandidateHash, CandidateIndex, CandidateReceipt, - DisputeStatement, GroupIndex, Hash, SessionIndex, ValidDisputeStatementKind, ValidatorId, - ValidatorIndex, ValidatorPair, ValidatorSignature, - }, - v2::SessionInfo, +use polkadot_primitives::v2::{ + ApprovalVote, BlockNumber, CandidateHash, CandidateIndex, CandidateReceipt, DisputeStatement, + GroupIndex, Hash, SessionIndex, SessionInfo, ValidDisputeStatementKind, ValidatorId, + ValidatorIndex, ValidatorPair, ValidatorSignature, }; use sc_keystore::LocalKeystore; use sp_application_crypto::Pair; diff --git a/node/core/approval-voting/src/ops.rs b/node/core/approval-voting/src/ops.rs index ad81a2638d5b..47a2dc805f25 100644 --- a/node/core/approval-voting/src/ops.rs +++ b/node/core/approval-voting/src/ops.rs @@ -20,7 +20,7 @@ use polkadot_node_subsystem::SubsystemResult; use bitvec::order::Lsb0 as BitOrderLsb0; -use polkadot_primitives::v1::{BlockNumber, CandidateHash, CandidateReceipt, GroupIndex, Hash}; +use polkadot_primitives::v2::{BlockNumber, CandidateHash, CandidateReceipt, GroupIndex, Hash}; use std::{ collections::{hash_map::Entry, BTreeMap, HashMap}, diff --git a/node/core/approval-voting/src/persisted_entries.rs b/node/core/approval-voting/src/persisted_entries.rs index ce56bf1a06bb..e3ea480816e0 100644 --- a/node/core/approval-voting/src/persisted_entries.rs +++ b/node/core/approval-voting/src/persisted_entries.rs @@ -21,7 +21,7 @@ //! data and logic are intertwined. use polkadot_node_primitives::approval::{AssignmentCert, DelayTranche, RelayVRFStory}; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ BlockNumber, CandidateHash, CandidateReceipt, CoreIndex, GroupIndex, Hash, SessionIndex, ValidatorIndex, ValidatorSignature, }; diff --git a/node/core/approval-voting/src/tests.rs b/node/core/approval-voting/src/tests.rs index 60c2f39be7c5..b40a8ed40b9c 100644 --- a/node/core/approval-voting/src/tests.rs +++ b/node/core/approval-voting/src/tests.rs @@ -31,7 +31,7 @@ use polkadot_node_subsystem::{ use polkadot_node_subsystem_test_helpers as test_helpers; use polkadot_node_subsystem_util::TimeoutExt; use polkadot_overseer::HeadSupportsParachains; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ CandidateCommitments, CandidateEvent, CoreIndex, GroupIndex, Header, Id as ParaId, ValidationCode, ValidatorSignature, }; @@ -220,7 +220,7 @@ struct MockAssignmentCriteria(Compute, Check); impl AssignmentCriteria for MockAssignmentCriteria where - Compute: Fn() -> HashMap, + Compute: Fn() -> HashMap, Check: Fn(ValidatorIndex) -> Result, { fn compute_assignments( @@ -230,21 +230,21 @@ where _config: &criteria::Config, _leaving_cores: Vec<( CandidateHash, - polkadot_primitives::v1::CoreIndex, - polkadot_primitives::v1::GroupIndex, + polkadot_primitives::v2::CoreIndex, + polkadot_primitives::v2::GroupIndex, )>, - ) -> HashMap { + ) -> HashMap { self.0() } fn check_assignment_cert( &self, - _claimed_core_index: polkadot_primitives::v1::CoreIndex, + _claimed_core_index: polkadot_primitives::v2::CoreIndex, validator_index: ValidatorIndex, _config: &criteria::Config, _relay_vrf_story: polkadot_node_primitives::approval::RelayVRFStory, _assignment: &polkadot_node_primitives::approval::AssignmentCert, - _backing_group: polkadot_primitives::v1::GroupIndex, + _backing_group: polkadot_primitives::v2::GroupIndex, ) -> Result { self.1(validator_index) } @@ -252,7 +252,7 @@ where impl MockAssignmentCriteria< - fn() -> HashMap, + fn() -> HashMap, F, > { @@ -470,7 +470,7 @@ fn test_harness>( let keystore = LocalKeystore::in_memory(); let _ = keystore.sr25519_generate_new( - polkadot_primitives::v1::PARACHAIN_KEY_TYPE_ID, + polkadot_primitives::v2::PARACHAIN_KEY_TYPE_ID, Some(&Sr25519Keyring::Alice.to_seed()), ); diff --git a/node/core/av-store/src/lib.rs b/node/core/av-store/src/lib.rs index 3231f8894b52..fffcb2500bec 100644 --- a/node/core/av-store/src/lib.rs +++ b/node/core/av-store/src/lib.rs @@ -34,7 +34,7 @@ use polkadot_node_subsystem_util::database::{DBTransaction, Database}; use bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec}; use polkadot_node_primitives::{AvailableData, ErasureChunk}; use polkadot_node_subsystem_util as util; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ BlockNumber, CandidateEvent, CandidateHash, CandidateReceipt, Hash, Header, ValidatorIndex, }; use polkadot_subsystem::{ diff --git a/node/core/av-store/src/tests.rs b/node/core/av-store/src/tests.rs index 250d2dd4dd94..70374c873bb2 100644 --- a/node/core/av-store/src/tests.rs +++ b/node/core/av-store/src/tests.rs @@ -26,7 +26,7 @@ use parking_lot::Mutex; use polkadot_node_primitives::{AvailableData, BlockData, PoV, Proof}; use polkadot_node_subsystem_test_helpers as test_helpers; use polkadot_node_subsystem_util::{database::Database, TimeoutExt}; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ CandidateHash, CandidateReceipt, CoreIndex, GroupIndex, HeadData, Header, PersistedValidationData, ValidatorId, }; diff --git a/node/core/backing/src/lib.rs b/node/core/backing/src/lib.rs index f3ce93536238..c4af0d2e1222 100644 --- a/node/core/backing/src/lib.rs +++ b/node/core/backing/src/lib.rs @@ -40,7 +40,7 @@ use polkadot_node_subsystem_util::{ request_from_runtime, request_session_index_for_child, request_validator_groups, request_validators, FromJobCommand, JobSender, Validator, }; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ BackedCandidate, CandidateCommitments, CandidateDescriptor, CandidateHash, CandidateReceipt, CollatorId, CommittedCandidateReceipt, CoreIndex, CoreState, Hash, Id as ParaId, SessionIndex, SigningContext, ValidatorId, ValidatorIndex, ValidatorSignature, ValidityAttestation, @@ -58,7 +58,7 @@ use polkadot_subsystem::{ use sp_keystore::SyncCryptoStorePtr; use statement_table::{ generic::AttestedCandidate as TableAttestedCandidate, - v1::{ + v2::{ SignedStatement as TableSignedStatement, Statement as TableStatement, Summary as TableSummary, }, @@ -331,7 +331,7 @@ async fn make_pov_available( n_validators: usize, pov: Arc, candidate_hash: CandidateHash, - validation_data: polkadot_primitives::v1::PersistedValidationData, + validation_data: polkadot_primitives::v2::PersistedValidationData, expected_erasure_root: Hash, span: Option<&jaeger::Span>, ) -> Result, Error> { diff --git a/node/core/backing/src/tests.rs b/node/core/backing/src/tests.rs index 68602189dcd7..d3372552e18b 100644 --- a/node/core/backing/src/tests.rs +++ b/node/core/backing/src/tests.rs @@ -23,7 +23,7 @@ use assert_matches::assert_matches; use futures::{future, Future}; use polkadot_node_primitives::{BlockData, InvalidCandidate}; use polkadot_node_subsystem_test_helpers as test_helpers; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ CollatorId, GroupRotationInfo, HeadData, PersistedValidationData, ScheduledCore, }; use polkadot_subsystem::{ @@ -34,7 +34,7 @@ use sp_application_crypto::AppKey; use sp_keyring::Sr25519Keyring; use sp_keystore::{CryptoStore, SyncCryptoStore}; use sp_tracing as _; -use statement_table::v1::Misbehavior; +use statement_table::v2::Misbehavior; use std::collections::HashMap; fn validator_pubkeys(val_ids: &[Sr25519Keyring]) -> Vec { diff --git a/node/core/bitfield-signing/src/lib.rs b/node/core/bitfield-signing/src/lib.rs index bcdc409d7a9a..9ce8b34a7c61 100644 --- a/node/core/bitfield-signing/src/lib.rs +++ b/node/core/bitfield-signing/src/lib.rs @@ -41,7 +41,7 @@ use polkadot_node_subsystem_util::{ metrics::{self, prometheus}, JobSender, JobSubsystem, JobTrait, Validator, }; -use polkadot_primitives::v1::{AvailabilityBitfield, CoreState, Hash, ValidatorIndex}; +use polkadot_primitives::v2::{AvailabilityBitfield, CoreState, Hash, ValidatorIndex}; use sp_keystore::{Error as KeystoreError, SyncCryptoStorePtr}; use std::{iter::FromIterator, pin::Pin, time::Duration}; use wasm_timer::{Delay, Instant}; diff --git a/node/core/bitfield-signing/src/tests.rs b/node/core/bitfield-signing/src/tests.rs index d0162d5d7084..b2c0c4e174d9 100644 --- a/node/core/bitfield-signing/src/tests.rs +++ b/node/core/bitfield-signing/src/tests.rs @@ -17,7 +17,7 @@ use super::*; use futures::{executor::block_on, pin_mut}; use polkadot_node_subsystem::messages::AllMessages; -use polkadot_primitives::v1::{CandidateHash, OccupiedCore}; +use polkadot_primitives::v2::{CandidateHash, OccupiedCore}; use test_helpers::dummy_candidate_descriptor; fn occupied_core(para_id: u32, candidate_hash: CandidateHash) -> CoreState { diff --git a/node/core/candidate-validation/src/lib.rs b/node/core/candidate-validation/src/lib.rs index d854bfe3fbe8..2dafe481b1b7 100644 --- a/node/core/candidate-validation/src/lib.rs +++ b/node/core/candidate-validation/src/lib.rs @@ -40,7 +40,7 @@ use polkadot_node_subsystem::{ }; use polkadot_node_subsystem_util::metrics::{self, prometheus}; use polkadot_parachain::primitives::{ValidationParams, ValidationResult as WasmValidationResult}; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ CandidateCommitments, CandidateDescriptor, Hash, OccupiedCoreAssumption, PersistedValidationData, ValidationCode, ValidationCodeHash, }; diff --git a/node/core/candidate-validation/src/tests.rs b/node/core/candidate-validation/src/tests.rs index 9eceaa1fe7da..29c4185ed2cb 100644 --- a/node/core/candidate-validation/src/tests.rs +++ b/node/core/candidate-validation/src/tests.rs @@ -22,7 +22,7 @@ use polkadot_node_core_pvf::PrepareError; use polkadot_node_subsystem::messages::AllMessages; use polkadot_node_subsystem_test_helpers as test_helpers; use polkadot_node_subsystem_util::reexports::SubsystemContext; -use polkadot_primitives::v1::{HeadData, UpwardMessage}; +use polkadot_primitives::v2::{HeadData, UpwardMessage}; use sp_core::testing::TaskExecutor; use sp_keyring::Sr25519Keyring; diff --git a/node/core/chain-api/src/lib.rs b/node/core/chain-api/src/lib.rs index 15cdfef1a663..307a6620ecb9 100644 --- a/node/core/chain-api/src/lib.rs +++ b/node/core/chain-api/src/lib.rs @@ -38,7 +38,7 @@ use sc_client_api::AuxStore; use sp_blockchain::HeaderBackend; use polkadot_node_subsystem_util::metrics::{self, prometheus}; -use polkadot_primitives::v1::{Block, BlockId}; +use polkadot_primitives::v2::{Block, BlockId}; use polkadot_subsystem::{ messages::ChainApiMessage, overseer, FromOverseer, OverseerSignal, SpawnedSubsystem, SubsystemContext, SubsystemError, SubsystemResult, diff --git a/node/core/chain-api/src/tests.rs b/node/core/chain-api/src/tests.rs index ca89f0546710..54bd2c50df14 100644 --- a/node/core/chain-api/src/tests.rs +++ b/node/core/chain-api/src/tests.rs @@ -6,7 +6,7 @@ use std::collections::BTreeMap; use polkadot_node_primitives::BlockWeight; use polkadot_node_subsystem_test_helpers::{make_subsystem_context, TestSubsystemContextHandle}; -use polkadot_primitives::v1::{BlockId, BlockNumber, Hash, Header}; +use polkadot_primitives::v2::{BlockId, BlockNumber, Hash, Header}; use sp_blockchain::Info as BlockInfo; use sp_core::testing::TaskExecutor; diff --git a/node/core/chain-selection/src/backend.rs b/node/core/chain-selection/src/backend.rs index d340e34e18a0..71b6797d3526 100644 --- a/node/core/chain-selection/src/backend.rs +++ b/node/core/chain-selection/src/backend.rs @@ -21,7 +21,7 @@ //! [`Backend`], maintaining consistency between queries and temporary writes, //! before any commit to the underlying storage is made. -use polkadot_primitives::v1::{BlockNumber, Hash}; +use polkadot_primitives::v2::{BlockNumber, Hash}; use std::collections::HashMap; diff --git a/node/core/chain-selection/src/db_backend/v1.rs b/node/core/chain-selection/src/db_backend/v1.rs index 942e270aab4e..8b4591f5c3a9 100644 --- a/node/core/chain-selection/src/db_backend/v1.rs +++ b/node/core/chain-selection/src/db_backend/v1.rs @@ -38,7 +38,7 @@ use crate::{ }; use polkadot_node_primitives::BlockWeight; -use polkadot_primitives::v1::{BlockNumber, Hash}; +use polkadot_primitives::v2::{BlockNumber, Hash}; use parity_scale_codec::{Decode, Encode}; use polkadot_node_subsystem_util::database::{DBTransaction, Database}; diff --git a/node/core/chain-selection/src/lib.rs b/node/core/chain-selection/src/lib.rs index 8e4cfb6ec240..345322423974 100644 --- a/node/core/chain-selection/src/lib.rs +++ b/node/core/chain-selection/src/lib.rs @@ -23,7 +23,7 @@ use polkadot_node_subsystem::{ overseer, FromOverseer, OverseerSignal, SpawnedSubsystem, SubsystemContext, SubsystemError, }; use polkadot_node_subsystem_util::database::Database; -use polkadot_primitives::v1::{BlockNumber, ConsensusLog, Hash, Header}; +use polkadot_primitives::v2::{BlockNumber, ConsensusLog, Hash, Header}; use futures::{channel::oneshot, future::Either, prelude::*}; use parity_scale_codec::Error as CodecError; diff --git a/node/core/chain-selection/src/tests.rs b/node/core/chain-selection/src/tests.rs index 396e11520733..217a5a74e029 100644 --- a/node/core/chain-selection/src/tests.rs +++ b/node/core/chain-selection/src/tests.rs @@ -39,7 +39,7 @@ use polkadot_node_subsystem::{ jaeger, messages::AllMessages, ActivatedLeaf, ActiveLeavesUpdate, LeafStatus, }; use polkadot_node_subsystem_test_helpers as test_helpers; -use polkadot_primitives::v1::{BlakeTwo256, ConsensusLog, HashT}; +use polkadot_primitives::v2::{BlakeTwo256, ConsensusLog, HashT}; #[derive(Default)] struct TestBackendInner { diff --git a/node/core/chain-selection/src/tree.rs b/node/core/chain-selection/src/tree.rs index e797ef992ca5..4645ec78a27f 100644 --- a/node/core/chain-selection/src/tree.rs +++ b/node/core/chain-selection/src/tree.rs @@ -24,7 +24,7 @@ //! and as the finalized block advances, orphaned sub-trees are entirely pruned. use polkadot_node_primitives::BlockWeight; -use polkadot_primitives::v1::{BlockNumber, Hash}; +use polkadot_primitives::v2::{BlockNumber, Hash}; use std::collections::HashMap; diff --git a/node/core/dispute-coordinator/src/dummy.rs b/node/core/dispute-coordinator/src/dummy.rs index ee58e617b0b5..c16d0c762cde 100644 --- a/node/core/dispute-coordinator/src/dummy.rs +++ b/node/core/dispute-coordinator/src/dummy.rs @@ -20,7 +20,7 @@ use polkadot_node_subsystem::{ messages::DisputeCoordinatorMessage, overseer, FromOverseer, OverseerSignal, SpawnedSubsystem, SubsystemContext, SubsystemError, }; -use polkadot_primitives::v1::BlockNumber; +use polkadot_primitives::v2::BlockNumber; use futures::prelude::*; diff --git a/node/core/dispute-coordinator/src/real/backend.rs b/node/core/dispute-coordinator/src/real/backend.rs index 469e9fb018e9..92e63fba1ad9 100644 --- a/node/core/dispute-coordinator/src/real/backend.rs +++ b/node/core/dispute-coordinator/src/real/backend.rs @@ -22,7 +22,7 @@ //! before any commit to the underlying storage is made. use polkadot_node_subsystem::SubsystemResult; -use polkadot_primitives::v1::{CandidateHash, SessionIndex}; +use polkadot_primitives::v2::{CandidateHash, SessionIndex}; use std::collections::HashMap; diff --git a/node/core/dispute-coordinator/src/real/db/v1.rs b/node/core/dispute-coordinator/src/real/db/v1.rs index 3bed89f35a09..a9b98cb7b668 100644 --- a/node/core/dispute-coordinator/src/real/db/v1.rs +++ b/node/core/dispute-coordinator/src/real/db/v1.rs @@ -18,7 +18,7 @@ use polkadot_node_subsystem::{SubsystemError, SubsystemResult}; use polkadot_node_subsystem_util::database::{DBTransaction, Database}; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ CandidateHash, CandidateReceipt, Hash, InvalidDisputeStatementKind, SessionIndex, ValidDisputeStatementKind, ValidatorIndex, ValidatorSignature, }; @@ -264,7 +264,7 @@ pub(crate) fn note_current_session( mod tests { use super::*; use ::test_helpers::{dummy_candidate_receipt, dummy_hash}; - use polkadot_primitives::v1::{Hash, Id as ParaId}; + use polkadot_primitives::v2::{Hash, Id as ParaId}; fn make_db() -> DbBackend { let db = kvdb_memorydb::create(1); diff --git a/node/core/dispute-coordinator/src/real/initialized.rs b/node/core/dispute-coordinator/src/real/initialized.rs index 42ee0ae46217..779ec57bfbc4 100644 --- a/node/core/dispute-coordinator/src/real/initialized.rs +++ b/node/core/dispute-coordinator/src/real/initialized.rs @@ -43,13 +43,10 @@ use polkadot_node_subsystem::{ use polkadot_node_subsystem_util::rolling_session_window::{ RollingSessionWindow, SessionWindowUpdate, SessionsUnavailable, }; -use polkadot_primitives::{ - v1::{ - byzantine_threshold, BlockNumber, CandidateHash, CandidateReceipt, CompactStatement, - DisputeStatement, DisputeStatementSet, Hash, ScrapedOnChainVotes, SessionIndex, - ValidDisputeStatementKind, ValidatorId, ValidatorIndex, ValidatorPair, ValidatorSignature, - }, - v2::SessionInfo, +use polkadot_primitives::v2::{ + byzantine_threshold, BlockNumber, CandidateHash, CandidateReceipt, CompactStatement, + DisputeStatement, DisputeStatementSet, Hash, ScrapedOnChainVotes, SessionIndex, SessionInfo, + ValidDisputeStatementKind, ValidatorId, ValidatorIndex, ValidatorPair, ValidatorSignature, }; use crate::{ @@ -771,7 +768,7 @@ impl Initialized { let n_validators = validators.len(); let supermajority_threshold = - polkadot_primitives::v1::supermajority_threshold(n_validators); + polkadot_primitives::v2::supermajority_threshold(n_validators); // In case we are not provided with a candidate receipt // we operate under the assumption, that a previous vote diff --git a/node/core/dispute-coordinator/src/real/mod.rs b/node/core/dispute-coordinator/src/real/mod.rs index 899be8abf6ba..b962c6f488b2 100644 --- a/node/core/dispute-coordinator/src/real/mod.rs +++ b/node/core/dispute-coordinator/src/real/mod.rs @@ -38,7 +38,7 @@ use polkadot_node_subsystem::{ use polkadot_node_subsystem_util::{ database::Database, rolling_session_window::RollingSessionWindow, }; -use polkadot_primitives::v1::{ValidatorIndex, ValidatorPair}; +use polkadot_primitives::v2::{ValidatorIndex, ValidatorPair}; use crate::{ error::{FatalResult, JfyiError, Result}, diff --git a/node/core/dispute-coordinator/src/real/ordering/mod.rs b/node/core/dispute-coordinator/src/real/ordering/mod.rs index 3b7532135a11..3bd939158c57 100644 --- a/node/core/dispute-coordinator/src/real/ordering/mod.rs +++ b/node/core/dispute-coordinator/src/real/ordering/mod.rs @@ -26,7 +26,7 @@ use polkadot_node_subsystem::{ messages::ChainApiMessage, ActivatedLeaf, ActiveLeavesUpdate, ChainApiError, SubsystemSender, }; use polkadot_node_subsystem_util::runtime::get_candidate_events; -use polkadot_primitives::v1::{BlockNumber, CandidateEvent, CandidateHash, CandidateReceipt, Hash}; +use polkadot_primitives::v2::{BlockNumber, CandidateEvent, CandidateHash, CandidateReceipt, Hash}; use crate::{ error::{FatalError, FatalResult, Result}, diff --git a/node/core/dispute-coordinator/src/real/ordering/tests.rs b/node/core/dispute-coordinator/src/real/ordering/tests.rs index 6db10d7432f9..09a7ef26ee5b 100644 --- a/node/core/dispute-coordinator/src/real/ordering/tests.rs +++ b/node/core/dispute-coordinator/src/real/ordering/tests.rs @@ -35,7 +35,7 @@ use polkadot_node_subsystem_test_helpers::{ make_subsystem_context, TestSubsystemContext, TestSubsystemContextHandle, TestSubsystemSender, }; use polkadot_node_subsystem_util::{reexports::SubsystemContext, TimeoutExt}; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ BlakeTwo256, BlockNumber, CandidateDescriptor, CandidateEvent, CandidateReceipt, CoreIndex, GroupIndex, Hash, HashT, HeadData, }; diff --git a/node/core/dispute-coordinator/src/real/participation/mod.rs b/node/core/dispute-coordinator/src/real/participation/mod.rs index 1041a380a29f..27e2350e1f51 100644 --- a/node/core/dispute-coordinator/src/real/participation/mod.rs +++ b/node/core/dispute-coordinator/src/real/participation/mod.rs @@ -27,7 +27,7 @@ use polkadot_node_subsystem::{ ActiveLeavesUpdate, RecoveryError, SubsystemContext, SubsystemSender, }; use polkadot_node_subsystem_util::runtime::get_validation_code_by_hash; -use polkadot_primitives::v1::{BlockNumber, CandidateHash, CandidateReceipt, Hash, SessionIndex}; +use polkadot_primitives::v2::{BlockNumber, CandidateHash, CandidateReceipt, Hash, SessionIndex}; use crate::real::LOG_TARGET; diff --git a/node/core/dispute-coordinator/src/real/participation/queues/mod.rs b/node/core/dispute-coordinator/src/real/participation/queues/mod.rs index dbdf00b77dae..921a0941337a 100644 --- a/node/core/dispute-coordinator/src/real/participation/queues/mod.rs +++ b/node/core/dispute-coordinator/src/real/participation/queues/mod.rs @@ -16,7 +16,7 @@ use std::collections::{BTreeMap, HashMap}; -use polkadot_primitives::v1::{CandidateHash, CandidateReceipt, SessionIndex}; +use polkadot_primitives::v2::{CandidateHash, CandidateReceipt, SessionIndex}; use crate::real::ordering::CandidateComparator; diff --git a/node/core/dispute-coordinator/src/real/participation/queues/tests.rs b/node/core/dispute-coordinator/src/real/participation/queues/tests.rs index 3d5759a66d6b..8d1cc970a75e 100644 --- a/node/core/dispute-coordinator/src/real/participation/queues/tests.rs +++ b/node/core/dispute-coordinator/src/real/participation/queues/tests.rs @@ -16,7 +16,7 @@ use ::test_helpers::{dummy_candidate_receipt, dummy_hash}; use assert_matches::assert_matches; -use polkadot_primitives::v1::{BlockNumber, Hash}; +use polkadot_primitives::v2::{BlockNumber, Hash}; use crate::real::ordering::CandidateComparator; diff --git a/node/core/dispute-coordinator/src/real/participation/tests.rs b/node/core/dispute-coordinator/src/real/participation/tests.rs index 75e2baa403db..bbb83e9fcda0 100644 --- a/node/core/dispute-coordinator/src/real/participation/tests.rs +++ b/node/core/dispute-coordinator/src/real/participation/tests.rs @@ -38,7 +38,7 @@ use polkadot_node_subsystem::{ use polkadot_node_subsystem_test_helpers::{ make_subsystem_context, TestSubsystemContext, TestSubsystemContextHandle, }; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ BlakeTwo256, CandidateCommitments, HashT, Header, PersistedValidationData, ValidationCode, }; diff --git a/node/core/dispute-coordinator/src/real/spam_slots.rs b/node/core/dispute-coordinator/src/real/spam_slots.rs index 7818b112411d..a9327dadeb0e 100644 --- a/node/core/dispute-coordinator/src/real/spam_slots.rs +++ b/node/core/dispute-coordinator/src/real/spam_slots.rs @@ -16,7 +16,7 @@ use std::collections::{HashMap, HashSet}; -use polkadot_primitives::v1::{CandidateHash, SessionIndex, ValidatorIndex}; +use polkadot_primitives::v2::{CandidateHash, SessionIndex, ValidatorIndex}; use crate::real::LOG_TARGET; diff --git a/node/core/dispute-coordinator/src/real/tests.rs b/node/core/dispute-coordinator/src/real/tests.rs index d2ccc35bdaac..bfed38265513 100644 --- a/node/core/dispute-coordinator/src/real/tests.rs +++ b/node/core/dispute-coordinator/src/real/tests.rs @@ -54,13 +54,10 @@ use polkadot_node_subsystem::{ ActivatedLeaf, ActiveLeavesUpdate, LeafStatus, }; use polkadot_node_subsystem_test_helpers::{make_subsystem_context, TestSubsystemContextHandle}; -use polkadot_primitives::{ - v1::{ - BlakeTwo256, BlockNumber, CandidateCommitments, CandidateHash, CandidateReceipt, Hash, - HashT, Header, MultiDisputeStatementSet, ScrapedOnChainVotes, SessionIndex, SigningContext, - ValidatorId, ValidatorIndex, - }, - v2::SessionInfo, +use polkadot_primitives::v2::{ + BlakeTwo256, BlockNumber, CandidateCommitments, CandidateHash, CandidateReceipt, Hash, HashT, + Header, MultiDisputeStatementSet, ScrapedOnChainVotes, SessionIndex, SessionInfo, + SigningContext, ValidatorId, ValidatorIndex, }; use crate::{ @@ -83,7 +80,7 @@ fn make_keystore(seeds: impl Iterator) -> LocalKeystore { for s in seeds { store - .sr25519_generate_new(polkadot_primitives::v1::PARACHAIN_KEY_TYPE_ID, Some(&s)) + .sr25519_generate_new(polkadot_primitives::v2::PARACHAIN_KEY_TYPE_ID, Some(&s)) .unwrap(); } @@ -1299,7 +1296,7 @@ fn supermajority_valid_dispute_may_be_finalized() { test_state.activate_leaf_at_session(&mut virtual_overseer, session, 1).await; let supermajority_threshold = - polkadot_primitives::v1::supermajority_threshold(test_state.validators.len()); + polkadot_primitives::v2::supermajority_threshold(test_state.validators.len()); let valid_vote = test_state .issue_explicit_statement_with_index(2, candidate_hash, session, true) @@ -1419,7 +1416,7 @@ fn concluded_supermajority_for_non_active_after_time() { test_state.activate_leaf_at_session(&mut virtual_overseer, session, 1).await; let supermajority_threshold = - polkadot_primitives::v1::supermajority_threshold(test_state.validators.len()); + polkadot_primitives::v2::supermajority_threshold(test_state.validators.len()); let valid_vote = test_state .issue_explicit_statement_with_index(2, candidate_hash, session, true) @@ -1517,7 +1514,7 @@ fn concluded_supermajority_against_non_active_after_time() { test_state.activate_leaf_at_session(&mut virtual_overseer, session, 1).await; let supermajority_threshold = - polkadot_primitives::v1::supermajority_threshold(test_state.validators.len()); + polkadot_primitives::v2::supermajority_threshold(test_state.validators.len()); let valid_vote = test_state .issue_explicit_statement_with_index(2, candidate_hash, session, true) diff --git a/node/core/dispute-coordinator/src/status.rs b/node/core/dispute-coordinator/src/status.rs index 5be1e7b390ed..f07c6a7d2684 100644 --- a/node/core/dispute-coordinator/src/status.rs +++ b/node/core/dispute-coordinator/src/status.rs @@ -17,7 +17,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; use parity_scale_codec::{Decode, Encode}; -use polkadot_primitives::v1::{CandidateHash, SessionIndex}; +use polkadot_primitives::v2::{CandidateHash, SessionIndex}; use crate::LOG_TARGET; diff --git a/node/core/parachains-inherent/src/lib.rs b/node/core/parachains-inherent/src/lib.rs index fdccb8321dd3..7ab8360451f3 100644 --- a/node/core/parachains-inherent/src/lib.rs +++ b/node/core/parachains-inherent/src/lib.rs @@ -28,7 +28,7 @@ use futures::{select, FutureExt}; use polkadot_node_subsystem::{ errors::SubsystemError, messages::ProvisionerMessage, overseer::Handle, }; -use polkadot_primitives::v1::{Block, Hash, InherentData as ParachainsInherentData}; +use polkadot_primitives::v2::{Block, Hash, InherentData as ParachainsInherentData}; use sp_blockchain::HeaderBackend; use sp_runtime::generic::BlockId; use std::time; @@ -112,7 +112,7 @@ impl sp_inherents::InherentDataProvider for ParachainsInherentDataProvider { dst_inherent_data: &mut sp_inherents::InherentData, ) -> Result<(), sp_inherents::Error> { dst_inherent_data - .put_data(polkadot_primitives::v1::PARACHAINS_INHERENT_IDENTIFIER, &self.inherent_data) + .put_data(polkadot_primitives::v2::PARACHAINS_INHERENT_IDENTIFIER, &self.inherent_data) } async fn try_handle_error( diff --git a/node/core/provisioner/src/lib.rs b/node/core/provisioner/src/lib.rs index d761844007d8..126e7bae5092 100644 --- a/node/core/provisioner/src/lib.rs +++ b/node/core/provisioner/src/lib.rs @@ -39,7 +39,7 @@ use polkadot_node_subsystem_util::{ self as util, request_availability_cores, request_persisted_validation_data, JobSender, JobSubsystem, JobTrait, }; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ BackedCandidate, BlockNumber, CandidateHash, CandidateReceipt, CoreState, DisputeStatement, DisputeStatementSet, Hash, MultiDisputeStatementSet, OccupiedCoreAssumption, SessionIndex, SignedAvailabilityBitfield, ValidatorIndex, diff --git a/node/core/provisioner/src/tests.rs b/node/core/provisioner/src/tests.rs index d4552743252c..d7470758558b 100644 --- a/node/core/provisioner/src/tests.rs +++ b/node/core/provisioner/src/tests.rs @@ -1,7 +1,7 @@ use super::*; use ::test_helpers::{dummy_candidate_descriptor, dummy_hash}; use bitvec::bitvec; -use polkadot_primitives::v1::{OccupiedCore, ScheduledCore}; +use polkadot_primitives::v2::{OccupiedCore, ScheduledCore}; pub fn occupied_core(para_id: u32) -> CoreState { CoreState::Occupied(OccupiedCore { @@ -41,7 +41,7 @@ pub fn scheduled_core(id: u32) -> ScheduledCore { mod select_availability_bitfields { use super::{super::*, default_bitvec, occupied_core}; use futures::executor::block_on; - use polkadot_primitives::v1::{ScheduledCore, SigningContext, ValidatorId, ValidatorIndex}; + use polkadot_primitives::v2::{ScheduledCore, SigningContext, ValidatorId, ValidatorIndex}; use sp_application_crypto::AppKey; use sp_keystore::{testing::KeyStore, CryptoStore, SyncCryptoStorePtr}; use std::sync::Arc; @@ -201,7 +201,7 @@ mod select_candidates { }, }; use polkadot_node_subsystem_test_helpers::TestSubsystemSender; - use polkadot_primitives::v1::{ + use polkadot_primitives::v2::{ BlockNumber, CandidateCommitments, CommittedCandidateReceipt, PersistedValidationData, }; diff --git a/node/core/pvf-checker/src/interest_view.rs b/node/core/pvf-checker/src/interest_view.rs index 6ca07fe80588..f6af819e9856 100644 --- a/node/core/pvf-checker/src/interest_view.rs +++ b/node/core/pvf-checker/src/interest_view.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use polkadot_primitives::v1::{Hash, ValidationCodeHash}; +use polkadot_primitives::v2::{Hash, ValidationCodeHash}; use std::collections::{ btree_map::{self, BTreeMap}, HashSet, diff --git a/node/core/pvf-checker/src/lib.rs b/node/core/pvf-checker/src/lib.rs index 34c7a2bbd0e8..8eaf898f07b1 100644 --- a/node/core/pvf-checker/src/lib.rs +++ b/node/core/pvf-checker/src/lib.rs @@ -26,9 +26,9 @@ use polkadot_node_subsystem::{ overseer, ActiveLeavesUpdate, FromOverseer, OverseerSignal, SpawnedSubsystem, SubsystemContext, SubsystemError, SubsystemResult, SubsystemSender, }; -use polkadot_primitives::{ - v1::{BlockNumber, Hash, SessionIndex, ValidationCodeHash, ValidatorId, ValidatorIndex}, - v2::PvfCheckStatement, +use polkadot_primitives::v2::{ + BlockNumber, Hash, PvfCheckStatement, SessionIndex, ValidationCodeHash, ValidatorId, + ValidatorIndex, }; use sp_keystore::SyncCryptoStorePtr; use std::collections::HashSet; diff --git a/node/core/pvf-checker/src/runtime_api.rs b/node/core/pvf-checker/src/runtime_api.rs index 59f94f6c1ac0..91b6e52d9973 100644 --- a/node/core/pvf-checker/src/runtime_api.rs +++ b/node/core/pvf-checker/src/runtime_api.rs @@ -21,9 +21,8 @@ use polkadot_node_subsystem::{ messages::{RuntimeApiMessage, RuntimeApiRequest}, SubsystemSender, }; -use polkadot_primitives::{ - v1::{Hash, SessionIndex, ValidationCodeHash, ValidatorId, ValidatorSignature}, - v2::PvfCheckStatement, +use polkadot_primitives::v2::{ + Hash, PvfCheckStatement, SessionIndex, ValidationCodeHash, ValidatorId, ValidatorSignature, }; pub(crate) async fn session_index_for_child( diff --git a/node/core/pvf-checker/src/tests.rs b/node/core/pvf-checker/src/tests.rs index 80a7601ead55..36ca35b187e7 100644 --- a/node/core/pvf-checker/src/tests.rs +++ b/node/core/pvf-checker/src/tests.rs @@ -25,11 +25,9 @@ use polkadot_node_subsystem::{ ActivatedLeaf, ActiveLeavesUpdate, FromOverseer, LeafStatus, OverseerSignal, RuntimeApiError, }; use polkadot_node_subsystem_test_helpers::{make_subsystem_context, TestSubsystemContextHandle}; -use polkadot_primitives::{ - v1::{ - BlockNumber, Hash, Header, SessionIndex, ValidationCode, ValidationCodeHash, ValidatorId, - }, - v2::PvfCheckStatement, +use polkadot_primitives::v2::{ + BlockNumber, Hash, Header, PvfCheckStatement, SessionIndex, ValidationCode, ValidationCodeHash, + ValidatorId, }; use sp_application_crypto::AppKey; use sp_core::testing::TaskExecutor; diff --git a/node/core/runtime-api/src/cache.rs b/node/core/runtime-api/src/cache.rs index c075b73d278e..3dab90e4c74e 100644 --- a/node/core/runtime-api/src/cache.rs +++ b/node/core/runtime-api/src/cache.rs @@ -20,15 +20,12 @@ use memory_lru::{MemoryLruCache, ResidentSize}; use parity_util_mem::{MallocSizeOf, MallocSizeOfExt}; use sp_consensus_babe::Epoch; -use polkadot_primitives::{ - v1::{ - AuthorityDiscoveryId, BlockNumber, CandidateCommitments, CandidateEvent, - CommittedCandidateReceipt, CoreState, GroupRotationInfo, Hash, Id as ParaId, - InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption, - PersistedValidationData, ScrapedOnChainVotes, SessionIndex, ValidationCode, - ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature, - }, - v2::{PvfCheckStatement, SessionInfo}, +use polkadot_primitives::v2::{ + AuthorityDiscoveryId, BlockNumber, CandidateCommitments, CandidateEvent, + CommittedCandidateReceipt, CoreState, GroupRotationInfo, Hash, Id as ParaId, + InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption, PersistedValidationData, + PvfCheckStatement, ScrapedOnChainVotes, SessionIndex, SessionInfo, ValidationCode, + ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature, }; const AUTHORITIES_CACHE_SIZE: usize = 128 * 1024; @@ -49,6 +46,7 @@ const CURRENT_BABE_EPOCH_CACHE_SIZE: usize = 64 * 1024; const ON_CHAIN_VOTES_CACHE_SIZE: usize = 3 * 1024; const PVFS_REQUIRE_PRECHECK_SIZE: usize = 1024; const VALIDATION_CODE_HASH_CACHE_SIZE: usize = 64 * 1024; +const VERSION_CACHE_SIZE: usize = 4 * 1024; struct ResidentSizeOf(T); @@ -116,6 +114,7 @@ pub(crate) struct RequestResultCache { (Hash, ParaId, OccupiedCoreAssumption), ResidentSizeOf>, >, + version: MemoryLruCache>, } impl Default for RequestResultCache { @@ -142,6 +141,7 @@ impl Default for RequestResultCache { on_chain_votes: MemoryLruCache::new(ON_CHAIN_VOTES_CACHE_SIZE), pvfs_require_precheck: MemoryLruCache::new(PVFS_REQUIRE_PRECHECK_SIZE), validation_code_hash: MemoryLruCache::new(VALIDATION_CODE_HASH_CACHE_SIZE), + version: MemoryLruCache::new(VERSION_CACHE_SIZE), } } } @@ -399,6 +399,14 @@ impl RequestResultCache { ) { self.validation_code_hash.insert(key, ResidentSizeOf(value)); } + + pub(crate) fn version(&mut self, relay_parent: &Hash) -> Option<&u32> { + self.version.get(&relay_parent).map(|v| &v.0) + } + + pub(crate) fn cache_version(&mut self, key: Hash, value: u32) { + self.version.insert(key, ResidentSizeOf(value)); + } } pub(crate) enum RequestResult { @@ -433,4 +441,5 @@ pub(crate) enum RequestResult { // This is a request with side-effects and no result, hence (). SubmitPvfCheckStatement(Hash, PvfCheckStatement, ValidatorSignature, ()), ValidationCodeHash(Hash, ParaId, OccupiedCoreAssumption, Option), + Version(Hash, u32), } diff --git a/node/core/runtime-api/src/lib.rs b/node/core/runtime-api/src/lib.rs index e1e23d162061..a9e806b2fdde 100644 --- a/node/core/runtime-api/src/lib.rs +++ b/node/core/runtime-api/src/lib.rs @@ -23,10 +23,7 @@ #![warn(missing_docs)] use polkadot_node_subsystem_util::metrics::{self, prometheus}; -use polkadot_primitives::{ - v1::{Block, BlockId, Hash}, - v2::ParachainHost, -}; +use polkadot_primitives::v2::{Block, BlockId, Hash, ParachainHost}; use polkadot_subsystem::{ errors::RuntimeApiError, messages::{RuntimeApiMessage, RuntimeApiRequest as Request}, @@ -165,6 +162,8 @@ where ValidationCodeHash(relay_parent, para_id, assumption, hash) => self .requests_cache .cache_validation_code_hash((relay_parent, para_id, assumption), hash), + Version(relay_parent, version) => + self.requests_cache.cache_version(relay_parent, version), } } @@ -195,6 +194,8 @@ where } match request { + Request::Version(sender) => + query!(version(), sender).map(|sender| Request::Version(sender)), Request::Authorities(sender) => query!(authorities(), sender).map(|sender| Request::Authorities(sender)), Request::Validators(sender) => @@ -360,6 +361,8 @@ where Client: ProvideRuntimeApi, Client::Api: ParachainHost + BabeApi + AuthorityDiscoveryApi, { + use sp_api::ApiExt; + let _timer = metrics.time_make_runtime_api_request(); macro_rules! query { @@ -367,7 +370,6 @@ where let sender = $sender; let api = client.runtime_api(); - use sp_api::ApiExt; let runtime_version = api.api_version::>(&BlockId::Hash(relay_parent)) .unwrap_or_else(|e| { tracing::warn!( @@ -404,6 +406,24 @@ where } match request { + Request::Version(sender) => { + let api = client.runtime_api(); + + let runtime_version = match api + .api_version::>(&BlockId::Hash(relay_parent)) + { + Ok(Some(v)) => Ok(v), + Ok(None) => Err(RuntimeApiError::NotSupported { runtime_api_name: "api_version" }), + Err(e) => Err(RuntimeApiError::Execution { + runtime_api_name: "api_version", + source: std::sync::Arc::new(e), + }), + }; + + let _ = sender.send(runtime_version.clone()); + runtime_version.ok().map(|v| RequestResult::Version(relay_parent, v)) + }, + Request::Authorities(sender) => query!(Authorities, authorities(), ver = 1, sender), Request::Validators(sender) => query!(Validators, validators(), ver = 1, sender), Request::ValidatorGroups(sender) => @@ -448,8 +468,6 @@ where Request::CandidateEvents(sender) => query!(CandidateEvents, candidate_events(), ver = 1, sender), Request::SessionInfo(index, sender) => { - use sp_api::ApiExt; - let api = client.runtime_api(); let block_id = BlockId::Hash(relay_parent); diff --git a/node/core/runtime-api/src/tests.rs b/node/core/runtime-api/src/tests.rs index d9e5700ff691..40027fe91a00 100644 --- a/node/core/runtime-api/src/tests.rs +++ b/node/core/runtime-api/src/tests.rs @@ -20,14 +20,11 @@ use ::test_helpers::{dummy_committed_candidate_receipt, dummy_validation_code}; use futures::channel::oneshot; use polkadot_node_primitives::{BabeAllowedSlots, BabeEpoch, BabeEpochConfiguration}; use polkadot_node_subsystem_test_helpers::make_subsystem_context; -use polkadot_primitives::{ - v1::{ - AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreState, - GroupRotationInfo, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, - OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes, SessionIndex, - ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature, - }, - v2::{PvfCheckStatement, SessionInfo}, +use polkadot_primitives::v2::{ + AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreState, GroupRotationInfo, + Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption, + PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, SessionIndex, SessionInfo, + ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature, }; use sp_core::testing::TaskExecutor; use std::{ @@ -111,7 +108,7 @@ sp_api::mock_impl_runtime_apis! { fn check_validation_outputs( &self, para_id: ParaId, - _commitments: polkadot_primitives::v1::CandidateCommitments, + _commitments: polkadot_primitives::v2::CandidateCommitments, ) -> bool { self.validation_outputs_results .get(¶_id) @@ -219,7 +216,7 @@ sp_api::mock_impl_runtime_apis! { } fn submit_report_equivocation_unsigned_extrinsic( - _equivocation_proof: sp_consensus_babe::EquivocationProof, + _equivocation_proof: sp_consensus_babe::EquivocationProof, _key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof, ) -> Option<()> { None @@ -442,7 +439,7 @@ fn requests_check_validation_outputs() { let relay_parent = [1; 32].into(); let para_a = 5.into(); let para_b = 6.into(); - let commitments = polkadot_primitives::v1::CandidateCommitments::default(); + let commitments = polkadot_primitives::v2::CandidateCommitments::default(); let spawner = sp_core::testing::TaskExecutor::new(); runtime_api.validation_outputs_results.insert(para_a, false); diff --git a/node/jaeger/src/spans.rs b/node/jaeger/src/spans.rs index 596d9fca7820..b7f82b133462 100644 --- a/node/jaeger/src/spans.rs +++ b/node/jaeger/src/spans.rs @@ -17,7 +17,7 @@ //! Polkadot Jaeger span definitions. //! //! ```rust -//! # use polkadot_primitives::v1::{CandidateHash, Hash}; +//! # use polkadot_primitives::v2::{CandidateHash, Hash}; //! # fn main() { //! use polkadot_node_jaeger as jaeger; //! @@ -51,7 +51,7 @@ //! over the course of a function, for this purpose use the non-consuming //! `fn` variants, i.e. //! ```rust -//! # use polkadot_primitives::v1::{CandidateHash, Hash}; +//! # use polkadot_primitives::v2::{CandidateHash, Hash}; //! # fn main() { //! # use polkadot_node_jaeger as jaeger; //! @@ -85,7 +85,7 @@ use parity_scale_codec::Encode; use polkadot_node_primitives::PoV; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ BlakeTwo256, CandidateHash, Hash, HashT, Id as ParaId, ValidatorIndex, }; use sc_network::PeerId; diff --git a/node/malus/src/variants/back_garbage_candidate.rs b/node/malus/src/variants/back_garbage_candidate.rs index 06938f2a4fea..210a03c0447f 100644 --- a/node/malus/src/variants/back_garbage_candidate.rs +++ b/node/malus/src/variants/back_garbage_candidate.rs @@ -40,7 +40,7 @@ use polkadot_node_subsystem_util as util; use crate::{interceptor::*, shared::*}; use polkadot_node_primitives::{PoV, ValidationResult}; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ CandidateCommitments, CandidateDescriptor, CandidateReceipt, PersistedValidationData, ValidationCode, }; diff --git a/node/malus/src/variants/suggest_garbage_candidate.rs b/node/malus/src/variants/suggest_garbage_candidate.rs index 82198c0a86b7..3d43f1c0054a 100644 --- a/node/malus/src/variants/suggest_garbage_candidate.rs +++ b/node/malus/src/variants/suggest_garbage_candidate.rs @@ -42,7 +42,7 @@ use polkadot_node_subsystem::{ use polkadot_node_subsystem_util as util; // Filter wrapping related types. use crate::interceptor::*; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ CandidateCommitments, CandidateReceipt, CommittedCandidateReceipt, CompactStatement, Hash, Signed, }; diff --git a/node/metrics/src/runtime/mod.rs b/node/metrics/src/runtime/mod.rs index 3e3ba84152ac..0b862445ac24 100644 --- a/node/metrics/src/runtime/mod.rs +++ b/node/metrics/src/runtime/mod.rs @@ -24,7 +24,7 @@ #![cfg(feature = "runtime-metrics")] use codec::Decode; -use primitives::v1::{ +use primitives::v2::{ metric_definitions::{CounterDefinition, CounterVecDefinition}, RuntimeMetricLabelValues, RuntimeMetricOp, RuntimeMetricUpdate, }; diff --git a/node/metrics/src/runtime/parachain.rs b/node/metrics/src/runtime/parachain.rs index e97e5e3093bd..d69a7fef97e3 100644 --- a/node/metrics/src/runtime/parachain.rs +++ b/node/metrics/src/runtime/parachain.rs @@ -18,7 +18,7 @@ //! All of the metrics have a correspondent runtime metric definition. use crate::runtime::RuntimeMetricsProvider; -use primitives::v1::metric_definitions::{ +use primitives::v2::metric_definitions::{ PARACHAIN_CREATE_INHERENT_BITFIELDS_SIGNATURE_CHECKS, PARACHAIN_INHERENT_DATA_BITFIELDS_PROCESSED, PARACHAIN_INHERENT_DATA_CANDIDATES_PROCESSED, PARACHAIN_INHERENT_DATA_DISPUTE_SETS_INCLUDED, PARACHAIN_INHERENT_DATA_DISPUTE_SETS_PROCESSED, diff --git a/node/metrics/src/tests.rs b/node/metrics/src/tests.rs index dd0353d3033d..75c67331fe8a 100644 --- a/node/metrics/src/tests.rs +++ b/node/metrics/src/tests.rs @@ -18,7 +18,7 @@ use hyper::{Client, Uri}; use polkadot_test_service::{node_config, run_validator_node, test_prometheus_config}; -use primitives::v1::metric_definitions::PARACHAIN_INHERENT_DATA_BITFIELDS_PROCESSED; +use primitives::v2::metric_definitions::PARACHAIN_INHERENT_DATA_BITFIELDS_PROCESSED; use sc_client_api::{execution_extensions::ExecutionStrategies, ExecutionStrategy}; use sp_keyring::AccountKeyring::*; use std::{collections::HashMap, convert::TryFrom}; diff --git a/node/network/approval-distribution/src/lib.rs b/node/network/approval-distribution/src/lib.rs index 97186e61aed5..96322b94ac41 100644 --- a/node/network/approval-distribution/src/lib.rs +++ b/node/network/approval-distribution/src/lib.rs @@ -40,7 +40,7 @@ use polkadot_node_subsystem_util::{ metrics::{self, prometheus}, MIN_GOSSIP_PEERS, }; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ BlockNumber, CandidateIndex, Hash, ValidatorIndex, ValidatorSignature, }; use std::collections::{hash_map, BTreeMap, HashMap, HashSet}; diff --git a/node/network/approval-distribution/src/tests.rs b/node/network/approval-distribution/src/tests.rs index 23fc49a77ed7..c177f28e6413 100644 --- a/node/network/approval-distribution/src/tests.rs +++ b/node/network/approval-distribution/src/tests.rs @@ -28,7 +28,7 @@ use std::time::Duration; type VirtualOverseer = test_helpers::TestSubsystemContextHandle; -fn dummy_signature() -> polkadot_primitives::v1::ValidatorSignature { +fn dummy_signature() -> polkadot_primitives::v2::ValidatorSignature { sp_core::crypto::UncheckedFrom::unchecked_from([1u8; 64]) } diff --git a/node/network/availability-distribution/src/error.rs b/node/network/availability-distribution/src/error.rs index 920eaef2395a..a336230fa7a6 100644 --- a/node/network/availability-distribution/src/error.rs +++ b/node/network/availability-distribution/src/error.rs @@ -19,7 +19,7 @@ use fatality::Nested; use polkadot_node_network_protocol::request_response::outgoing::RequestError; -use polkadot_primitives::v1::SessionIndex; +use polkadot_primitives::v2::SessionIndex; use futures::channel::oneshot; diff --git a/node/network/availability-distribution/src/pov_requester/mod.rs b/node/network/availability-distribution/src/pov_requester/mod.rs index 1e5c8b25ec7a..d46e58f1f271 100644 --- a/node/network/availability-distribution/src/pov_requester/mod.rs +++ b/node/network/availability-distribution/src/pov_requester/mod.rs @@ -25,7 +25,7 @@ use polkadot_node_network_protocol::request_response::{ }; use polkadot_node_primitives::PoV; use polkadot_node_subsystem_util::runtime::RuntimeInfo; -use polkadot_primitives::v1::{AuthorityDiscoveryId, CandidateHash, Hash, ValidatorIndex}; +use polkadot_primitives::v2::{AuthorityDiscoveryId, CandidateHash, Hash, ValidatorIndex}; use polkadot_subsystem::{ jaeger, messages::{IfDisconnected, NetworkBridgeMessage}, @@ -133,7 +133,7 @@ mod tests { use sp_core::testing::TaskExecutor; use polkadot_node_primitives::BlockData; - use polkadot_primitives::v1::{CandidateHash, Hash, ValidatorIndex}; + use polkadot_primitives::v2::{CandidateHash, Hash, ValidatorIndex}; use polkadot_subsystem::messages::{ AllMessages, AvailabilityDistributionMessage, RuntimeApiMessage, RuntimeApiRequest, }; diff --git a/node/network/availability-distribution/src/requester/fetch_task/mod.rs b/node/network/availability-distribution/src/requester/fetch_task/mod.rs index 480c3a889562..f5b57bdc8190 100644 --- a/node/network/availability-distribution/src/requester/fetch_task/mod.rs +++ b/node/network/availability-distribution/src/requester/fetch_task/mod.rs @@ -28,7 +28,7 @@ use polkadot_node_network_protocol::request_response::{ v1::{ChunkFetchingRequest, ChunkFetchingResponse}, }; use polkadot_node_primitives::ErasureChunk; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ AuthorityDiscoveryId, BlakeTwo256, CandidateHash, GroupIndex, Hash, HashT, OccupiedCore, SessionIndex, }; diff --git a/node/network/availability-distribution/src/requester/fetch_task/tests.rs b/node/network/availability-distribution/src/requester/fetch_task/tests.rs index c19c1f720f91..7f667bd8872d 100644 --- a/node/network/availability-distribution/src/requester/fetch_task/tests.rs +++ b/node/network/availability-distribution/src/requester/fetch_task/tests.rs @@ -30,7 +30,7 @@ use sp_keyring::Sr25519Keyring; use polkadot_node_network_protocol::request_response::{v1, Recipient}; use polkadot_node_primitives::{BlockData, PoV, Proof}; -use polkadot_primitives::v1::{CandidateHash, ValidatorIndex}; +use polkadot_primitives::v2::{CandidateHash, ValidatorIndex}; use super::*; use crate::{metrics::Metrics, tests::mock::get_valid_chunk_data}; diff --git a/node/network/availability-distribution/src/requester/mod.rs b/node/network/availability-distribution/src/requester/mod.rs index 14310b3384fd..3925e845dd64 100644 --- a/node/network/availability-distribution/src/requester/mod.rs +++ b/node/network/availability-distribution/src/requester/mod.rs @@ -33,7 +33,7 @@ use futures::{ }; use polkadot_node_subsystem_util::runtime::{get_occupied_cores, RuntimeInfo}; -use polkadot_primitives::v1::{CandidateHash, Hash, OccupiedCore}; +use polkadot_primitives::v2::{CandidateHash, Hash, OccupiedCore}; use polkadot_subsystem::{ messages::{AllMessages, ChainApiMessage}, ActivatedLeaf, ActiveLeavesUpdate, LeafStatus, SubsystemContext, diff --git a/node/network/availability-distribution/src/requester/session_cache.rs b/node/network/availability-distribution/src/requester/session_cache.rs index 7e3406e61769..23c98043e36c 100644 --- a/node/network/availability-distribution/src/requester/session_cache.rs +++ b/node/network/availability-distribution/src/requester/session_cache.rs @@ -20,7 +20,7 @@ use lru::LruCache; use rand::{seq::SliceRandom, thread_rng}; use polkadot_node_subsystem_util::runtime::RuntimeInfo; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ AuthorityDiscoveryId, GroupIndex, Hash, SessionIndex, ValidatorIndex, }; use polkadot_subsystem::SubsystemContext; diff --git a/node/network/availability-distribution/src/requester/tests.rs b/node/network/availability-distribution/src/requester/tests.rs index 3f6d284d9b92..a5096f9014b4 100644 --- a/node/network/availability-distribution/src/requester/tests.rs +++ b/node/network/availability-distribution/src/requester/tests.rs @@ -21,9 +21,8 @@ use futures::FutureExt; use polkadot_node_network_protocol::jaeger; use polkadot_node_primitives::{BlockData, ErasureChunk, PoV, SpawnNamed}; use polkadot_node_subsystem_util::runtime::RuntimeInfo; -use polkadot_primitives::{ - v1::{BlockNumber, CoreState, GroupIndex, Hash, Id, ScheduledCore, SessionIndex}, - v2::SessionInfo, +use polkadot_primitives::v2::{ + BlockNumber, CoreState, GroupIndex, Hash, Id, ScheduledCore, SessionIndex, SessionInfo, }; use polkadot_subsystem::{ diff --git a/node/network/availability-distribution/src/responder.rs b/node/network/availability-distribution/src/responder.rs index e4e9cb4eed9e..467d090ac5fa 100644 --- a/node/network/availability-distribution/src/responder.rs +++ b/node/network/availability-distribution/src/responder.rs @@ -26,7 +26,7 @@ use polkadot_node_network_protocol::{ UnifiedReputationChange as Rep, }; use polkadot_node_primitives::{AvailableData, ErasureChunk}; -use polkadot_primitives::v1::{CandidateHash, ValidatorIndex}; +use polkadot_primitives::v2::{CandidateHash, ValidatorIndex}; use polkadot_subsystem::{jaeger, messages::AvailabilityStoreMessage, SubsystemSender}; use crate::{ diff --git a/node/network/availability-distribution/src/tests/mock.rs b/node/network/availability-distribution/src/tests/mock.rs index 048fd1acae59..fbd42341098b 100644 --- a/node/network/availability-distribution/src/tests/mock.rs +++ b/node/network/availability-distribution/src/tests/mock.rs @@ -22,13 +22,10 @@ use sp_keyring::Sr25519Keyring; use polkadot_erasure_coding::{branches, obtain_chunks_v1 as obtain_chunks}; use polkadot_node_primitives::{AvailableData, BlockData, ErasureChunk, PoV, Proof}; -use polkadot_primitives::{ - v1::{ - CandidateCommitments, CandidateDescriptor, CandidateHash, CommittedCandidateReceipt, - GroupIndex, Hash, HeadData, Id as ParaId, OccupiedCore, PersistedValidationData, - ValidatorIndex, - }, - v2::SessionInfo, +use polkadot_primitives::v2::{ + CandidateCommitments, CandidateDescriptor, CandidateHash, CommittedCandidateReceipt, + GroupIndex, Hash, HeadData, Id as ParaId, OccupiedCore, PersistedValidationData, SessionInfo, + ValidatorIndex, }; use polkadot_primitives_test_helpers::{ dummy_collator, dummy_collator_signature, dummy_hash, dummy_validation_code, diff --git a/node/network/availability-distribution/src/tests/mod.rs b/node/network/availability-distribution/src/tests/mod.rs index b502c947dcff..d82c7f2f5a72 100644 --- a/node/network/availability-distribution/src/tests/mod.rs +++ b/node/network/availability-distribution/src/tests/mod.rs @@ -19,7 +19,7 @@ use std::collections::HashSet; use futures::{executor, future, Future}; use polkadot_node_network_protocol::request_response::IncomingRequest; -use polkadot_primitives::v1::CoreState; +use polkadot_primitives::v2::CoreState; use sp_keystore::SyncCryptoStorePtr; use polkadot_subsystem_testhelpers as test_helpers; diff --git a/node/network/availability-distribution/src/tests/state.rs b/node/network/availability-distribution/src/tests/state.rs index e9b81ee1aaf5..ff7685dc650d 100644 --- a/node/network/availability-distribution/src/tests/state.rs +++ b/node/network/availability-distribution/src/tests/state.rs @@ -39,9 +39,9 @@ use polkadot_node_network_protocol::{ request_response::{v1, IncomingRequest, OutgoingRequest, Requests}, }; use polkadot_node_primitives::ErasureChunk; -use polkadot_primitives::{ - v1::{CandidateHash, CoreState, GroupIndex, Hash, Id as ParaId, ScheduledCore, ValidatorIndex}, - v2::SessionInfo, +use polkadot_primitives::v2::{ + CandidateHash, CoreState, GroupIndex, Hash, Id as ParaId, ScheduledCore, SessionInfo, + ValidatorIndex, }; use polkadot_subsystem::{ messages::{ diff --git a/node/network/availability-recovery/src/lib.rs b/node/network/availability-recovery/src/lib.rs index 91596d9795de..870fad87ffae 100644 --- a/node/network/availability-recovery/src/lib.rs +++ b/node/network/availability-recovery/src/lib.rs @@ -49,12 +49,9 @@ use polkadot_node_network_protocol::{ }; use polkadot_node_primitives::{AvailableData, ErasureChunk}; use polkadot_node_subsystem_util::request_session_info; -use polkadot_primitives::{ - v1::{ - AuthorityDiscoveryId, BlakeTwo256, BlockNumber, CandidateHash, CandidateReceipt, - GroupIndex, Hash, HashT, SessionIndex, ValidatorId, ValidatorIndex, - }, - v2::SessionInfo, +use polkadot_primitives::v2::{ + AuthorityDiscoveryId, BlakeTwo256, BlockNumber, CandidateHash, CandidateReceipt, GroupIndex, + Hash, HashT, SessionIndex, SessionInfo, ValidatorId, ValidatorIndex, }; use polkadot_subsystem::{ errors::RecoveryError, diff --git a/node/network/availability-recovery/src/tests.rs b/node/network/availability-recovery/src/tests.rs index 2d4587d942c3..ccdc277cd1a2 100644 --- a/node/network/availability-recovery/src/tests.rs +++ b/node/network/availability-recovery/src/tests.rs @@ -30,7 +30,7 @@ use sc_network::config::RequestResponseConfig; use polkadot_erasure_coding::{branches, obtain_chunks_v1 as obtain_chunks}; use polkadot_node_primitives::{BlockData, PoV, Proof}; use polkadot_node_subsystem_util::TimeoutExt; -use polkadot_primitives::v1::{AuthorityDiscoveryId, HeadData, PersistedValidationData}; +use polkadot_primitives::v2::{AuthorityDiscoveryId, HeadData, PersistedValidationData}; use polkadot_primitives_test_helpers::{dummy_candidate_receipt, dummy_hash}; use polkadot_subsystem::{ jaeger, diff --git a/node/network/bitfield-distribution/src/lib.rs b/node/network/bitfield-distribution/src/lib.rs index c1d5c6fde6db..988126dd6936 100644 --- a/node/network/bitfield-distribution/src/lib.rs +++ b/node/network/bitfield-distribution/src/lib.rs @@ -32,7 +32,7 @@ use polkadot_node_subsystem_util::{ metrics::{self, prometheus}, MIN_GOSSIP_PEERS, }; -use polkadot_primitives::v1::{Hash, SignedAvailabilityBitfield, SigningContext, ValidatorId}; +use polkadot_primitives::v2::{Hash, SignedAvailabilityBitfield, SigningContext, ValidatorId}; use polkadot_subsystem::{ jaeger, messages::*, overseer, ActiveLeavesUpdate, FromOverseer, OverseerSignal, PerLeafSpan, SpawnedSubsystem, SubsystemContext, SubsystemError, SubsystemResult, diff --git a/node/network/bitfield-distribution/src/tests.rs b/node/network/bitfield-distribution/src/tests.rs index 049b04ca6a0f..f50a8a06d7c0 100644 --- a/node/network/bitfield-distribution/src/tests.rs +++ b/node/network/bitfield-distribution/src/tests.rs @@ -22,7 +22,7 @@ use maplit::hashmap; use polkadot_node_network_protocol::{our_view, view, ObservedRole}; use polkadot_node_subsystem_test_helpers::make_subsystem_context; use polkadot_node_subsystem_util::TimeoutExt; -use polkadot_primitives::v1::{AvailabilityBitfield, Signed, ValidatorIndex}; +use polkadot_primitives::v2::{AvailabilityBitfield, Signed, ValidatorIndex}; use polkadot_subsystem::jaeger; use sp_application_crypto::AppKey; use sp_keystore::{testing::KeyStore, SyncCryptoStore, SyncCryptoStorePtr}; diff --git a/node/network/bridge/src/lib.rs b/node/network/bridge/src/lib.rs index 1d92a95c148d..8be504da40ba 100644 --- a/node/network/bridge/src/lib.rs +++ b/node/network/bridge/src/lib.rs @@ -31,7 +31,7 @@ use polkadot_node_network_protocol::{ }; use polkadot_node_subsystem_util::metrics::{self, prometheus}; use polkadot_overseer::gen::{OverseerError, Subsystem}; -use polkadot_primitives::v1::{BlockNumber, Hash}; +use polkadot_primitives::v2::{BlockNumber, Hash}; use polkadot_subsystem::{ errors::{SubsystemError, SubsystemResult}, messages::{AllMessages, CollatorProtocolMessage, NetworkBridgeEvent, NetworkBridgeMessage}, diff --git a/node/network/bridge/src/network.rs b/node/network/bridge/src/network.rs index d5114f72b452..3d29e73fa229 100644 --- a/node/network/bridge/src/network.rs +++ b/node/network/bridge/src/network.rs @@ -31,7 +31,7 @@ use polkadot_node_network_protocol::{ request_response::{OutgoingRequest, Recipient, Requests}, PeerId, UnifiedReputationChange as Rep, }; -use polkadot_primitives::v1::{AuthorityDiscoveryId, Block, Hash}; +use polkadot_primitives::v2::{AuthorityDiscoveryId, Block, Hash}; use crate::validator_discovery::AuthorityDiscovery; diff --git a/node/network/bridge/src/tests.rs b/node/network/bridge/src/tests.rs index 30c1f964e520..75681ee7b5d6 100644 --- a/node/network/bridge/src/tests.rs +++ b/node/network/bridge/src/tests.rs @@ -33,7 +33,7 @@ use polkadot_node_subsystem_test_helpers::{ SingleItemSink, SingleItemStream, TestSubsystemContextHandle, }; use polkadot_node_subsystem_util::metered; -use polkadot_primitives::v1::AuthorityDiscoveryId; +use polkadot_primitives::v2::AuthorityDiscoveryId; use polkadot_primitives_test_helpers::dummy_collator_signature; use polkadot_subsystem::{ jaeger, diff --git a/node/network/bridge/src/validator_discovery.rs b/node/network/bridge/src/validator_discovery.rs index 324a7f29055a..11c6f9c5271b 100644 --- a/node/network/bridge/src/validator_discovery.rs +++ b/node/network/bridge/src/validator_discovery.rs @@ -30,7 +30,7 @@ use polkadot_node_network_protocol::{ peer_set::{PeerSet, PerPeerSet}, PeerId, }; -use polkadot_primitives::v1::AuthorityDiscoveryId; +use polkadot_primitives::v2::AuthorityDiscoveryId; const LOG_TARGET: &str = "parachain::validator-discovery"; diff --git a/node/network/collator-protocol/src/collator_side/mod.rs b/node/network/collator-protocol/src/collator_side/mod.rs index 1e13175bee7c..d1e5c5add718 100644 --- a/node/network/collator-protocol/src/collator_side/mod.rs +++ b/node/network/collator-protocol/src/collator_side/mod.rs @@ -40,7 +40,7 @@ use polkadot_node_subsystem_util::{ runtime::{get_availability_cores, get_group_rotation_info, RuntimeInfo}, TimeoutExt, }; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ AuthorityDiscoveryId, CandidateHash, CandidateReceipt, CollatorPair, CoreIndex, CoreState, Hash, Id as ParaId, }; diff --git a/node/network/collator-protocol/src/collator_side/tests.rs b/node/network/collator-protocol/src/collator_side/tests.rs index 526cfab04e19..10c1a032694d 100644 --- a/node/network/collator-protocol/src/collator_side/tests.rs +++ b/node/network/collator-protocol/src/collator_side/tests.rs @@ -32,12 +32,9 @@ use sp_runtime::traits::AppVerify; use polkadot_node_network_protocol::{our_view, request_response::IncomingRequest, view}; use polkadot_node_primitives::BlockData; use polkadot_node_subsystem_util::TimeoutExt; -use polkadot_primitives::{ - v1::{ - AuthorityDiscoveryId, CollatorPair, GroupRotationInfo, ScheduledCore, SessionIndex, - ValidatorId, ValidatorIndex, - }, - v2::SessionInfo, +use polkadot_primitives::v2::{ + AuthorityDiscoveryId, CollatorPair, GroupRotationInfo, ScheduledCore, SessionIndex, + SessionInfo, ValidatorId, ValidatorIndex, }; use polkadot_primitives_test_helpers::TestCandidateBuilder; use polkadot_subsystem::{ diff --git a/node/network/collator-protocol/src/lib.rs b/node/network/collator-protocol/src/lib.rs index b0f3d8b80fdb..eb6106b4e07f 100644 --- a/node/network/collator-protocol/src/lib.rs +++ b/node/network/collator-protocol/src/lib.rs @@ -31,7 +31,7 @@ use polkadot_node_network_protocol::{ request_response::{v1 as request_v1, IncomingRequestReceiver}, PeerId, UnifiedReputationChange as Rep, }; -use polkadot_primitives::v1::CollatorPair; +use polkadot_primitives::v2::CollatorPair; use polkadot_subsystem::{ errors::SubsystemError, diff --git a/node/network/collator-protocol/src/validator_side/mod.rs b/node/network/collator-protocol/src/validator_side/mod.rs index 0082b9190220..9b464749d188 100644 --- a/node/network/collator-protocol/src/validator_side/mod.rs +++ b/node/network/collator-protocol/src/validator_side/mod.rs @@ -44,7 +44,7 @@ use polkadot_node_network_protocol::{ }; use polkadot_node_primitives::{PoV, SignedFullStatement}; use polkadot_node_subsystem_util::metrics::{self, prometheus}; -use polkadot_primitives::v1::{CandidateReceipt, CollatorId, Hash, Id as ParaId}; +use polkadot_primitives::v2::{CandidateReceipt, CollatorId, Hash, Id as ParaId}; use polkadot_subsystem::{ jaeger, messages::{ diff --git a/node/network/collator-protocol/src/validator_side/tests.rs b/node/network/collator-protocol/src/validator_side/tests.rs index e15a7d2eeadd..2978a5c76e89 100644 --- a/node/network/collator-protocol/src/validator_side/tests.rs +++ b/node/network/collator-protocol/src/validator_side/tests.rs @@ -29,7 +29,7 @@ use polkadot_node_network_protocol::{ }; use polkadot_node_primitives::BlockData; use polkadot_node_subsystem_util::TimeoutExt; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ CollatorPair, CoreState, GroupIndex, GroupRotationInfo, OccupiedCore, ScheduledCore, ValidatorId, ValidatorIndex, }; @@ -132,7 +132,7 @@ fn test_harness>(test: impl FnOnce(TestHarne let keystore = TestKeyStore::new(); keystore .sr25519_generate_new( - polkadot_primitives::v1::PARACHAIN_KEY_TYPE_ID, + polkadot_primitives::v2::PARACHAIN_KEY_TYPE_ID, Some(&Sr25519Keyring::Alice.to_seed()), ) .unwrap(); diff --git a/node/network/dispute-distribution/src/sender/mod.rs b/node/network/dispute-distribution/src/sender/mod.rs index 0b0d90345d81..814e0b430067 100644 --- a/node/network/dispute-distribution/src/sender/mod.rs +++ b/node/network/dispute-distribution/src/sender/mod.rs @@ -21,7 +21,7 @@ use futures::channel::{mpsc, oneshot}; use polkadot_node_network_protocol::request_response::v1::DisputeRequest; use polkadot_node_primitives::{CandidateVotes, DisputeMessage, SignedDisputeStatement}; use polkadot_node_subsystem_util::runtime::RuntimeInfo; -use polkadot_primitives::v1::{CandidateHash, DisputeStatement, Hash, SessionIndex}; +use polkadot_primitives::v2::{CandidateHash, DisputeStatement, Hash, SessionIndex}; use polkadot_subsystem::{ messages::{AllMessages, DisputeCoordinatorMessage}, ActiveLeavesUpdate, SubsystemContext, diff --git a/node/network/dispute-distribution/src/sender/send_task.rs b/node/network/dispute-distribution/src/sender/send_task.rs index 7a7c4755d4ac..d42289a49ccb 100644 --- a/node/network/dispute-distribution/src/sender/send_task.rs +++ b/node/network/dispute-distribution/src/sender/send_task.rs @@ -27,7 +27,7 @@ use polkadot_node_network_protocol::{ IfDisconnected, }; use polkadot_node_subsystem_util::{metrics, runtime::RuntimeInfo}; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ AuthorityDiscoveryId, CandidateHash, Hash, SessionIndex, ValidatorIndex, }; use polkadot_subsystem::{ diff --git a/node/network/dispute-distribution/src/tests/mock.rs b/node/network/dispute-distribution/src/tests/mock.rs index 40c6d4b10526..08428d5852cc 100644 --- a/node/network/dispute-distribution/src/tests/mock.rs +++ b/node/network/dispute-distribution/src/tests/mock.rs @@ -32,12 +32,9 @@ use sp_keyring::Sr25519Keyring; use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use polkadot_node_primitives::{DisputeMessage, SignedDisputeStatement}; -use polkadot_primitives::{ - v1::{ - AuthorityDiscoveryId, CandidateHash, CandidateReceipt, Hash, SessionIndex, ValidatorId, - ValidatorIndex, - }, - v2::SessionInfo, +use polkadot_primitives::v2::{ + AuthorityDiscoveryId, CandidateHash, CandidateReceipt, Hash, SessionIndex, SessionInfo, + ValidatorId, ValidatorIndex, }; use polkadot_primitives_test_helpers::dummy_candidate_descriptor; @@ -198,7 +195,7 @@ impl MockAuthorityDiscovery { impl AuthorityDiscovery for MockAuthorityDiscovery { async fn get_addresses_by_authority_id( &mut self, - _authority: polkadot_primitives::v1::AuthorityDiscoveryId, + _authority: polkadot_primitives::v2::AuthorityDiscoveryId, ) -> Option> { panic!("Not implemented"); } @@ -206,7 +203,7 @@ impl AuthorityDiscovery for MockAuthorityDiscovery { async fn get_authority_ids_by_peer_id( &mut self, peer_id: polkadot_node_network_protocol::PeerId, - ) -> Option> { + ) -> Option> { for (a, p) in self.peer_ids.iter() { if p == &peer_id { return Some(HashSet::from([MOCK_VALIDATORS_DISCOVERY_KEYS diff --git a/node/network/dispute-distribution/src/tests/mod.rs b/node/network/dispute-distribution/src/tests/mod.rs index a34b4bc203a9..269176299559 100644 --- a/node/network/dispute-distribution/src/tests/mod.rs +++ b/node/network/dispute-distribution/src/tests/mod.rs @@ -41,9 +41,8 @@ use polkadot_node_network_protocol::{ IfDisconnected, }; use polkadot_node_primitives::{CandidateVotes, UncheckedDisputeMessage}; -use polkadot_primitives::{ - v1::{AuthorityDiscoveryId, CandidateHash, Hash, SessionIndex}, - v2::SessionInfo, +use polkadot_primitives::v2::{ + AuthorityDiscoveryId, CandidateHash, Hash, SessionIndex, SessionInfo, }; use polkadot_subsystem::{ messages::{ diff --git a/node/network/gossip-support/src/lib.rs b/node/network/gossip-support/src/lib.rs index a12fbf82d236..ee5aef8ee525 100644 --- a/node/network/gossip-support/src/lib.rs +++ b/node/network/gossip-support/src/lib.rs @@ -52,7 +52,7 @@ use polkadot_node_subsystem::{ SubsystemError, SubsystemSender, }; use polkadot_node_subsystem_util as util; -use polkadot_primitives::v1::{AuthorityDiscoveryId, Hash, SessionIndex}; +use polkadot_primitives::v2::{AuthorityDiscoveryId, Hash, SessionIndex}; #[cfg(test)] mod tests; diff --git a/node/network/gossip-support/src/tests.rs b/node/network/gossip-support/src/tests.rs index 5009742e8631..c1ed929d843b 100644 --- a/node/network/gossip-support/src/tests.rs +++ b/node/network/gossip-support/src/tests.rs @@ -91,14 +91,14 @@ impl MockAuthorityDiscovery { impl AuthorityDiscovery for MockAuthorityDiscovery { async fn get_addresses_by_authority_id( &mut self, - authority: polkadot_primitives::v1::AuthorityDiscoveryId, + authority: polkadot_primitives::v2::AuthorityDiscoveryId, ) -> Option> { self.addrs.get(&authority).cloned() } async fn get_authority_ids_by_peer_id( &mut self, peer_id: polkadot_node_network_protocol::PeerId, - ) -> Option> { + ) -> Option> { self.authorities.get(&peer_id).cloned() } } diff --git a/node/network/protocol/src/authority_discovery.rs b/node/network/protocol/src/authority_discovery.rs index b769ecad1746..4c7a7bc801b0 100644 --- a/node/network/protocol/src/authority_discovery.rs +++ b/node/network/protocol/src/authority_discovery.rs @@ -22,7 +22,7 @@ use async_trait::async_trait; use sc_authority_discovery::Service as AuthorityDiscoveryService; -use polkadot_primitives::v1::AuthorityDiscoveryId; +use polkadot_primitives::v2::AuthorityDiscoveryId; use sc_network::{Multiaddr, PeerId}; /// An abstraction over the authority discovery service. diff --git a/node/network/protocol/src/lib.rs b/node/network/protocol/src/lib.rs index e0fb2d2849d1..e97cb8820392 100644 --- a/node/network/protocol/src/lib.rs +++ b/node/network/protocol/src/lib.rs @@ -20,7 +20,7 @@ #![warn(missing_docs)] use parity_scale_codec::{Decode, Encode}; -use polkadot_primitives::v1::{BlockNumber, Hash}; +use polkadot_primitives::v2::{BlockNumber, Hash}; use std::{collections::HashMap, fmt}; #[doc(hidden)] @@ -169,7 +169,7 @@ impl std::ops::Deref for OurView { /// /// ``` /// # use polkadot_node_network_protocol::our_view; -/// # use polkadot_primitives::v1::Hash; +/// # use polkadot_primitives::v2::Hash; /// let our_view = our_view![Hash::repeat_byte(1), Hash::repeat_byte(2)]; /// ``` #[macro_export] @@ -203,7 +203,7 @@ pub struct View { /// /// ``` /// # use polkadot_node_network_protocol::view; -/// # use polkadot_primitives::v1::Hash; +/// # use polkadot_primitives::v2::Hash; /// let view = view![Hash::repeat_byte(1), Hash::repeat_byte(2)]; /// ``` #[macro_export] @@ -284,7 +284,7 @@ pub mod v1 { use parity_scale_codec::{Decode, Encode}; use std::convert::TryFrom; - use polkadot_primitives::v1::{ + use polkadot_primitives::v2::{ CandidateHash, CandidateIndex, CollatorId, CollatorSignature, CompactStatement, Hash, Id as ParaId, UncheckedSignedAvailabilityBitfield, ValidatorIndex, ValidatorSignature, }; diff --git a/node/network/protocol/src/request_response/mod.rs b/node/network/protocol/src/request_response/mod.rs index b4e013b5b107..8b55cdbc0f15 100644 --- a/node/network/protocol/src/request_response/mod.rs +++ b/node/network/protocol/src/request_response/mod.rs @@ -35,7 +35,7 @@ use std::{borrow::Cow, time::Duration, u64}; use futures::channel::mpsc; -use polkadot_primitives::v1::{MAX_CODE_SIZE, MAX_POV_SIZE}; +use polkadot_primitives::v2::{MAX_CODE_SIZE, MAX_POV_SIZE}; use strum::EnumIter; pub use sc_network::{config as network, config::RequestResponseConfig}; diff --git a/node/network/protocol/src/request_response/outgoing.rs b/node/network/protocol/src/request_response/outgoing.rs index 19aba34535d7..1f71b4510ea8 100644 --- a/node/network/protocol/src/request_response/outgoing.rs +++ b/node/network/protocol/src/request_response/outgoing.rs @@ -21,7 +21,7 @@ use parity_scale_codec::{Decode, Encode, Error as DecodingError}; use sc_network as network; use sc_network::PeerId; -use polkadot_primitives::v1::AuthorityDiscoveryId; +use polkadot_primitives::v2::AuthorityDiscoveryId; use super::{v1, IsRequest, Protocol}; diff --git a/node/network/protocol/src/request_response/v1.rs b/node/network/protocol/src/request_response/v1.rs index 8a63d653e8c7..5474070c94ae 100644 --- a/node/network/protocol/src/request_response/v1.rs +++ b/node/network/protocol/src/request_response/v1.rs @@ -21,7 +21,7 @@ use parity_scale_codec::{Decode, Encode}; use polkadot_node_primitives::{ AvailableData, DisputeMessage, ErasureChunk, PoV, Proof, UncheckedDisputeMessage, }; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ CandidateHash, CandidateReceipt, CommittedCandidateReceipt, Hash, Id as ParaId, ValidatorIndex, }; diff --git a/node/network/statement-distribution/src/error.rs b/node/network/statement-distribution/src/error.rs index 7ccd31a48fc7..9f0e30c730c3 100644 --- a/node/network/statement-distribution/src/error.rs +++ b/node/network/statement-distribution/src/error.rs @@ -19,7 +19,7 @@ use polkadot_node_network_protocol::PeerId; use polkadot_node_subsystem_util::runtime; -use polkadot_primitives::v1::{CandidateHash, Hash}; +use polkadot_primitives::v2::{CandidateHash, Hash}; use polkadot_subsystem::SubsystemError; use crate::LOG_TARGET; diff --git a/node/network/statement-distribution/src/lib.rs b/node/network/statement-distribution/src/lib.rs index 5b42cbaecd12..702e2db6a71d 100644 --- a/node/network/statement-distribution/src/lib.rs +++ b/node/network/statement-distribution/src/lib.rs @@ -34,7 +34,7 @@ use polkadot_node_network_protocol::{ use polkadot_node_primitives::{SignedFullStatement, Statement, UncheckedSignedFullStatement}; use polkadot_node_subsystem_util::{self as util, MIN_GOSSIP_PEERS}; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ AuthorityDiscoveryId, CandidateHash, CommittedCandidateReceipt, CompactStatement, Hash, SigningContext, ValidatorId, ValidatorIndex, ValidatorSignature, }; diff --git a/node/network/statement-distribution/src/requester.rs b/node/network/statement-distribution/src/requester.rs index bf82b14812ff..7bc70ea0505a 100644 --- a/node/network/statement-distribution/src/requester.rs +++ b/node/network/statement-distribution/src/requester.rs @@ -29,7 +29,7 @@ use polkadot_node_network_protocol::{ PeerId, UnifiedReputationChange, }; use polkadot_node_subsystem_util::TimeoutExt; -use polkadot_primitives::v1::{CandidateHash, CommittedCandidateReceipt, Hash}; +use polkadot_primitives::v2::{CandidateHash, CommittedCandidateReceipt, Hash}; use polkadot_subsystem::{Span, Stage}; use crate::{metrics::Metrics, COST_WRONG_HASH, LOG_TARGET}; diff --git a/node/network/statement-distribution/src/responder.rs b/node/network/statement-distribution/src/responder.rs index 74bcf679799b..6aca72bbabed 100644 --- a/node/network/statement-distribution/src/responder.rs +++ b/node/network/statement-distribution/src/responder.rs @@ -29,7 +29,7 @@ use polkadot_node_network_protocol::{ }, PeerId, UnifiedReputationChange as Rep, }; -use polkadot_primitives::v1::{CandidateHash, CommittedCandidateReceipt, Hash}; +use polkadot_primitives::v2::{CandidateHash, CommittedCandidateReceipt, Hash}; use crate::LOG_TARGET; diff --git a/node/network/statement-distribution/src/tests.rs b/node/network/statement-distribution/src/tests.rs index 1858eb8c09a3..5e885e71e0cd 100644 --- a/node/network/statement-distribution/src/tests.rs +++ b/node/network/statement-distribution/src/tests.rs @@ -28,7 +28,7 @@ use polkadot_node_network_protocol::{ }; use polkadot_node_primitives::Statement; use polkadot_node_subsystem_test_helpers::mock::make_ferdie_keystore; -use polkadot_primitives::{v1::ValidationCode, v2::SessionInfo}; +use polkadot_primitives::v2::{SessionInfo, ValidationCode}; use polkadot_primitives_test_helpers::{dummy_committed_candidate_receipt, dummy_hash}; use polkadot_subsystem::{ jaeger, diff --git a/node/overseer/examples/minimal-example.rs b/node/overseer/examples/minimal-example.rs index 966c51f9f217..14f8cf9d4ed7 100644 --- a/node/overseer/examples/minimal-example.rs +++ b/node/overseer/examples/minimal-example.rs @@ -33,7 +33,7 @@ use polkadot_overseer::{ gen::{FromOverseer, SpawnedSubsystem}, AllMessages, HeadSupportsParachains, OverseerSignal, SubsystemError, }; -use polkadot_primitives::v1::Hash; +use polkadot_primitives::v2::Hash; struct AlwaysSupportsParachains; impl HeadSupportsParachains for AlwaysSupportsParachains { diff --git a/node/overseer/src/lib.rs b/node/overseer/src/lib.rs index f12e21245a77..5fabcf018c17 100644 --- a/node/overseer/src/lib.rs +++ b/node/overseer/src/lib.rs @@ -71,10 +71,7 @@ use futures::{channel::oneshot, future::BoxFuture, select, Future, FutureExt, St use lru::LruCache; use client::{BlockImportNotification, BlockchainEvents, FinalityNotification}; -use polkadot_primitives::{ - v1::{Block, BlockId, BlockNumber, Hash}, - v2::ParachainHost, -}; +use polkadot_primitives::v2::{Block, BlockId, BlockNumber, Hash, ParachainHost}; use sp_api::{ApiExt, ProvideRuntimeApi}; use polkadot_node_network_protocol::v1 as protocol_v1; @@ -336,7 +333,7 @@ pub async fn forward_events>(client: Arc

, mut hand /// # use std::time::Duration; /// # use futures::{executor, pin_mut, select, FutureExt}; /// # use futures_timer::Delay; -/// # use polkadot_primitives::v1::Hash; +/// # use polkadot_primitives::v2::Hash; /// # use polkadot_overseer::{ /// # self as overseer, /// # OverseerSignal, diff --git a/node/overseer/src/tests.rs b/node/overseer/src/tests.rs index 761cb970cd1d..cc4bd38f05b0 100644 --- a/node/overseer/src/tests.rs +++ b/node/overseer/src/tests.rs @@ -28,7 +28,7 @@ use polkadot_node_subsystem_types::{ messages::{NetworkBridgeEvent, RuntimeApiRequest}, ActivatedLeaf, LeafStatus, }; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ CandidateHash, CollatorPair, InvalidDisputeStatementKind, ValidDisputeStatementKind, ValidatorIndex, }; diff --git a/node/primitives/src/approval.rs b/node/primitives/src/approval.rs index 5c644fc39fa5..d53a37ed4e7b 100644 --- a/node/primitives/src/approval.rs +++ b/node/primitives/src/approval.rs @@ -20,7 +20,7 @@ pub use sp_consensus_babe::Slot; pub use sp_consensus_vrf::schnorrkel::{Randomness, VRFOutput, VRFProof}; use parity_scale_codec::{Decode, Encode}; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ BlockNumber, CandidateHash, CandidateIndex, CoreIndex, Hash, Header, ValidatorIndex, ValidatorSignature, }; diff --git a/node/primitives/src/disputes/message.rs b/node/primitives/src/disputes/message.rs index 5c057e973bc0..88a65ab04015 100644 --- a/node/primitives/src/disputes/message.rs +++ b/node/primitives/src/disputes/message.rs @@ -24,9 +24,8 @@ use thiserror::Error; use parity_scale_codec::{Decode, Encode}; use super::{InvalidDisputeVote, SignedDisputeStatement, ValidDisputeVote}; -use polkadot_primitives::{ - v1::{CandidateReceipt, DisputeStatement, SessionIndex, ValidatorIndex}, - v2::SessionInfo, +use polkadot_primitives::v2::{ + CandidateReceipt, DisputeStatement, SessionIndex, SessionInfo, ValidatorIndex, }; /// A dispute initiating/participating message that is guaranteed to have been built from signed diff --git a/node/primitives/src/disputes/mod.rs b/node/primitives/src/disputes/mod.rs index fe5df710c76c..ae6c1c08cbfb 100644 --- a/node/primitives/src/disputes/mod.rs +++ b/node/primitives/src/disputes/mod.rs @@ -22,7 +22,7 @@ use sp_application_crypto::AppKey; use sp_keystore::{CryptoStore, Error as KeystoreError, SyncCryptoStorePtr}; use super::{Statement, UncheckedSignedFullStatement}; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ CandidateHash, CandidateReceipt, DisputeStatement, InvalidDisputeStatementKind, SessionIndex, SigningContext, ValidDisputeStatementKind, ValidatorId, ValidatorIndex, ValidatorSignature, }; diff --git a/node/primitives/src/lib.rs b/node/primitives/src/lib.rs index fd2268ab6023..2d09d9c96357 100644 --- a/node/primitives/src/lib.rs +++ b/node/primitives/src/lib.rs @@ -34,7 +34,7 @@ pub use sp_consensus_babe::{ }; pub use sp_core::traits::SpawnNamed; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ BlakeTwo256, CandidateCommitments, CandidateHash, CollatorPair, CommittedCandidateReceipt, CompactStatement, EncodeAs, Hash, HashT, HeadData, Id as ParaId, OutboundHrmpMessage, PersistedValidationData, SessionIndex, Signed, UncheckedSigned, UpwardMessage, ValidationCode, @@ -288,7 +288,7 @@ impl MaybeCompressedPoV { /// - contains a proof of validity. #[derive(Clone, Encode, Decode)] #[cfg(not(target_os = "unknown"))] -pub struct Collation { +pub struct Collation { /// Messages destined to be interpreted by the Relay chain itself. pub upward_messages: Vec, /// The horizontal messages sent by the parachain. diff --git a/node/service/src/chain_spec.rs b/node/service/src/chain_spec.rs index cb5f5692b5be..803e4e102b31 100644 --- a/node/service/src/chain_spec.rs +++ b/node/service/src/chain_spec.rs @@ -24,7 +24,7 @@ use kusama_runtime as kusama; use kusama_runtime_constants::currency::UNITS as KSM; use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use pallet_staking::Forcing; -use polkadot_primitives::v1::{AccountId, AccountPublic, AssignmentId, ValidatorId}; +use polkadot_primitives::v2::{AccountId, AccountPublic, AssignmentId, ValidatorId}; #[cfg(feature = "polkadot-native")] use polkadot_runtime as polkadot; #[cfg(feature = "polkadot-native")] @@ -64,9 +64,9 @@ const DEFAULT_PROTOCOL_ID: &str = "dot"; #[serde(rename_all = "camelCase")] pub struct Extensions { /// Block numbers with known hashes. - pub fork_blocks: sc_client_api::ForkBlocks, + pub fork_blocks: sc_client_api::ForkBlocks, /// Known bad block hashes. - pub bad_blocks: sc_client_api::BadBlocks, + pub bad_blocks: sc_client_api::BadBlocks, /// The light sync state. /// /// This value will be set by the `sync-state rpc` implementation. @@ -174,9 +174,9 @@ pub fn wococo_config() -> Result { ))] fn default_parachains_host_configuration( ) -> polkadot_runtime_parachains::configuration::HostConfiguration< - polkadot_primitives::v1::BlockNumber, + polkadot_primitives::v2::BlockNumber, > { - use polkadot_primitives::v1::{MAX_CODE_SIZE, MAX_POV_SIZE}; + use polkadot_primitives::v2::{MAX_CODE_SIZE, MAX_POV_SIZE}; polkadot_runtime_parachains::configuration::HostConfiguration { validation_upgrade_cooldown: 2u32, @@ -569,7 +569,7 @@ fn westend_staging_testnet_config_genesis(wasm_binary: &[u8]) -> westend::Genesi }, paras: Default::default(), registrar: westend_runtime::RegistrarConfig { - next_free_para_id: polkadot_primitives::v1::LOWEST_PUBLIC_ID, + next_free_para_id: polkadot_primitives::v2::LOWEST_PUBLIC_ID, }, xcm_pallet: Default::default(), } @@ -1062,7 +1062,7 @@ fn rococo_staging_testnet_config_genesis(wasm_binary: &[u8]) -> rococo_runtime:: config: default_parachains_host_configuration(), }, registrar: rococo_runtime::RegistrarConfig { - next_free_para_id: polkadot_primitives::v1::LOWEST_PUBLIC_ID, + next_free_para_id: polkadot_primitives::v2::LOWEST_PUBLIC_ID, }, xcm_pallet: Default::default(), transaction_payment: Default::default(), @@ -1502,7 +1502,7 @@ pub fn westend_testnet_genesis( }, paras: Default::default(), registrar: westend_runtime::RegistrarConfig { - next_free_para_id: polkadot_primitives::v1::LOWEST_PUBLIC_ID, + next_free_para_id: polkadot_primitives::v2::LOWEST_PUBLIC_ID, }, xcm_pallet: Default::default(), } @@ -1576,7 +1576,7 @@ pub fn rococo_testnet_genesis( }, paras: rococo_runtime::ParasConfig { paras: vec![] }, registrar: rococo_runtime::RegistrarConfig { - next_free_para_id: polkadot_primitives::v1::LOWEST_PUBLIC_ID, + next_free_para_id: polkadot_primitives::v2::LOWEST_PUBLIC_ID, }, xcm_pallet: Default::default(), transaction_payment: Default::default(), diff --git a/node/service/src/grandpa_support.rs b/node/service/src/grandpa_support.rs index 275d81ae49b9..f85249579ecf 100644 --- a/node/service/src/grandpa_support.rs +++ b/node/service/src/grandpa_support.rs @@ -23,7 +23,7 @@ use sp_runtime::traits::{Block as BlockT, Header as _, NumberFor}; use crate::HeaderProvider; #[cfg(feature = "full-node")] -use polkadot_primitives::v1::{Block, Hash}; +use polkadot_primitives::v2::{Block, Hash}; /// Returns the block hash of the block at the given `target_number` by walking /// backwards from the given `current_header`. diff --git a/node/service/src/lib.rs b/node/service/src/lib.rs index 59525774e10a..fd660f01f7fd 100644 --- a/node/service/src/lib.rs +++ b/node/service/src/lib.rs @@ -94,7 +94,7 @@ pub use polkadot_client::{ AbstractClient, Client, ClientHandle, ExecuteWithClient, FullBackend, FullClient, RuntimeApiCollection, }; -pub use polkadot_primitives::v1::{Block, BlockId, CollatorPair, Hash, Id as ParaId}; +pub use polkadot_primitives::v2::{Block, BlockId, CollatorPair, Hash, Id as ParaId}; pub use sc_client_api::{Backend, CallExecutor, ExecutionStrategy}; pub use sc_consensus::{BlockImport, LongestChain}; use sc_executor::NativeElseWasmExecutor; diff --git a/node/service/src/relay_chain_selection.rs b/node/service/src/relay_chain_selection.rs index 59f97ab7e2a3..c6c021dba2d1 100644 --- a/node/service/src/relay_chain_selection.rs +++ b/node/service/src/relay_chain_selection.rs @@ -40,7 +40,7 @@ use consensus_common::{Error as ConsensusError, SelectChain}; use futures::channel::oneshot; use polkadot_node_subsystem_util::metrics::{self, prometheus}; use polkadot_overseer::{AllMessages, Handle}; -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ Block as PolkadotBlock, BlockNumber, Hash, Header as PolkadotHeader, }; use polkadot_subsystem::messages::{ @@ -55,7 +55,7 @@ use std::sync::Arc; /// This is a safety net that should be removed at some point in the future. // Until it's not, make sure to also update `MAX_HEADS_LOOK_BACK` in `approval-voting` // and `MAX_BATCH_SCRAPE_ANCESTORS` in `dispute-coordinator` when changing its value. -const MAX_FINALITY_LAG: polkadot_primitives::v1::BlockNumber = 500; +const MAX_FINALITY_LAG: polkadot_primitives::v2::BlockNumber = 500; const LOG_TARGET: &str = "parachain::chain-selection"; diff --git a/node/service/src/tests.rs b/node/service/src/tests.rs index cb96a5b0ebeb..5fdf3ce5d478 100644 --- a/node/service/src/tests.rs +++ b/node/service/src/tests.rs @@ -36,7 +36,7 @@ use assert_matches::assert_matches; use std::{sync::Arc, time::Duration}; use futures::{channel::oneshot, prelude::*}; -use polkadot_primitives::v1::{Block, BlockNumber, Hash, Header}; +use polkadot_primitives::v2::{Block, BlockNumber, Hash, Header}; use polkadot_subsystem::messages::{ ApprovalVotingMessage, ChainSelectionMessage, DisputeCoordinatorMessage, HighestApprovedAncestorBlock, diff --git a/node/subsystem-test-helpers/src/lib.rs b/node/subsystem-test-helpers/src/lib.rs index b69760743def..06249e109d06 100644 --- a/node/subsystem-test-helpers/src/lib.rs +++ b/node/subsystem-test-helpers/src/lib.rs @@ -373,7 +373,7 @@ mod tests { use futures::executor::block_on; use polkadot_node_subsystem::messages::CollatorProtocolMessage; use polkadot_overseer::{dummy::dummy_overseer_builder, Handle, HeadSupportsParachains}; - use polkadot_primitives::v1::Hash; + use polkadot_primitives::v2::Hash; struct AlwaysSupportsParachains; impl HeadSupportsParachains for AlwaysSupportsParachains { diff --git a/node/subsystem-test-helpers/src/mock.rs b/node/subsystem-test-helpers/src/mock.rs index 0883bdf98a12..17692dda7ea2 100644 --- a/node/subsystem-test-helpers/src/mock.rs +++ b/node/subsystem-test-helpers/src/mock.rs @@ -21,7 +21,7 @@ use sp_application_crypto::AppKey; use sp_keyring::Sr25519Keyring; use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; -use polkadot_primitives::v1::{AuthorityDiscoveryId, ValidatorId}; +use polkadot_primitives::v2::{AuthorityDiscoveryId, ValidatorId}; /// Get mock keystore with `Ferdie` key. pub fn make_ferdie_keystore() -> SyncCryptoStorePtr { diff --git a/node/subsystem-types/src/lib.rs b/node/subsystem-types/src/lib.rs index e2150e14abe5..f6ff9bea7374 100644 --- a/node/subsystem-types/src/lib.rs +++ b/node/subsystem-types/src/lib.rs @@ -24,7 +24,7 @@ use std::{fmt, sync::Arc}; -pub use polkadot_primitives::v1::{BlockNumber, Hash}; +pub use polkadot_primitives::v2::{BlockNumber, Hash}; use smallvec::SmallVec; pub mod errors; diff --git a/node/subsystem-types/src/messages.rs b/node/subsystem-types/src/messages.rs index 56c5f93d37fa..8657ec16283b 100644 --- a/node/subsystem-types/src/messages.rs +++ b/node/subsystem-types/src/messages.rs @@ -38,19 +38,16 @@ use polkadot_node_primitives::{ CollationSecondedSignal, DisputeMessage, ErasureChunk, PoV, SignedDisputeStatement, SignedFullStatement, ValidationResult, }; -use polkadot_primitives::{ - v1::{ - AuthorityDiscoveryId, BackedCandidate, BlockNumber, CandidateDescriptor, CandidateEvent, - CandidateHash, CandidateIndex, CandidateReceipt, CollatorId, CommittedCandidateReceipt, - CoreState, GroupIndex, GroupRotationInfo, Hash, Header as BlockHeader, Id as ParaId, - InboundDownwardMessage, InboundHrmpMessage, MultiDisputeStatementSet, - OccupiedCoreAssumption, PersistedValidationData, SessionIndex, SignedAvailabilityBitfield, - SignedAvailabilityBitfields, ValidationCode, ValidationCodeHash, ValidatorId, - ValidatorIndex, ValidatorSignature, - }, - v2::{PvfCheckStatement, SessionInfo}, +use polkadot_primitives::v2::{ + AuthorityDiscoveryId, BackedCandidate, BlockNumber, CandidateDescriptor, CandidateEvent, + CandidateHash, CandidateIndex, CandidateReceipt, CollatorId, CommittedCandidateReceipt, + CoreState, GroupIndex, GroupRotationInfo, Hash, Header as BlockHeader, Id as ParaId, + InboundDownwardMessage, InboundHrmpMessage, MultiDisputeStatementSet, OccupiedCoreAssumption, + PersistedValidationData, PvfCheckStatement, SessionIndex, SessionInfo, + SignedAvailabilityBitfield, SignedAvailabilityBitfields, ValidationCode, ValidationCodeHash, + ValidatorId, ValidatorIndex, ValidatorSignature, }; -use polkadot_statement_table::v1::Misbehavior; +use polkadot_statement_table::v2::Misbehavior; use std::{ collections::{BTreeMap, HashSet}, sync::Arc, @@ -615,6 +612,8 @@ pub type RuntimeApiSender = oneshot::Sender), /// Get the next, current and some previous authority discovery set deduplicated. Authorities(RuntimeApiSender>), /// Get the current validator set. @@ -641,7 +640,7 @@ pub enum RuntimeApiRequest { /// Sends back `true` if the validation outputs pass all acceptance criteria checks. CheckValidationOutputs( ParaId, - polkadot_primitives::v1::CandidateCommitments, + polkadot_primitives::v2::CandidateCommitments, RuntimeApiSender, ), /// Get the session index that a child of the block will have. @@ -671,7 +670,7 @@ pub enum RuntimeApiRequest { /// Get information about the BABE epoch the block was included in. CurrentBabeEpoch(RuntimeApiSender), /// Get all disputes in relation to a relay parent. - FetchOnChainVotes(RuntimeApiSender>), + FetchOnChainVotes(RuntimeApiSender>), /// Submits a PVF pre-checking statement into the transaction pool. SubmitPvfCheckStatement(PvfCheckStatement, ValidatorSignature, RuntimeApiSender<()>), /// Returns code hashes of PVFs that require pre-checking by validators in the active set. diff --git a/node/subsystem-types/src/messages/network_bridge_event.rs b/node/subsystem-types/src/messages/network_bridge_event.rs index 959181a2bd1b..b8fe157cbef0 100644 --- a/node/subsystem-types/src/messages/network_bridge_event.rs +++ b/node/subsystem-types/src/messages/network_bridge_event.rs @@ -19,7 +19,7 @@ use std::{collections::HashSet, convert::TryFrom}; pub use sc_network::{PeerId, ReputationChange}; use polkadot_node_network_protocol::{ObservedRole, OurView, View, WrongVariant}; -use polkadot_primitives::v1::AuthorityDiscoveryId; +use polkadot_primitives::v2::AuthorityDiscoveryId; /// Events from network. #[derive(Debug, Clone, PartialEq)] diff --git a/node/subsystem-util/src/determine_new_blocks.rs b/node/subsystem-util/src/determine_new_blocks.rs index acb2d5dc6559..3c862b1fc704 100644 --- a/node/subsystem-util/src/determine_new_blocks.rs +++ b/node/subsystem-util/src/determine_new_blocks.rs @@ -18,7 +18,7 @@ use futures::{channel::oneshot, prelude::*}; use polkadot_node_subsystem::{messages::ChainApiMessage, SubsystemSender}; -use polkadot_primitives::v1::{BlockNumber, Hash, Header}; +use polkadot_primitives::v2::{BlockNumber, Hash, Header}; /// Given a new chain-head hash, this determines the hashes of all new blocks we should track /// metadata for, given this head. diff --git a/node/subsystem-util/src/lib.rs b/node/subsystem-util/src/lib.rs index b1a66ad94175..e7c7a1851323 100644 --- a/node/subsystem-util/src/lib.rs +++ b/node/subsystem-util/src/lib.rs @@ -49,14 +49,11 @@ use futures::{ use parity_scale_codec::Encode; use pin_project::pin_project; -use polkadot_primitives::{ - v1::{ - AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreState, EncodeAs, - GroupIndex, GroupRotationInfo, Hash, Id as ParaId, OccupiedCoreAssumption, - PersistedValidationData, SessionIndex, Signed, SigningContext, ValidationCode, - ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature, - }, - v2::SessionInfo, +use polkadot_primitives::v2::{ + AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreState, EncodeAs, + GroupIndex, GroupRotationInfo, Hash, Id as ParaId, OccupiedCoreAssumption, + PersistedValidationData, SessionIndex, SessionInfo, Signed, SigningContext, ValidationCode, + ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature, }; use sp_application_crypto::AppKey; use sp_core::{traits::SpawnNamed, ByteArray}; diff --git a/node/subsystem-util/src/rolling_session_window.rs b/node/subsystem-util/src/rolling_session_window.rs index 1f204d302677..c8a467d47d38 100644 --- a/node/subsystem-util/src/rolling_session_window.rs +++ b/node/subsystem-util/src/rolling_session_window.rs @@ -20,10 +20,7 @@ //! care about the state of particular blocks. pub use polkadot_node_primitives::{new_session_window_size, SessionWindowSize}; -use polkadot_primitives::{ - v1::{Hash, SessionIndex}, - v2::SessionInfo, -}; +use polkadot_primitives::v2::{Hash, SessionIndex, SessionInfo}; use futures::channel::oneshot; use polkadot_node_subsystem::{ @@ -279,7 +276,7 @@ mod tests { use assert_matches::assert_matches; use polkadot_node_subsystem::messages::{AllMessages, AvailabilityRecoveryMessage}; use polkadot_node_subsystem_test_helpers::make_subsystem_context; - use polkadot_primitives::v1::Header; + use polkadot_primitives::v2::Header; use sp_core::testing::TaskExecutor; pub const TEST_WINDOW_SIZE: SessionWindowSize = new_session_window_size!(6); diff --git a/node/subsystem-util/src/runtime/error.rs b/node/subsystem-util/src/runtime/error.rs index cfa532207953..67e69c91c1bd 100644 --- a/node/subsystem-util/src/runtime/error.rs +++ b/node/subsystem-util/src/runtime/error.rs @@ -20,7 +20,7 @@ use futures::channel::oneshot; use polkadot_node_subsystem::errors::RuntimeApiError; -use polkadot_primitives::v1::SessionIndex; +use polkadot_primitives::v2::SessionIndex; #[allow(missing_docs)] #[fatality::fatality(splitable)] diff --git a/node/subsystem-util/src/runtime/mod.rs b/node/subsystem-util/src/runtime/mod.rs index 46d33e639002..31a67a6859c7 100644 --- a/node/subsystem-util/src/runtime/mod.rs +++ b/node/subsystem-util/src/runtime/mod.rs @@ -26,13 +26,10 @@ use sp_core::crypto::ByteArray; use sp_keystore::{CryptoStore, SyncCryptoStorePtr}; use polkadot_node_subsystem::{SubsystemContext, SubsystemSender}; -use polkadot_primitives::{ - v1::{ - CandidateEvent, CoreState, EncodeAs, GroupIndex, GroupRotationInfo, Hash, OccupiedCore, - SessionIndex, Signed, SigningContext, UncheckedSigned, ValidationCode, ValidationCodeHash, - ValidatorId, ValidatorIndex, - }, - v2::SessionInfo, +use polkadot_primitives::v2::{ + CandidateEvent, CoreState, EncodeAs, GroupIndex, GroupRotationInfo, Hash, OccupiedCore, + SessionIndex, SessionInfo, Signed, SigningContext, UncheckedSigned, ValidationCode, + ValidationCodeHash, ValidatorId, ValidatorIndex, }; use crate::{ diff --git a/node/subsystem-util/src/tests.rs b/node/subsystem-util/src/tests.rs index bcc09a33e3f0..eb30c177f777 100644 --- a/node/subsystem-util/src/tests.rs +++ b/node/subsystem-util/src/tests.rs @@ -24,7 +24,7 @@ use polkadot_node_subsystem::{ ActivatedLeaf, ActiveLeavesUpdate, FromOverseer, LeafStatus, OverseerSignal, SpawnedSubsystem, }; use polkadot_node_subsystem_test_helpers::{self as test_helpers, make_subsystem_context}; -use polkadot_primitives::v1::Hash; +use polkadot_primitives::v2::Hash; use polkadot_primitives_test_helpers::{dummy_candidate_receipt, dummy_hash}; use std::{ pin::Pin, diff --git a/node/test/client/src/block_builder.rs b/node/test/client/src/block_builder.rs index cb938d65ca19..1ee6d1e87dc5 100644 --- a/node/test/client/src/block_builder.rs +++ b/node/test/client/src/block_builder.rs @@ -16,7 +16,7 @@ use crate::{Client, FullBackend}; use parity_scale_codec::{Decode, Encode}; -use polkadot_primitives::v1::{Block, InherentData as ParachainsInherentData}; +use polkadot_primitives::v2::{Block, InherentData as ParachainsInherentData}; use polkadot_test_runtime::{GetLastTimestamp, UncheckedExtrinsic}; use sc_block_builder::{BlockBuilder, BlockBuilderProvider}; use sp_api::ProvideRuntimeApi; @@ -110,7 +110,7 @@ impl InitPolkadotBlockBuilder for Client { inherent_data .put_data( - polkadot_primitives::v1::PARACHAINS_INHERENT_IDENTIFIER, + polkadot_primitives::v2::PARACHAINS_INHERENT_IDENTIFIER, ¶chains_inherent_data, ) .expect("Put parachains inherent data"); diff --git a/node/test/client/src/lib.rs b/node/test/client/src/lib.rs index 1485d61323f6..1370ec295788 100644 --- a/node/test/client/src/lib.rs +++ b/node/test/client/src/lib.rs @@ -20,7 +20,7 @@ mod block_builder; -use polkadot_primitives::v1::Block; +use polkadot_primitives::v2::Block; use sc_service::client; use sp_core::storage::Storage; use sp_runtime::BuildStorage; diff --git a/node/test/service/src/chain_spec.rs b/node/test/service/src/chain_spec.rs index 3004abae05af..5e81522994a3 100644 --- a/node/test/service/src/chain_spec.rs +++ b/node/test/service/src/chain_spec.rs @@ -19,7 +19,7 @@ use babe_primitives::AuthorityId as BabeId; use grandpa::AuthorityId as GrandpaId; use pallet_staking::Forcing; -use polkadot_primitives::v1::{AccountId, AssignmentId, ValidatorId, MAX_CODE_SIZE, MAX_POV_SIZE}; +use polkadot_primitives::v2::{AccountId, AssignmentId, ValidatorId, MAX_CODE_SIZE, MAX_POV_SIZE}; use polkadot_service::chain_spec::{get_account_id_from_seed, get_from_seed, Extensions}; use polkadot_test_runtime::BABE_GENESIS_EPOCH_CONFIG; use sc_chain_spec::{ChainSpec, ChainType}; diff --git a/node/test/service/src/lib.rs b/node/test/service/src/lib.rs index 112471025bc1..8cf75a75f62c 100644 --- a/node/test/service/src/lib.rs +++ b/node/test/service/src/lib.rs @@ -25,7 +25,7 @@ use futures::future::Future; use polkadot_node_primitives::{CollationGenerationConfig, CollatorFn}; use polkadot_node_subsystem::messages::{CollationGenerationMessage, CollatorProtocolMessage}; use polkadot_overseer::Handle; -use polkadot_primitives::v1::{Balance, CollatorPair, HeadData, Id as ParaId, ValidationCode}; +use polkadot_primitives::v2::{Balance, CollatorPair, HeadData, Id as ParaId, ValidationCode}; use polkadot_runtime_common::BlockHashCount; use polkadot_runtime_parachains::paras::ParaGenesisArgs; use polkadot_service::{ @@ -372,7 +372,7 @@ pub fn construct_extrinsic( UncheckedExtrinsic::new_signed( function.clone(), polkadot_test_runtime::Address::Id(caller.public().into()), - polkadot_primitives::v0::Signature::Sr25519(signature.clone()), + polkadot_primitives::v2::Signature::Sr25519(signature.clone()), extra.clone(), ) } diff --git a/parachain/test-parachains/adder/collator/src/lib.rs b/parachain/test-parachains/adder/collator/src/lib.rs index 061eec1db62b..1ab0fb1a4660 100644 --- a/parachain/test-parachains/adder/collator/src/lib.rs +++ b/parachain/test-parachains/adder/collator/src/lib.rs @@ -23,7 +23,7 @@ use polkadot_node_primitives::{ Collation, CollationResult, CollationSecondedSignal, CollatorFn, MaybeCompressedPoV, PoV, Statement, }; -use polkadot_primitives::v1::{CollatorId, CollatorPair}; +use polkadot_primitives::v2::{CollatorId, CollatorPair}; use sp_core::{traits::SpawnNamed, Pair}; use std::{ collections::HashMap, @@ -248,7 +248,7 @@ mod tests { use futures::executor::block_on; use polkadot_parachain::primitives::{ValidationParams, ValidationResult}; - use polkadot_primitives::v1::PersistedValidationData; + use polkadot_primitives::v2::PersistedValidationData; #[test] fn collator_works() { diff --git a/parachain/test-parachains/adder/collator/src/main.rs b/parachain/test-parachains/adder/collator/src/main.rs index 09f307e6fb75..57e4dea689e3 100644 --- a/parachain/test-parachains/adder/collator/src/main.rs +++ b/parachain/test-parachains/adder/collator/src/main.rs @@ -19,7 +19,7 @@ use polkadot_cli::{Error, Result}; use polkadot_node_primitives::CollationGenerationConfig; use polkadot_node_subsystem::messages::{CollationGenerationMessage, CollatorProtocolMessage}; -use polkadot_primitives::v1::Id as ParaId; +use polkadot_primitives::v2::Id as ParaId; use sc_cli::{Error as SubstrateCliError, Role, SubstrateCli}; use sp_core::hexdisplay::HexDisplay; use test_parachain_adder_collator::Collator; diff --git a/parachain/test-parachains/adder/collator/tests/integration.rs b/parachain/test-parachains/adder/collator/tests/integration.rs index 2db4e678f818..cb04fc942744 100644 --- a/parachain/test-parachains/adder/collator/tests/integration.rs +++ b/parachain/test-parachains/adder/collator/tests/integration.rs @@ -22,7 +22,7 @@ const PUPPET_EXE: &str = env!("CARGO_BIN_EXE_adder_collator_puppet_worker"); // If this test is failing, make sure to run all tests with the `real-overseer` feature being enabled. #[substrate_test_utils::test] async fn collating_using_adder_collator() { - use polkadot_primitives::v1::Id as ParaId; + use polkadot_primitives::v2::Id as ParaId; use sp_keyring::AccountKeyring::*; let mut builder = sc_cli::LoggerBuilder::new(""); diff --git a/parachain/test-parachains/undying/collator/src/lib.rs b/parachain/test-parachains/undying/collator/src/lib.rs index e4030a3e4dbb..8ca8e9409958 100644 --- a/parachain/test-parachains/undying/collator/src/lib.rs +++ b/parachain/test-parachains/undying/collator/src/lib.rs @@ -23,7 +23,7 @@ use polkadot_node_primitives::{ maybe_compress_pov, Collation, CollationResult, CollationSecondedSignal, CollatorFn, MaybeCompressedPoV, PoV, Statement, }; -use polkadot_primitives::v1::{CollatorId, CollatorPair, Hash}; +use polkadot_primitives::v2::{CollatorId, CollatorPair, Hash}; use sp_core::{traits::SpawnNamed, Pair}; use std::{ collections::HashMap, @@ -329,7 +329,7 @@ mod tests { use futures::executor::block_on; use polkadot_parachain::primitives::{ValidationParams, ValidationResult}; - use polkadot_primitives::v1::{Hash, PersistedValidationData}; + use polkadot_primitives::v2::{Hash, PersistedValidationData}; #[test] fn collator_works() { diff --git a/parachain/test-parachains/undying/collator/src/main.rs b/parachain/test-parachains/undying/collator/src/main.rs index e23ad8e7ebe5..d5abecdd93a4 100644 --- a/parachain/test-parachains/undying/collator/src/main.rs +++ b/parachain/test-parachains/undying/collator/src/main.rs @@ -19,7 +19,7 @@ use polkadot_cli::{Error, Result}; use polkadot_node_primitives::CollationGenerationConfig; use polkadot_node_subsystem::messages::{CollationGenerationMessage, CollatorProtocolMessage}; -use polkadot_primitives::v1::Id as ParaId; +use polkadot_primitives::v2::Id as ParaId; use sc_cli::{Error as SubstrateCliError, Role, SubstrateCli}; use sp_core::hexdisplay::HexDisplay; use test_parachain_undying_collator::Collator; diff --git a/parachain/test-parachains/undying/collator/tests/integration.rs b/parachain/test-parachains/undying/collator/tests/integration.rs index 69810fba4880..1adbe4e5db91 100644 --- a/parachain/test-parachains/undying/collator/tests/integration.rs +++ b/parachain/test-parachains/undying/collator/tests/integration.rs @@ -22,7 +22,7 @@ const PUPPET_EXE: &str = env!("CARGO_BIN_EXE_undying_collator_puppet_worker"); // If this test is failing, make sure to run all tests with the `real-overseer` feature being enabled. #[substrate_test_utils::test] async fn collating_using_undying_collator() { - use polkadot_primitives::v1::Id as ParaId; + use polkadot_primitives::v2::Id as ParaId; use sp_keyring::AccountKeyring::*; let mut builder = sc_cli::LoggerBuilder::new(""); diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index febcb175d0c9..c1cb635b8c8e 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -19,6 +19,4 @@ #![warn(missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] -pub mod v0; -pub mod v1; pub mod v2; diff --git a/primitives/src/v0.rs b/primitives/src/v0.rs deleted file mode 100644 index c4751babd35b..000000000000 --- a/primitives/src/v0.rs +++ /dev/null @@ -1,944 +0,0 @@ -// Copyright 2017-2020 Parity Technologies (UK) Ltd. -// This file is part of Polkadot. - -// Polkadot is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Polkadot is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Polkadot. If not, see . - -//! Primitives which are necessary for parachain execution from a relay-chain -//! perspective. - -use sp_std::{cmp::Ordering, prelude::*}; - -use bitvec::vec::BitVec; -use parity_scale_codec::{Decode, Encode}; -#[cfg(feature = "std")] -use parity_util_mem::{MallocSizeOf, MallocSizeOfOps}; -use scale_info::TypeInfo; -#[cfg(feature = "std")] -use serde::{Deserialize, Serialize}; - -use application_crypto::KeyTypeId; -use inherents::InherentIdentifier; -use primitives::RuntimeDebug; -use runtime_primitives::traits::{AppVerify, Block as BlockT}; - -pub use parity_scale_codec::Compact; -pub use polkadot_core_primitives::*; -pub use runtime_primitives::traits::{BlakeTwo256, Hash as HashT, IdentifyAccount, Verify}; - -pub use polkadot_parachain::primitives::{ - BlockData, HeadData, Id, UpwardMessage, ValidationCode, LOWEST_USER_ID, -}; - -/// The key type ID for a collator key. -pub const COLLATOR_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"coll"); - -/// An identifier for inherent data that provides new minimally-attested -/// parachain heads. -pub const NEW_HEADS_IDENTIFIER: InherentIdentifier = *b"newheads"; - -mod collator_app { - use application_crypto::{app_crypto, sr25519}; - app_crypto!(sr25519, super::COLLATOR_KEY_TYPE_ID); -} - -/// Identity that collators use. -pub type CollatorId = collator_app::Public; - -#[cfg(feature = "std")] -impl MallocSizeOf for CollatorId { - fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { - 0 - } - fn constant_size() -> Option { - Some(0) - } -} - -/// A Parachain collator keypair. -#[cfg(feature = "std")] -pub type CollatorPair = collator_app::Pair; - -/// Signature on candidate's block data by a collator. -pub type CollatorSignature = collator_app::Signature; - -#[cfg(feature = "std")] -impl MallocSizeOf for CollatorSignature { - fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { - 0 - } - fn constant_size() -> Option { - Some(0) - } -} - -/// The key type ID for a parachain validator key. -pub const PARACHAIN_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"para"); - -mod validator_app { - use application_crypto::{app_crypto, sr25519}; - app_crypto!(sr25519, super::PARACHAIN_KEY_TYPE_ID); -} - -/// Identity that parachain validators use when signing validation messages. -/// -/// For now we assert that parachain validator set is exactly equivalent to the authority set, and -/// so we define it to be the same type as `SessionKey`. In the future it may have different crypto. -pub type ValidatorId = validator_app::Public; - -#[cfg(feature = "std")] -impl MallocSizeOf for ValidatorId { - fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { - 0 - } - fn constant_size() -> Option { - Some(0) - } -} - -/// Index of the validator is used as a lightweight replacement of the `ValidatorId` when appropriate. -#[derive(Eq, Ord, PartialEq, PartialOrd, Copy, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash, MallocSizeOf))] -pub struct ValidatorIndex(pub u32); - -// We should really get https://github.com/paritytech/polkadot/issues/2403 going .. -impl From for ValidatorIndex { - fn from(n: u32) -> Self { - ValidatorIndex(n) - } -} - -application_crypto::with_pair! { - /// A Parachain validator keypair. - pub type ValidatorPair = validator_app::Pair; -} - -/// Signature with which parachain validators sign blocks. -/// -/// For now we assert that parachain validator set is exactly equivalent to the authority set, and -/// so we define it to be the same type as `SessionKey`. In the future it may have different crypto. -pub type ValidatorSignature = validator_app::Signature; - -#[cfg(feature = "std")] -impl MallocSizeOf for ValidatorSignature { - fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { - 0 - } - fn constant_size() -> Option { - Some(0) - } -} - -/// Retriability for a given active para. -#[derive(Clone, Eq, PartialEq, Encode, Decode, TypeInfo)] -#[cfg_attr(feature = "std", derive(Debug))] -pub enum Retriable { - /// Ineligible for retry. This means it's either a parachain that is always scheduled anyway or - /// has been removed/swapped. - Never, - /// Eligible for retry; the associated value is the number of retries that the para already had. - WithRetries(u32), -} - -/// Type determining the active set of parachains in current block. -pub trait ActiveParas { - /// Return the active set of parachains in current block. This attempts to keep any IDs in the - /// same place between sequential blocks. It is therefore unordered. The second item in the - /// tuple is the required collator ID, if any. If `Some`, then it is invalid to include any - /// other collator's block. - /// - /// NOTE: The initial implementation simply concatenates the (ordered) set of (permanent) - /// parachain IDs with the (unordered) set of parathread IDs selected for this block. - fn active_paras() -> Vec<(Id, Option<(CollatorId, Retriable)>)>; -} - -/// Description of how often/when this parachain is scheduled for progression. -#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)] -pub enum Scheduling { - /// Scheduled every block. - Always, - /// Scheduled dynamically (i.e. a parathread). - Dynamic, -} - -/// Information regarding a deployed parachain/thread. -#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)] -pub struct Info { - /// Scheduling info. - pub scheduling: Scheduling, -} - -/// An `Info` value for a standard leased parachain. -pub const PARACHAIN_INFO: Info = Info { scheduling: Scheduling::Always }; - -/// Auxiliary for when there's an attempt to swap two parachains/parathreads. -pub trait SwapAux { - /// Result describing whether it is possible to swap two parachains. Doesn't mutate state. - fn ensure_can_swap(one: Id, other: Id) -> Result<(), &'static str>; - - /// Updates any needed state/references to enact a logical swap of two parachains. Identity, - /// code and `head_data` remain equivalent for all parachains/threads, however other properties - /// such as leases, deposits held and thread/chain nature are swapped. - /// - /// May only be called on a state that `ensure_can_swap` has previously returned `Ok` for: if this is - /// not the case, the result is undefined. May only return an error if `ensure_can_swap` also returns - /// an error. - fn on_swap(one: Id, other: Id) -> Result<(), &'static str>; -} - -impl SwapAux for () { - fn ensure_can_swap(_: Id, _: Id) -> Result<(), &'static str> { - Err("Swapping disabled") - } - fn on_swap(_: Id, _: Id) -> Result<(), &'static str> { - Err("Swapping disabled") - } -} - -/// Identifier for a chain, either one of a number of parachains or the relay chain. -#[derive(Copy, Clone, PartialEq, Encode, Decode, TypeInfo, RuntimeDebug)] -pub enum Chain { - /// The relay chain. - Relay, - /// A parachain of the given index. - Parachain(Id), -} - -/// The duty roster specifying what jobs each validator must do. -#[derive(Clone, PartialEq, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Default))] -pub struct DutyRoster { - /// Lookup from validator index to chain on which that validator has a duty to validate. - pub validator_duty: Vec, -} - -/// Extra data that is needed along with the other fields in a `CandidateReceipt` -/// to fully validate the candidate. -/// -/// These are global parameters that apply to all parachain candidates in a block. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Default))] -pub struct GlobalValidationData { - /// The maximum code size permitted, in bytes. - pub max_code_size: u32, - /// The maximum head-data size permitted, in bytes. - pub max_head_data_size: u32, - /// The relay-chain block number this is in the context of. - pub block_number: N, -} - -/// Extra data that is needed along with the other fields in a `CandidateReceipt` -/// to fully validate the candidate. These fields are parachain-specific. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Default))] -pub struct LocalValidationData { - /// The parent head-data. - pub parent_head: HeadData, - /// The balance of the parachain at the moment of validation. - pub balance: Balance, - /// Whether the parachain is allowed to upgrade its validation code. - /// - /// This is `Some` if so, and contains the number of the minimum relay-chain - /// height at which the upgrade will be applied, if an upgrade is signaled - /// now. - /// - /// A parachain should enact its side of the upgrade at the end of the first - /// parablock executing in the context of a relay-chain block with at least this - /// height. This may be equal to the current perceived relay-chain block height, in - /// which case the code upgrade should be applied at the end of the signaling - /// block. - pub code_upgrade_allowed: Option, -} - -/// Commitments made in a `CandidateReceipt`. Many of these are outputs of validation. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Default))] -pub struct CandidateCommitments { - /// Fees paid from the chain to the relay chain validators. - pub fees: Balance, - /// Messages destined to be interpreted by the Relay chain itself. - pub upward_messages: Vec, - /// The root of a block's erasure encoding Merkle tree. - pub erasure_root: H, - /// New validation code. - pub new_validation_code: Option, - /// Number of `DownwardMessage`'s that were processed by the Parachain. - /// - /// It is expected that the Parachain processes them from first to last. - pub processed_downward_messages: u32, -} - -/// Get a collator signature payload on a relay-parent, block-data combo. -pub fn collator_signature_payload>( - relay_parent: &H, - parachain_index: &Id, - pov_block_hash: &H, -) -> [u8; 68] { - // 32-byte hash length is protected in a test below. - let mut payload = [0u8; 68]; - - payload[0..32].copy_from_slice(relay_parent.as_ref()); - u32::from(*parachain_index).using_encoded(|s| payload[32..32 + s.len()].copy_from_slice(s)); - payload[36..68].copy_from_slice(pov_block_hash.as_ref()); - - payload -} - -fn check_collator_signature>( - relay_parent: &H, - parachain_index: &Id, - pov_block_hash: &H, - collator: &CollatorId, - signature: &CollatorSignature, -) -> Result<(), ()> { - let payload = collator_signature_payload(relay_parent, parachain_index, pov_block_hash); - if signature.verify(&payload[..], collator) { - Ok(()) - } else { - Err(()) - } -} - -/// All data pertaining to the execution of a parachain candidate. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -pub struct CandidateReceipt { - /// The ID of the parachain this is a candidate for. - pub parachain_index: Id, - /// The hash of the relay-chain block this should be executed in - /// the context of. - pub relay_parent: H, - /// The head-data - pub head_data: HeadData, - /// The collator's relay-chain account ID - pub collator: CollatorId, - /// Signature on blake2-256 of the block data by collator. - pub signature: CollatorSignature, - /// The hash of the PoV-block. - pub pov_block_hash: H, - /// The global validation schedule. - pub global_validation: GlobalValidationData, - /// The local validation data. - pub local_validation: LocalValidationData, - /// Commitments made as a result of validation. - pub commitments: CandidateCommitments, -} - -impl, N> CandidateReceipt { - /// Check integrity vs. provided block data. - pub fn check_signature(&self) -> Result<(), ()> { - check_collator_signature( - &self.relay_parent, - &self.parachain_index, - &self.pov_block_hash, - &self.collator, - &self.signature, - ) - } - - /// Abridge this `CandidateReceipt`, splitting it into an `AbridgedCandidateReceipt` - /// and its omitted component. - pub fn abridge(self) -> (AbridgedCandidateReceipt, OmittedValidationData) { - let CandidateReceipt { - parachain_index, - relay_parent, - head_data, - collator, - signature, - pov_block_hash, - global_validation, - local_validation, - commitments, - } = self; - - let abridged = AbridgedCandidateReceipt { - parachain_index, - relay_parent, - head_data, - collator, - signature, - pov_block_hash, - commitments, - }; - - let omitted = OmittedValidationData { global_validation, local_validation }; - - (abridged, omitted) - } -} - -impl PartialOrd for CandidateReceipt { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl Ord for CandidateReceipt { - fn cmp(&self, other: &Self) -> Ordering { - // TODO: compare signatures or something more sane - // https://github.com/paritytech/polkadot/issues/222 - self.parachain_index - .cmp(&other.parachain_index) - .then_with(|| self.head_data.cmp(&other.head_data)) - } -} - -/// All the data which is omitted in an `AbridgedCandidateReceipt`, but that -/// is necessary for validation of the parachain candidate. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Default))] -pub struct OmittedValidationData { - /// The global validation schedule. - pub global_validation: GlobalValidationData, - /// The local validation data. - pub local_validation: LocalValidationData, -} - -/// An abridged candidate-receipt. -/// -/// Much info in a candidate-receipt is duplicated from the relay-chain state. -/// When submitting to the relay-chain, this data should be omitted as it can -/// be re-generated from relay-chain state. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -pub struct AbridgedCandidateReceipt { - /// The ID of the parachain this is a candidate for. - pub parachain_index: Id, - /// The hash of the relay-chain block this should be executed in - /// the context of. - // NOTE: the fact that the hash includes this value means that code depends - // on this for deduplication. Removing this field is likely to break things. - pub relay_parent: H, - /// The head-data - pub head_data: HeadData, - /// The collator's relay-chain account ID - pub collator: CollatorId, - /// Signature on blake2-256 of the block data by collator. - pub signature: CollatorSignature, - /// The hash of the `pov-block`. - pub pov_block_hash: H, - /// Commitments made as a result of validation. - pub commitments: CandidateCommitments, -} - -/// A candidate-receipt with commitments directly included. -pub struct CommitedCandidateReceipt { - /// The descriptor of the candidate. - pub descriptor: CandidateDescriptor, - - /// The commitments of the candidate receipt. - pub commitments: CandidateCommitments, -} - -impl + Encode> AbridgedCandidateReceipt { - /// Check integrity vs. provided block data. - pub fn check_signature(&self) -> Result<(), ()> { - check_collator_signature( - &self.relay_parent, - &self.parachain_index, - &self.pov_block_hash, - &self.collator, - &self.signature, - ) - } - - /// Compute the hash of the abridged candidate receipt. - /// - /// This is often used as the canonical hash of the receipt, rather than - /// the hash of the full receipt. The reason being that all data in the full - /// receipt is committed to in the abridged receipt; this receipt references - /// the relay-chain block in which context it should be executed, which implies - /// any blockchain state that must be referenced. - pub fn hash(&self) -> Hash { - BlakeTwo256::hash_of(self) - } -} - -impl AbridgedCandidateReceipt { - /// Combine the abridged candidate receipt with the omitted data, - /// forming a full `CandidateReceipt`. - pub fn complete(self, omitted: OmittedValidationData) -> CandidateReceipt { - let AbridgedCandidateReceipt { - parachain_index, - relay_parent, - head_data, - collator, - signature, - pov_block_hash, - commitments, - } = self; - - let OmittedValidationData { global_validation, local_validation } = omitted; - - CandidateReceipt { - parachain_index, - relay_parent, - head_data, - collator, - signature, - pov_block_hash, - local_validation, - global_validation, - commitments, - } - } - - /// Clone the relevant portions of the `CandidateReceipt` to form a `CollationInfo`. - pub fn to_collation_info(&self) -> CollationInfo { - let AbridgedCandidateReceipt { - parachain_index, - relay_parent, - head_data, - collator, - signature, - pov_block_hash, - commitments: _commitments, - } = self; - - CollationInfo { - parachain_index: *parachain_index, - relay_parent: *relay_parent, - head_data: head_data.clone(), - collator: collator.clone(), - signature: signature.clone(), - pov_block_hash: *pov_block_hash, - } - } - - /// Clone the relevant portions of the `AbridgedCandidateReceipt` to form a `CandidateDescriptor`. - pub fn to_descriptor(&self) -> CandidateDescriptor { - CandidateDescriptor { - para_id: self.parachain_index, - relay_parent: self.relay_parent, - collator: self.collator.clone(), - signature: self.signature.clone(), - pov_hash: self.pov_block_hash.clone(), - } - } -} - -impl PartialOrd for AbridgedCandidateReceipt { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl Ord for AbridgedCandidateReceipt { - fn cmp(&self, other: &Self) -> Ordering { - // TODO: compare signatures or something more sane - // https://github.com/paritytech/polkadot/issues/222 - self.parachain_index - .cmp(&other.parachain_index) - .then_with(|| self.head_data.cmp(&other.head_data)) - } -} - -/// A unique descriptor of the candidate receipt, in a lightweight format. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -pub struct CandidateDescriptor { - /// The ID of the para this is a candidate for. - pub para_id: Id, - /// The hash of the relay-chain block this should be executed in - /// the context of. - // NOTE: the fact that the hash includes this value means that code depends - // on this for deduplication. Removing this field is likely to break things. - pub relay_parent: H, - /// The collator's relay-chain account ID - pub collator: CollatorId, - /// Signature on blake2-256 of components of this receipt: - /// The para ID, the relay parent, and the `pov_hash`. - pub signature: CollatorSignature, - /// The hash of the `pov-block`. - pub pov_hash: H, -} - -/// A collation sent by a collator. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -pub struct CollationInfo { - /// The ID of the parachain this is a candidate for. - pub parachain_index: Id, - /// The relay-chain block hash this block should execute in the - /// context of. - pub relay_parent: Hash, - /// The collator's relay-chain account ID - pub collator: CollatorId, - /// Signature on blake2-256 of the block data by collator. - pub signature: CollatorSignature, - /// The head-data - pub head_data: HeadData, - /// blake2-256 Hash of the `pov-block` - pub pov_block_hash: Hash, -} - -impl CollationInfo { - /// Check integrity vs. a `pov-block`. - pub fn check_signature(&self) -> Result<(), ()> { - check_collator_signature( - &self.relay_parent, - &self.parachain_index, - &self.pov_block_hash, - &self.collator, - &self.signature, - ) - } - - /// Turn this into an `AbridgedCandidateReceipt` by supplying a set of commitments. - pub fn into_receipt(self, commitments: CandidateCommitments) -> AbridgedCandidateReceipt { - let CollationInfo { - parachain_index, - relay_parent, - collator, - signature, - head_data, - pov_block_hash, - } = self; - - AbridgedCandidateReceipt { - parachain_index, - relay_parent, - collator, - signature, - head_data, - pov_block_hash, - commitments, - } - } -} - -/// A full collation. -#[derive(PartialEq, Eq, Clone, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Encode, Decode, TypeInfo))] -pub struct Collation { - /// Candidate receipt itself. - pub info: CollationInfo, - /// A proof-of-validation for the receipt. - pub pov: PoVBlock, -} - -/// A Proof-of-Validation block. -#[derive(PartialEq, Eq, Clone, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Encode, Decode, TypeInfo))] -pub struct PoVBlock { - /// Block data. - pub block_data: BlockData, -} - -impl PoVBlock { - /// Compute hash of block data. - #[cfg(feature = "std")] - pub fn hash(&self) -> Hash { - BlakeTwo256::hash_of(&self) - } -} - -/// The data that is kept available about a particular parachain block. -#[derive(PartialEq, Eq, Clone, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Encode, Decode, TypeInfo))] -pub struct AvailableData { - /// The PoV block. - pub pov_block: PoVBlock, - /// Data that is omitted from an abridged candidate receipt - /// that is necessary for validation. - pub omitted_validation: OmittedValidationData, - // In the future, outgoing messages as well. -} - -const BACKING_STATEMENT_MAGIC: [u8; 4] = *b"BKNG"; - -/// Statements that can be made about parachain candidates. These are the -/// actual values that are signed. -#[derive(Clone, PartialEq, Eq, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Hash))] -pub enum CompactStatement { - /// Proposal of a parachain candidate. - Seconded(CandidateHash), - /// State that a parachain candidate is valid. - Valid(CandidateHash), -} - -impl CompactStatement { - /// Yields the payload used for validator signatures on this kind - /// of statement. - pub fn signing_payload(&self, context: &SigningContext) -> Vec { - (self, context).encode() - } -} - -// Inner helper for codec on `CompactStatement`. -#[derive(Encode, Decode, TypeInfo)] -enum CompactStatementInner { - #[codec(index = 1)] - Seconded(CandidateHash), - #[codec(index = 2)] - Valid(CandidateHash), -} - -impl From for CompactStatementInner { - fn from(s: CompactStatement) -> Self { - match s { - CompactStatement::Seconded(h) => CompactStatementInner::Seconded(h), - CompactStatement::Valid(h) => CompactStatementInner::Valid(h), - } - } -} - -impl parity_scale_codec::Encode for CompactStatement { - fn size_hint(&self) -> usize { - // magic + discriminant + payload - 4 + 1 + 32 - } - - fn encode_to(&self, dest: &mut T) { - dest.write(&BACKING_STATEMENT_MAGIC); - CompactStatementInner::from(self.clone()).encode_to(dest) - } -} - -impl parity_scale_codec::Decode for CompactStatement { - fn decode( - input: &mut I, - ) -> Result { - let maybe_magic = <[u8; 4]>::decode(input)?; - if maybe_magic != BACKING_STATEMENT_MAGIC { - return Err(parity_scale_codec::Error::from("invalid magic string")) - } - - Ok(match CompactStatementInner::decode(input)? { - CompactStatementInner::Seconded(h) => CompactStatement::Seconded(h), - CompactStatementInner::Valid(h) => CompactStatement::Valid(h), - }) - } -} - -impl CompactStatement { - /// Get the underlying candidate hash this references. - pub fn candidate_hash(&self) -> &CandidateHash { - match *self { - CompactStatement::Seconded(ref h) | CompactStatement::Valid(ref h) => h, - } - } -} - -/// An either implicit or explicit attestation to the validity of a parachain -/// candidate. -#[derive(Clone, Eq, PartialEq, Decode, Encode, RuntimeDebug, TypeInfo)] -#[cfg_attr(feature = "std", derive(MallocSizeOf))] -pub enum ValidityAttestation { - /// Implicit validity attestation by issuing. - /// This corresponds to issuance of a `Candidate` statement. - #[codec(index = 1)] - Implicit(ValidatorSignature), - /// An explicit attestation. This corresponds to issuance of a - /// `Valid` statement. - #[codec(index = 2)] - Explicit(ValidatorSignature), -} - -impl ValidityAttestation { - /// Produce the underlying signed payload of the attestation, given the hash of the candidate, - /// which should be known in context. - pub fn to_compact_statement(&self, candidate_hash: CandidateHash) -> CompactStatement { - // Explicit and implicit map directly from - // `ValidityVote::Valid` and `ValidityVote::Issued`, and hence there is a - // `1:1` relationshow which enables the conversion. - match *self { - ValidityAttestation::Implicit(_) => CompactStatement::Seconded(candidate_hash), - ValidityAttestation::Explicit(_) => CompactStatement::Valid(candidate_hash), - } - } - - /// Get a reference to the signature. - pub fn signature(&self) -> &ValidatorSignature { - match *self { - ValidityAttestation::Implicit(ref sig) => sig, - ValidityAttestation::Explicit(ref sig) => sig, - } - } - - /// Produce the underlying signed payload of the attestation, given the hash of the candidate, - /// which should be known in context. - pub fn signed_payload( - &self, - candidate_hash: CandidateHash, - signing_context: &SigningContext, - ) -> Vec { - match *self { - ValidityAttestation::Implicit(_) => - (CompactStatement::Seconded(candidate_hash), signing_context).encode(), - ValidityAttestation::Explicit(_) => - (CompactStatement::Valid(candidate_hash), signing_context).encode(), - } - } -} - -/// A type returned by runtime with current session index and a parent hash. -#[derive(Clone, Eq, PartialEq, Default, Decode, Encode, RuntimeDebug)] -pub struct SigningContext { - /// Current session index. - pub session_index: sp_staking::SessionIndex, - /// Hash of the parent. - pub parent_hash: H, -} - -/// An attested candidate. This is submitted to the relay chain by a block author. -#[derive(Clone, PartialEq, Decode, Encode, RuntimeDebug)] -pub struct AttestedCandidate { - /// The candidate data. This is abridged, because the omitted data - /// is already present within the relay chain state. - pub candidate: AbridgedCandidateReceipt, - /// Validity attestations. - pub validity_votes: Vec, - /// Indices of the corresponding validity votes. - pub validator_indices: BitVec, -} - -impl AttestedCandidate { - /// Get the candidate. - pub fn candidate(&self) -> &AbridgedCandidateReceipt { - &self.candidate - } - - /// Get the group ID of the candidate. - pub fn parachain_index(&self) -> Id { - self.candidate.parachain_index - } -} - -/// A fee schedule for messages. This is a linear function in the number of bytes of a message. -#[derive( - PartialEq, Eq, PartialOrd, Hash, Default, Clone, Copy, Encode, Decode, TypeInfo, RuntimeDebug, -)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -pub struct FeeSchedule { - /// The base fee charged for all messages. - pub base: Balance, - /// The per-byte fee for messages charged on top of that. - pub per_byte: Balance, -} - -impl FeeSchedule { - /// Compute the fee for a message of given size. - pub fn compute_message_fee(&self, n_bytes: usize) -> Balance { - use sp_std::mem; - debug_assert!(mem::size_of::() >= mem::size_of::()); - - let n_bytes = n_bytes as Balance; - self.base.saturating_add(n_bytes.saturating_mul(self.per_byte)) - } -} - -sp_api::decl_runtime_apis! { - /// The API for querying the state of parachains on-chain. - #[api_version(3)] - pub trait ParachainHost { - /// Get the current validators. - fn validators() -> Vec; - /// Get the current duty roster. - fn duty_roster() -> DutyRoster; - /// Get the currently active parachains. - fn active_parachains() -> Vec<(Id, Option<(CollatorId, Retriable)>)>; - /// Get the global validation schedule that all parachains should - /// be validated under. - fn global_validation_data() -> GlobalValidationData; - /// Get the local validation data for a particular parachain. - fn local_validation_data(id: Id) -> Option; - /// Get the given parachain's head code blob. - fn parachain_code(id: Id) -> Option; - /// Extract the abridged head that was set in the extrinsics. - fn get_heads(extrinsics: Vec<::Extrinsic>) - -> Option>; - /// Get a `SigningContext` with current `SessionIndex` and parent hash. - fn signing_context() -> SigningContext; - /// Get the `DownwardMessage`'s for the given parachain. - fn downward_messages(id: Id) -> Vec; - } -} - -/// Runtime ID module. -pub mod id { - use sp_version::ApiId; - - /// Parachain host runtime API id. - pub const PARACHAIN_HOST: ApiId = *b"parahost"; -} - -/// Custom validity errors used in Polkadot while validating transactions. -#[repr(u8)] -pub enum ValidityError { - /// The Ethereum signature is invalid. - InvalidEthereumSignature = 0, - /// The signer has no claim. - SignerHasNoClaim = 1, - /// No permission to execute the call. - NoPermission = 2, - /// An invalid statement was made for a claim. - InvalidStatement = 3, -} - -impl From for u8 { - fn from(err: ValidityError) -> Self { - err as u8 - } -} - -/// App-specific crypto used for reporting equivocation/misbehavior in BABE, -/// GRANDPA and Parachains, described in the white paper as the fisherman role. -/// Any rewards for misbehavior reporting will be paid out to this account. -pub mod fisherman { - use super::{Signature, Verify}; - use primitives::crypto::KeyTypeId; - - /// Key type for the reporting module. Used for reporting BABE, GRANDPA - /// and Parachain equivocations. - pub const KEY_TYPE: KeyTypeId = KeyTypeId(*b"fish"); - - mod app { - use application_crypto::{app_crypto, sr25519}; - app_crypto!(sr25519, super::KEY_TYPE); - } - - /// Identity of the equivocation/misbehavior reporter. - pub type FishermanId = app::Public; - - /// An `AppCrypto` type to allow submitting signed transactions using the fisherman - /// application key as signer. - pub struct FishermanAppCrypto; - impl frame_system::offchain::AppCrypto<::Signer, Signature> - for FishermanAppCrypto - { - type RuntimeAppPublic = FishermanId; - type GenericSignature = primitives::sr25519::Signature; - type GenericPublic = primitives::sr25519::Public; - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn balance_bigger_than_usize() { - let zero_b: Balance = 0; - let zero_u: usize = 0; - - assert!(zero_b.leading_zeros() >= zero_u.leading_zeros()); - } - - #[test] - fn collator_signature_payload_is_valid() { - // if this fails, collator signature verification code has to be updated. - let h = Hash::default(); - assert_eq!(h.as_ref().len(), 32); - - let _payload = - collator_signature_payload(&Hash::repeat_byte(1), &5u32.into(), &Hash::repeat_byte(2)); - } -} diff --git a/primitives/src/v1/mod.rs b/primitives/src/v1/mod.rs deleted file mode 100644 index e6281c20decf..000000000000 --- a/primitives/src/v1/mod.rs +++ /dev/null @@ -1,1438 +0,0 @@ -// Copyright 2017-2020 Parity Technologies (UK) Ltd. -// This file is part of Polkadot. - -// Polkadot is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Polkadot is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Polkadot. If not, see . - -//! `V1` Primitives. - -use bitvec::vec::BitVec; -use parity_scale_codec::{Decode, Encode}; -use scale_info::TypeInfo; -use sp_std::prelude::*; - -use application_crypto::KeyTypeId; -use inherents::InherentIdentifier; -use primitives::RuntimeDebug; -use runtime_primitives::traits::{AppVerify, Header as HeaderT}; -use sp_arithmetic::traits::{BaseArithmetic, Saturating}; - -pub use runtime_primitives::traits::{BlakeTwo256, Hash as HashT}; - -// Export some core primitives. -pub use polkadot_core_primitives::v1::{ - AccountId, AccountIndex, AccountPublic, Balance, Block, BlockId, BlockNumber, CandidateHash, - ChainId, DownwardMessage, Hash, Header, InboundDownwardMessage, InboundHrmpMessage, Moment, - Nonce, OutboundHrmpMessage, Remark, Signature, UncheckedExtrinsic, -}; - -// Export some polkadot-parachain primitives -pub use polkadot_parachain::primitives::{ - HeadData, HrmpChannelId, Id, UpwardMessage, ValidationCode, ValidationCodeHash, - LOWEST_PUBLIC_ID, LOWEST_USER_ID, -}; - -// Export some basic parachain primitives from v0. -pub use crate::v0::{ - CollatorId, CollatorSignature, CompactStatement, SigningContext, ValidatorId, ValidatorIndex, - ValidatorSignature, ValidityAttestation, PARACHAIN_KEY_TYPE_ID, -}; - -#[cfg(feature = "std")] -use parity_util_mem::{MallocSizeOf, MallocSizeOfOps}; - -// More exports from v0 for std. -#[cfg(feature = "std")] -pub use crate::v0::{CollatorPair, ValidatorPair}; - -pub use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; -pub use sp_consensus_slots::Slot; -pub use sp_staking::SessionIndex; - -/// Signed data. -mod signed; -pub use signed::{EncodeAs, Signed, UncheckedSigned}; - -mod metrics; -pub use metrics::{ - metric_definitions, RuntimeMetricLabel, RuntimeMetricLabelValue, RuntimeMetricLabelValues, - RuntimeMetricLabels, RuntimeMetricOp, RuntimeMetricUpdate, -}; - -/// A declarations of storage keys where an external observer can find some interesting data. -pub mod well_known_keys { - use super::{HrmpChannelId, Id}; - use hex_literal::hex; - use parity_scale_codec::Encode as _; - use sp_io::hashing::twox_64; - use sp_std::prelude::*; - - // A note on generating these magic values below: - // - // The `StorageValue`, such as `ACTIVE_CONFIG` was obtained by calling: - // - // ::ActiveConfig::hashed_key() - // - // The `StorageMap` values require `prefix`, and for example for `hrmp_egress_channel_index`, - // it could be obtained like: - // - // ::HrmpEgressChannelsIndex::prefix_hash(); - // - - /// The current slot number. - /// - /// The storage entry should be accessed as a `Slot` encoded value. - pub const CURRENT_SLOT: &[u8] = - &hex!["1cb6f36e027abb2091cfb5110ab5087f06155b3cd9a8c9e5e9a23fd5dc13a5ed"]; - - /// The currently active host configuration. - /// - /// The storage entry should be accessed as an `AbridgedHostConfiguration` encoded value. - pub const ACTIVE_CONFIG: &[u8] = - &hex!["06de3d8a54d27e44a9d5ce189618f22db4b49d95320d9021994c850f25b8e385"]; - - /// The upward message dispatch queue for the given para id. - /// - /// The storage entry stores a tuple of two values: - /// - /// - `count: u32`, the number of messages currently in the queue for given para, - /// - `total_size: u32`, the total size of all messages in the queue. - pub fn relay_dispatch_queue_size(para_id: Id) -> Vec { - let prefix = hex!["f5207f03cfdce586301014700e2c2593fad157e461d71fd4c1f936839a5f1f3e"]; - - para_id.using_encoded(|para_id: &[u8]| { - prefix - .as_ref() - .iter() - .chain(twox_64(para_id).iter()) - .chain(para_id.iter()) - .cloned() - .collect() - }) - } - - /// The HRMP channel for the given identifier. - /// - /// The storage entry should be accessed as an `AbridgedHrmpChannel` encoded value. - pub fn hrmp_channels(channel: HrmpChannelId) -> Vec { - let prefix = hex!["6a0da05ca59913bc38a8630590f2627cb6604cff828a6e3f579ca6c59ace013d"]; - - channel.using_encoded(|channel: &[u8]| { - prefix - .as_ref() - .iter() - .chain(twox_64(channel).iter()) - .chain(channel.iter()) - .cloned() - .collect() - }) - } - - /// The list of inbound channels for the given para. - /// - /// The storage entry stores a `Vec` - pub fn hrmp_ingress_channel_index(para_id: Id) -> Vec { - let prefix = hex!["6a0da05ca59913bc38a8630590f2627c1d3719f5b0b12c7105c073c507445948"]; - - para_id.using_encoded(|para_id: &[u8]| { - prefix - .as_ref() - .iter() - .chain(twox_64(para_id).iter()) - .chain(para_id.iter()) - .cloned() - .collect() - }) - } - - /// The list of outbound channels for the given para. - /// - /// The storage entry stores a `Vec` - pub fn hrmp_egress_channel_index(para_id: Id) -> Vec { - let prefix = hex!["6a0da05ca59913bc38a8630590f2627cf12b746dcf32e843354583c9702cc020"]; - - para_id.using_encoded(|para_id: &[u8]| { - prefix - .as_ref() - .iter() - .chain(twox_64(para_id).iter()) - .chain(para_id.iter()) - .cloned() - .collect() - }) - } - - /// The MQC head for the downward message queue of the given para. See more in the `Dmp` module. - /// - /// The storage entry stores a `Hash`. This is polkadot hash which is at the moment - /// `blake2b-256`. - pub fn dmq_mqc_head(para_id: Id) -> Vec { - let prefix = hex!["63f78c98723ddc9073523ef3beefda0c4d7fefc408aac59dbfe80a72ac8e3ce5"]; - - para_id.using_encoded(|para_id: &[u8]| { - prefix - .as_ref() - .iter() - .chain(twox_64(para_id).iter()) - .chain(para_id.iter()) - .cloned() - .collect() - }) - } - - /// The signal that indicates whether the parachain should go-ahead with the proposed validation - /// code upgrade. - /// - /// The storage entry stores a value of `UpgradeGoAhead` type. - pub fn upgrade_go_ahead_signal(para_id: Id) -> Vec { - let prefix = hex!["cd710b30bd2eab0352ddcc26417aa1949e94c040f5e73d9b7addd6cb603d15d3"]; - - para_id.using_encoded(|para_id: &[u8]| { - prefix - .as_ref() - .iter() - .chain(twox_64(para_id).iter()) - .chain(para_id.iter()) - .cloned() - .collect() - }) - } - - /// The signal that indicates whether the parachain is disallowed to signal an upgrade at this - /// relay-parent. - /// - /// The storage entry stores a value of `UpgradeRestriction` type. - pub fn upgrade_restriction_signal(para_id: Id) -> Vec { - let prefix = hex!["cd710b30bd2eab0352ddcc26417aa194f27bbb460270642b5bcaf032ea04d56a"]; - - para_id.using_encoded(|para_id: &[u8]| { - prefix - .as_ref() - .iter() - .chain(twox_64(para_id).iter()) - .chain(para_id.iter()) - .cloned() - .collect() - }) - } -} - -/// Unique identifier for the Parachains Inherent -pub const PARACHAINS_INHERENT_IDENTIFIER: InherentIdentifier = *b"parachn0"; - -/// The key type ID for parachain assignment key. -pub const ASSIGNMENT_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"asgn"); - -/// Maximum compressed code size we support right now. -/// At the moment we have runtime upgrade on chain, which restricts scalability severely. If we want -/// to have bigger values, we should fix that first. -/// -/// Used for: -/// * initial genesis for the Parachains configuration -/// * checking updates to this stored runtime configuration do not exceed this limit -/// * when detecting a code decompression bomb in the client -// NOTE: This value is used in the runtime so be careful when changing it. -pub const MAX_CODE_SIZE: u32 = 3 * 1024 * 1024; - -/// Maximum head data size we support right now. -/// -/// Used for: -/// * initial genesis for the Parachains configuration -/// * checking updates to this stored runtime configuration do not exceed this limit -// NOTE: This value is used in the runtime so be careful when changing it. -pub const MAX_HEAD_DATA_SIZE: u32 = 1 * 1024 * 1024; - -/// Maximum PoV size we support right now. -/// -/// Used for: -/// * initial genesis for the Parachains configuration -/// * checking updates to this stored runtime configuration do not exceed this limit -/// * when detecting a PoV decompression bomb in the client -// NOTE: This value is used in the runtime so be careful when changing it. -pub const MAX_POV_SIZE: u32 = 5 * 1024 * 1024; - -// The public key of a keypair used by a validator for determining assignments -/// to approve included parachain candidates. -mod assignment_app { - use application_crypto::{app_crypto, sr25519}; - app_crypto!(sr25519, super::ASSIGNMENT_KEY_TYPE_ID); -} - -/// The public key of a keypair used by a validator for determining assignments -/// to approve included parachain candidates. -pub type AssignmentId = assignment_app::Public; - -application_crypto::with_pair! { - /// The full keypair used by a validator for determining assignments to approve included - /// parachain candidates. - pub type AssignmentPair = assignment_app::Pair; -} - -#[cfg(feature = "std")] -impl MallocSizeOf for AssignmentId { - fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { - 0 - } - fn constant_size() -> Option { - Some(0) - } -} - -/// The index of the candidate in the list of candidates fully included as-of the block. -pub type CandidateIndex = u32; - -/// Get a collator signature payload on a relay-parent, block-data combo. -pub fn collator_signature_payload>( - relay_parent: &H, - para_id: &Id, - persisted_validation_data_hash: &Hash, - pov_hash: &Hash, - validation_code_hash: &ValidationCodeHash, -) -> [u8; 132] { - // 32-byte hash length is protected in a test below. - let mut payload = [0u8; 132]; - - payload[0..32].copy_from_slice(relay_parent.as_ref()); - u32::from(*para_id).using_encoded(|s| payload[32..32 + s.len()].copy_from_slice(s)); - payload[36..68].copy_from_slice(persisted_validation_data_hash.as_ref()); - payload[68..100].copy_from_slice(pov_hash.as_ref()); - payload[100..132].copy_from_slice(validation_code_hash.as_ref()); - - payload -} - -fn check_collator_signature>( - relay_parent: &H, - para_id: &Id, - persisted_validation_data_hash: &Hash, - pov_hash: &Hash, - validation_code_hash: &ValidationCodeHash, - collator: &CollatorId, - signature: &CollatorSignature, -) -> Result<(), ()> { - let payload = collator_signature_payload( - relay_parent, - para_id, - persisted_validation_data_hash, - pov_hash, - validation_code_hash, - ); - - if signature.verify(&payload[..], collator) { - Ok(()) - } else { - Err(()) - } -} - -/// A unique descriptor of the candidate receipt. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Hash, MallocSizeOf))] -pub struct CandidateDescriptor { - /// The ID of the para this is a candidate for. - pub para_id: Id, - /// The hash of the relay-chain block this is executed in the context of. - pub relay_parent: H, - /// The collator's sr25519 public key. - pub collator: CollatorId, - /// The blake2-256 hash of the persisted validation data. This is extra data derived from - /// relay-chain state which may vary based on bitfields included before the candidate. - /// Thus it cannot be derived entirely from the relay-parent. - pub persisted_validation_data_hash: Hash, - /// The blake2-256 hash of the PoV. - pub pov_hash: Hash, - /// The root of a block's erasure encoding Merkle tree. - pub erasure_root: Hash, - /// Signature on blake2-256 of components of this receipt: - /// The parachain index, the relay parent, the validation data hash, and the `pov_hash`. - pub signature: CollatorSignature, - /// Hash of the para header that is being generated by this candidate. - pub para_head: Hash, - /// The blake2-256 hash of the validation code bytes. - pub validation_code_hash: ValidationCodeHash, -} - -impl> CandidateDescriptor { - /// Check the signature of the collator within this descriptor. - pub fn check_collator_signature(&self) -> Result<(), ()> { - check_collator_signature( - &self.relay_parent, - &self.para_id, - &self.persisted_validation_data_hash, - &self.pov_hash, - &self.validation_code_hash, - &self.collator, - &self.signature, - ) - } -} - -/// A candidate-receipt. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(MallocSizeOf))] -pub struct CandidateReceipt { - /// The descriptor of the candidate. - pub descriptor: CandidateDescriptor, - /// The hash of the encoded commitments made as a result of candidate execution. - pub commitments_hash: Hash, -} - -impl CandidateReceipt { - /// Get a reference to the candidate descriptor. - pub fn descriptor(&self) -> &CandidateDescriptor { - &self.descriptor - } - - /// Computes the blake2-256 hash of the receipt. - pub fn hash(&self) -> CandidateHash - where - H: Encode, - { - CandidateHash(BlakeTwo256::hash_of(self)) - } -} - -/// All data pertaining to the execution of a para candidate. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -pub struct FullCandidateReceipt { - /// The inner candidate receipt. - pub inner: CandidateReceipt, - /// The validation data derived from the relay-chain state at that - /// point. The hash of the persisted validation data should - /// match the `persisted_validation_data_hash` in the descriptor - /// of the receipt. - pub validation_data: PersistedValidationData, -} - -/// A candidate-receipt with commitments directly included. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Hash, MallocSizeOf))] -pub struct CommittedCandidateReceipt { - /// The descriptor of the candidate. - pub descriptor: CandidateDescriptor, - /// The commitments of the candidate receipt. - pub commitments: CandidateCommitments, -} - -impl CommittedCandidateReceipt { - /// Get a reference to the candidate descriptor. - pub fn descriptor(&self) -> &CandidateDescriptor { - &self.descriptor - } -} - -impl CommittedCandidateReceipt { - /// Transforms this into a plain `CandidateReceipt`. - pub fn to_plain(&self) -> CandidateReceipt { - CandidateReceipt { - descriptor: self.descriptor.clone(), - commitments_hash: self.commitments.hash(), - } - } - - /// Computes the hash of the committed candidate receipt. - /// - /// This computes the canonical hash, not the hash of the directly encoded data. - /// Thus this is a shortcut for `candidate.to_plain().hash()`. - pub fn hash(&self) -> CandidateHash - where - H: Encode, - { - self.to_plain().hash() - } - - /// Does this committed candidate receipt corresponds to the given [`CandidateReceipt`]? - pub fn corresponds_to(&self, receipt: &CandidateReceipt) -> bool - where - H: PartialEq, - { - receipt.descriptor == self.descriptor && receipt.commitments_hash == self.commitments.hash() - } -} - -impl PartialOrd for CommittedCandidateReceipt { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl Ord for CommittedCandidateReceipt { - fn cmp(&self, other: &Self) -> sp_std::cmp::Ordering { - // TODO: compare signatures or something more sane - // https://github.com/paritytech/polkadot/issues/222 - self.descriptor() - .para_id - .cmp(&other.descriptor().para_id) - .then_with(|| self.commitments.head_data.cmp(&other.commitments.head_data)) - } -} - -/// The validation data provides information about how to create the inputs for validation of a candidate. -/// This information is derived from the chain state and will vary from para to para, although some -/// fields may be the same for every para. -/// -/// Since this data is used to form inputs to the validation function, it needs to be persisted by the -/// availability system to avoid dependence on availability of the relay-chain state. -/// -/// Furthermore, the validation data acts as a way to authorize the additional data the collator needs -/// to pass to the validation function. For example, the validation function can check whether the incoming -/// messages (e.g. downward messages) were actually sent by using the data provided in the validation data -/// using so called MQC heads. -/// -/// Since the commitments of the validation function are checked by the relay-chain, secondary checkers -/// can rely on the invariant that the relay-chain only includes para-blocks for which these checks have -/// already been done. As such, there is no need for the validation data used to inform validators and -/// collators about the checks the relay-chain will perform to be persisted by the availability system. -/// -/// The `PersistedValidationData` should be relatively lightweight primarily because it is constructed -/// during inclusion for each candidate and therefore lies on the critical path of inclusion. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Default, MallocSizeOf))] -pub struct PersistedValidationData { - /// The parent head-data. - pub parent_head: HeadData, - /// The relay-chain block number this is in the context of. - pub relay_parent_number: N, - /// The relay-chain block storage root this is in the context of. - pub relay_parent_storage_root: H, - /// The maximum legal size of a POV block, in bytes. - pub max_pov_size: u32, -} - -impl PersistedValidationData { - /// Compute the blake2-256 hash of the persisted validation data. - pub fn hash(&self) -> Hash { - BlakeTwo256::hash_of(self) - } -} - -/// Commitments made in a `CandidateReceipt`. Many of these are outputs of validation. -#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Hash, MallocSizeOf, Default))] -pub struct CandidateCommitments { - /// Messages destined to be interpreted by the Relay chain itself. - pub upward_messages: Vec, - /// Horizontal messages sent by the parachain. - pub horizontal_messages: Vec>, - /// New validation code. - pub new_validation_code: Option, - /// The head-data produced as a result of execution. - pub head_data: HeadData, - /// The number of messages processed from the DMQ. - pub processed_downward_messages: u32, - /// The mark which specifies the block number up to which all inbound HRMP messages are processed. - pub hrmp_watermark: N, -} - -impl CandidateCommitments { - /// Compute the blake2-256 hash of the commitments. - pub fn hash(&self) -> Hash { - BlakeTwo256::hash_of(self) - } -} - -/// A bitfield concerning availability of backed candidates. -/// -/// Every bit refers to an availability core index. -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct AvailabilityBitfield(pub BitVec); - -impl From> for AvailabilityBitfield { - fn from(inner: BitVec) -> Self { - AvailabilityBitfield(inner) - } -} - -/// A signed compact statement, suitable to be sent to the chain. -pub type SignedStatement = Signed; - -/// A bitfield signed by a particular validator about the availability of pending candidates. -pub type SignedAvailabilityBitfield = Signed; -/// A signed bitfield with signature not yet checked. -pub type UncheckedSignedAvailabilityBitfield = UncheckedSigned; - -/// A set of signed availability bitfields. Should be sorted by validator index, ascending. -pub type SignedAvailabilityBitfields = Vec; -/// A set of unchecked signed availability bitfields. Should be sorted by validator index, ascending. -pub type UncheckedSignedAvailabilityBitfields = Vec; - -/// A backed (or backable, depending on context) candidate. -#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] -pub struct BackedCandidate { - /// The candidate referred to. - pub candidate: CommittedCandidateReceipt, - /// The validity votes themselves, expressed as signatures. - pub validity_votes: Vec, - /// The indices of the validators within the group, expressed as a bitfield. - pub validator_indices: BitVec, -} - -impl BackedCandidate { - /// Get a reference to the descriptor of the para. - pub fn descriptor(&self) -> &CandidateDescriptor { - &self.candidate.descriptor - } - - /// Compute this candidate's hash. - pub fn hash(&self) -> CandidateHash - where - H: Clone + Encode, - { - self.candidate.hash() - } - - /// Get this candidate's receipt. - pub fn receipt(&self) -> CandidateReceipt - where - H: Clone, - { - self.candidate.to_plain() - } -} - -/// Verify the backing of the given candidate. -/// -/// Provide a lookup from the index of a validator within the group assigned to this para, -/// as opposed to the index of the validator within the overall validator set, as well as -/// the number of validators in the group. -/// -/// Also provide the signing context. -/// -/// Returns either an error, indicating that one of the signatures was invalid or that the index -/// was out-of-bounds, or the number of signatures checked. -pub fn check_candidate_backing + Clone + Encode>( - backed: &BackedCandidate, - signing_context: &SigningContext, - group_len: usize, - validator_lookup: impl Fn(usize) -> Option, -) -> Result { - if backed.validator_indices.len() != group_len { - return Err(()) - } - - if backed.validity_votes.len() > group_len { - return Err(()) - } - - // this is known, even in runtime, to be blake2-256. - let hash = backed.candidate.hash(); - - let mut signed = 0; - for ((val_in_group_idx, _), attestation) in backed - .validator_indices - .iter() - .enumerate() - .filter(|(_, signed)| **signed) - .zip(backed.validity_votes.iter()) - { - let validator_id = validator_lookup(val_in_group_idx).ok_or(())?; - let payload = attestation.signed_payload(hash.clone(), signing_context); - let sig = attestation.signature(); - - if sig.verify(&payload[..], &validator_id) { - signed += 1; - } else { - return Err(()) - } - } - - if signed != backed.validity_votes.len() { - return Err(()) - } - - Ok(signed) -} - -/// The unique (during session) index of a core. -#[derive( - Encode, Decode, Default, PartialOrd, Ord, Eq, PartialEq, Clone, Copy, TypeInfo, RuntimeDebug, -)] -#[cfg_attr(feature = "std", derive(Hash, MallocSizeOf))] -pub struct CoreIndex(pub u32); - -impl From for CoreIndex { - fn from(i: u32) -> CoreIndex { - CoreIndex(i) - } -} - -/// The unique (during session) index of a validator group. -#[derive(Encode, Decode, Default, Clone, Copy, Debug, PartialEq, Eq, TypeInfo)] -#[cfg_attr(feature = "std", derive(Hash, MallocSizeOf))] -pub struct GroupIndex(pub u32); - -impl From for GroupIndex { - fn from(i: u32) -> GroupIndex { - GroupIndex(i) - } -} - -/// A claim on authoring the next block for a given parathread. -#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(PartialEq))] -pub struct ParathreadClaim(pub Id, pub CollatorId); - -/// An entry tracking a claim to ensure it does not pass the maximum number of retries. -#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(PartialEq))] -pub struct ParathreadEntry { - /// The claim. - pub claim: ParathreadClaim, - /// Number of retries. - pub retries: u32, -} - -/// What is occupying a specific availability core. -#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(PartialEq))] -pub enum CoreOccupied { - /// A parathread. - Parathread(ParathreadEntry), - /// A parachain. - Parachain, -} - -/// A helper data-type for tracking validator-group rotations. -#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] -pub struct GroupRotationInfo { - /// The block number where the session started. - pub session_start_block: N, - /// How often groups rotate. 0 means never. - pub group_rotation_frequency: N, - /// The current block number. - pub now: N, -} - -impl GroupRotationInfo { - /// Returns the index of the group needed to validate the core at the given index, assuming - /// the given number of cores. - /// - /// `core_index` should be less than `cores`, which is capped at `u32::max()`. - pub fn group_for_core(&self, core_index: CoreIndex, cores: usize) -> GroupIndex { - if self.group_rotation_frequency == 0 { - return GroupIndex(core_index.0) - } - if cores == 0 { - return GroupIndex(0) - } - - let cores = sp_std::cmp::min(cores, u32::MAX as usize); - let blocks_since_start = self.now.saturating_sub(self.session_start_block); - let rotations = blocks_since_start / self.group_rotation_frequency; - - // g = c + r mod cores - - let idx = (core_index.0 as usize + rotations as usize) % cores; - GroupIndex(idx as u32) - } - - /// Returns the index of the group assigned to the given core. This does no checking or - /// whether the group index is in-bounds. - /// - /// `core_index` should be less than `cores`, which is capped at `u32::max()`. - pub fn core_for_group(&self, group_index: GroupIndex, cores: usize) -> CoreIndex { - if self.group_rotation_frequency == 0 { - return CoreIndex(group_index.0) - } - if cores == 0 { - return CoreIndex(0) - } - - let cores = sp_std::cmp::min(cores, u32::MAX as usize); - let blocks_since_start = self.now.saturating_sub(self.session_start_block); - let rotations = blocks_since_start / self.group_rotation_frequency; - let rotations = rotations % cores as u32; - - // g = c + r mod cores - // c = g - r mod cores - // x = x + cores mod cores - // c = (g + cores) - r mod cores - - let idx = (group_index.0 as usize + cores - rotations as usize) % cores; - CoreIndex(idx as u32) - } - - /// Create a new `GroupRotationInfo` with one further rotation applied. - pub fn bump_rotation(&self) -> Self { - GroupRotationInfo { - session_start_block: self.session_start_block, - group_rotation_frequency: self.group_rotation_frequency, - now: self.next_rotation_at(), - } - } -} - -impl GroupRotationInfo { - /// Returns the block number of the next rotation after the current block. If the current block - /// is 10 and the rotation frequency is 5, this should return 15. - pub fn next_rotation_at(&self) -> N { - let cycle_once = self.now + self.group_rotation_frequency; - cycle_once - - (cycle_once.saturating_sub(self.session_start_block) % self.group_rotation_frequency) - } - - /// Returns the block number of the last rotation before or including the current block. If the - /// current block is 10 and the rotation frequency is 5, this should return 10. - pub fn last_rotation_at(&self) -> N { - self.now - - (self.now.saturating_sub(self.session_start_block) % self.group_rotation_frequency) - } -} - -/// Information about a core which is currently occupied. -#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] -pub struct OccupiedCore { - // NOTE: this has no ParaId as it can be deduced from the candidate descriptor. - /// If this core is freed by availability, this is the assignment that is next up on this - /// core, if any. None if there is nothing queued for this core. - pub next_up_on_available: Option, - /// The relay-chain block number this began occupying the core at. - pub occupied_since: N, - /// The relay-chain block this will time-out at, if any. - pub time_out_at: N, - /// If this core is freed by being timed-out, this is the assignment that is next up on this - /// core. None if there is nothing queued for this core or there is no possibility of timing - /// out. - pub next_up_on_time_out: Option, - /// A bitfield with 1 bit for each validator in the set. `1` bits mean that the corresponding - /// validators has attested to availability on-chain. A 2/3+ majority of `1` bits means that - /// this will be available. - #[cfg_attr(feature = "std", ignore_malloc_size_of = "outside type")] - pub availability: BitVec, - /// The group assigned to distribute availability pieces of this candidate. - pub group_responsible: GroupIndex, - /// The hash of the candidate occupying the core. - pub candidate_hash: CandidateHash, - /// The descriptor of the candidate occupying the core. - pub candidate_descriptor: CandidateDescriptor, -} - -impl OccupiedCore { - /// Get the Para currently occupying this core. - pub fn para_id(&self) -> Id { - self.candidate_descriptor.para_id - } -} - -/// Information about a core which is currently occupied. -#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] -pub struct ScheduledCore { - /// The ID of a para scheduled. - pub para_id: Id, - /// The collator required to author the block, if any. - pub collator: Option, -} - -/// The state of a particular availability core. -#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] -pub enum CoreState { - /// The core is currently occupied. - #[codec(index = 0)] - Occupied(OccupiedCore), - /// The core is currently free, with a para scheduled and given the opportunity - /// to occupy. - /// - /// If a particular Collator is required to author this block, that is also present in this - /// variant. - #[codec(index = 1)] - Scheduled(ScheduledCore), - /// The core is currently free and there is nothing scheduled. This can be the case for parathread - /// cores when there are no parathread blocks queued. Parachain cores will never be left idle. - #[codec(index = 2)] - Free, -} - -impl CoreState { - /// If this core state has a `para_id`, return it. - pub fn para_id(&self) -> Option { - match self { - Self::Occupied(ref core) => Some(core.para_id()), - Self::Scheduled(ScheduledCore { para_id, .. }) => Some(*para_id), - Self::Free => None, - } - } - - /// Is this core state `Self::Occupied`? - pub fn is_occupied(&self) -> bool { - matches!(self, Self::Occupied(_)) - } -} - -/// An assumption being made about the state of an occupied core. -#[derive(Clone, Copy, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(PartialEq, Eq, Hash))] -pub enum OccupiedCoreAssumption { - /// The candidate occupying the core was made available and included to free the core. - #[codec(index = 0)] - Included, - /// The candidate occupying the core timed out and freed the core without advancing the para. - #[codec(index = 1)] - TimedOut, - /// The core was not occupied to begin with. - #[codec(index = 2)] - Free, -} - -/// An even concerning a candidate. -#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] -pub enum CandidateEvent { - /// This candidate receipt was backed in the most recent block. - /// This includes the core index the candidate is now occupying. - #[codec(index = 0)] - CandidateBacked(CandidateReceipt, HeadData, CoreIndex, GroupIndex), - /// This candidate receipt was included and became a parablock at the most recent block. - /// This includes the core index the candidate was occupying as well as the group responsible - /// for backing the candidate. - #[codec(index = 1)] - CandidateIncluded(CandidateReceipt, HeadData, CoreIndex, GroupIndex), - /// This candidate receipt was not made available in time and timed out. - /// This includes the core index the candidate was occupying. - #[codec(index = 2)] - CandidateTimedOut(CandidateReceipt, HeadData, CoreIndex), -} - -/// Information about validator sets of a session. -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] -pub struct SessionInfo { - /// Validators in canonical ordering. - /// - /// NOTE: There might be more authorities in the current session, than `validators` participating - /// in parachain consensus. See - /// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148). - /// - /// `SessionInfo::validators` will be limited to to `max_validators` when set. - pub validators: Vec, - /// Validators' authority discovery keys for the session in canonical ordering. - /// - /// NOTE: The first `validators.len()` entries will match the corresponding validators in - /// `validators`, afterwards any remaining authorities can be found. This is any authorities not - /// participating in parachain consensus - see - /// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148) - #[cfg_attr(feature = "std", ignore_malloc_size_of = "outside type")] - pub discovery_keys: Vec, - /// The assignment keys for validators. - /// - /// NOTE: There might be more authorities in the current session, than validators participating - /// in parachain consensus. See - /// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148). - /// - /// Therefore: - /// ```ignore - /// assignment_keys.len() == validators.len() && validators.len() <= discovery_keys.len() - /// ``` - pub assignment_keys: Vec, - /// Validators in shuffled ordering - these are the validator groups as produced - /// by the `Scheduler` module for the session and are typically referred to by - /// `GroupIndex`. - pub validator_groups: Vec>, - /// The number of availability cores used by the protocol during this session. - pub n_cores: u32, - /// The zeroth delay tranche width. - pub zeroth_delay_tranche_width: u32, - /// The number of samples we do of `relay_vrf_modulo`. - pub relay_vrf_modulo_samples: u32, - /// The number of delay tranches in total. - pub n_delay_tranches: u32, - /// How many slots (BABE / SASSAFRAS) must pass before an assignment is considered a - /// no-show. - pub no_show_slots: u32, - /// The number of validators needed to approve a block. - pub needed_approvals: u32, -} - -/// Scraped runtime backing votes and resolved disputes. -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] -pub struct ScrapedOnChainVotes { - /// The session in which the block was included. - pub session: SessionIndex, - /// Set of backing validators for each candidate, represented by its candidate - /// receipt. - pub backing_validators_per_candidate: - Vec<(CandidateReceipt, Vec<(ValidatorIndex, ValidityAttestation)>)>, - /// On-chain-recorded set of disputes. - /// Note that the above `backing_validators` are - /// unrelated to the backers of the disputes candidates. - pub disputes: MultiDisputeStatementSet, -} - -/// A vote of approval on a candidate. -#[derive(Clone, RuntimeDebug)] -pub struct ApprovalVote(pub CandidateHash); - -impl ApprovalVote { - /// Yields the signing payload for this approval vote. - pub fn signing_payload(&self, session_index: SessionIndex) -> Vec { - const MAGIC: [u8; 4] = *b"APPR"; - - (MAGIC, &self.0, session_index).encode() - } -} - -/// Custom validity errors used in Polkadot while validating transactions. -#[repr(u8)] -pub enum ValidityError { - /// The Ethereum signature is invalid. - InvalidEthereumSignature = 0, - /// The signer has no claim. - SignerHasNoClaim = 1, - /// No permission to execute the call. - NoPermission = 2, - /// An invalid statement was made for a claim. - InvalidStatement = 3, -} - -impl From for u8 { - fn from(err: ValidityError) -> Self { - err as u8 - } -} - -/// Abridged version of `HostConfiguration` (from the `Configuration` parachains host runtime module) -/// meant to be used by a parachain or PDK such as cumulus. -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -#[cfg_attr(feature = "std", derive(PartialEq))] -pub struct AbridgedHostConfiguration { - /// The maximum validation code size, in bytes. - pub max_code_size: u32, - /// The maximum head-data size, in bytes. - pub max_head_data_size: u32, - /// Total number of individual messages allowed in the parachain -> relay-chain message queue. - pub max_upward_queue_count: u32, - /// Total size of messages allowed in the parachain -> relay-chain message queue before which - /// no further messages may be added to it. If it exceeds this then the queue may contain only - /// a single message. - pub max_upward_queue_size: u32, - /// The maximum size of an upward message that can be sent by a candidate. - /// - /// This parameter affects the size upper bound of the `CandidateCommitments`. - pub max_upward_message_size: u32, - /// The maximum number of messages that a candidate can contain. - /// - /// This parameter affects the size upper bound of the `CandidateCommitments`. - pub max_upward_message_num_per_candidate: u32, - /// The maximum number of outbound HRMP messages can be sent by a candidate. - /// - /// This parameter affects the upper bound of size of `CandidateCommitments`. - pub hrmp_max_message_num_per_candidate: u32, - /// The minimum period, in blocks, between which parachains can update their validation code. - pub validation_upgrade_cooldown: BlockNumber, - /// The delay, in blocks, before a validation upgrade is applied. - pub validation_upgrade_delay: BlockNumber, -} - -/// Abridged version of `HrmpChannel` (from the `Hrmp` parachains host runtime module) meant to be -/// used by a parachain or PDK such as cumulus. -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -#[cfg_attr(feature = "std", derive(PartialEq))] -pub struct AbridgedHrmpChannel { - /// The maximum number of messages that can be pending in the channel at once. - pub max_capacity: u32, - /// The maximum total size of the messages that can be pending in the channel at once. - pub max_total_size: u32, - /// The maximum message size that could be put into the channel. - pub max_message_size: u32, - /// The current number of messages pending in the channel. - /// Invariant: should be less or equal to `max_capacity`.s`. - pub msg_count: u32, - /// The total size in bytes of all message payloads in the channel. - /// Invariant: should be less or equal to `max_total_size`. - pub total_size: u32, - /// A head of the Message Queue Chain for this channel. Each link in this chain has a form: - /// `(prev_head, B, H(M))`, where - /// - `prev_head`: is the previous value of `mqc_head` or zero if none. - /// - `B`: is the [relay-chain] block number in which a message was appended - /// - `H(M)`: is the hash of the message being appended. - /// This value is initialized to a special value that consists of all zeroes which indicates - /// that no messages were previously added. - pub mqc_head: Option, -} - -/// A possible upgrade restriction that prevents a parachain from performing an upgrade. -#[derive(Copy, Clone, Encode, Decode, PartialEq, RuntimeDebug, TypeInfo)] -pub enum UpgradeRestriction { - /// There is an upgrade restriction and there are no details about its specifics nor how long - /// it could last. - #[codec(index = 0)] - Present, -} - -/// A struct that the relay-chain communicates to a parachain indicating what course of action the -/// parachain should take in the coordinated parachain validation code upgrade process. -/// -/// This data type appears in the last step of the upgrade process. After the parachain observes it -/// and reacts to it the upgrade process concludes. -#[derive(Copy, Clone, Encode, Decode, PartialEq, RuntimeDebug, TypeInfo)] -pub enum UpgradeGoAhead { - /// Abort the upgrade process. There is something wrong with the validation code previously - /// submitted by the parachain. This variant can also be used to prevent upgrades by the governance - /// should an emergency emerge. - /// - /// The expected reaction on this variant is that the parachain will admit this message and - /// remove all the data about the pending upgrade. Depending on the nature of the problem (to - /// be examined offchain for now), it can try to send another validation code or just retry later. - #[codec(index = 0)] - Abort, - /// Apply the pending code change. The parablock that is built on a relay-parent that is descendant - /// of the relay-parent where the parachain observed this signal must use the upgraded validation - /// code. - #[codec(index = 1)] - GoAhead, -} - -/// Consensus engine id for polkadot v1 consensus engine. -pub const POLKADOT_ENGINE_ID: runtime_primitives::ConsensusEngineId = *b"POL1"; - -/// A consensus log item for polkadot validation. To be used with [`POLKADOT_ENGINE_ID`]. -#[derive(Decode, Encode, Clone, PartialEq, Eq)] -pub enum ConsensusLog { - /// A parachain or parathread upgraded its code. - #[codec(index = 1)] - ParaUpgradeCode(Id, ValidationCodeHash), - /// A parachain or parathread scheduled a code upgrade. - #[codec(index = 2)] - ParaScheduleUpgradeCode(Id, ValidationCodeHash, BlockNumber), - /// Governance requests to auto-approve every candidate included up to the given block - /// number in the current chain, inclusive. - #[codec(index = 3)] - ForceApprove(BlockNumber), - /// A signal to revert the block number in the same chain as the - /// header this digest is part of and all of its descendants. - /// - /// It is a no-op for a block to contain a revert digest targeting - /// its own number or a higher number. - /// - /// In practice, these are issued when on-chain logic has detected an - /// invalid parachain block within its own chain, due to a dispute. - #[codec(index = 4)] - Revert(BlockNumber), -} - -impl ConsensusLog { - /// Attempt to convert a reference to a generic digest item into a consensus log. - pub fn from_digest_item( - digest_item: &runtime_primitives::DigestItem, - ) -> Result, parity_scale_codec::Error> { - match digest_item { - runtime_primitives::DigestItem::Consensus(id, encoded) if id == &POLKADOT_ENGINE_ID => - Ok(Some(Self::decode(&mut &encoded[..])?)), - _ => Ok(None), - } - } -} - -impl From for runtime_primitives::DigestItem { - fn from(c: ConsensusLog) -> runtime_primitives::DigestItem { - Self::Consensus(POLKADOT_ENGINE_ID, c.encode()) - } -} - -/// A statement about a candidate, to be used within the dispute resolution process. -/// -/// Statements are either in favor of the candidate's validity or against it. -#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)] -#[cfg_attr(feature = "std", derive(MallocSizeOf))] -pub enum DisputeStatement { - /// A valid statement, of the given kind. - #[codec(index = 0)] - Valid(ValidDisputeStatementKind), - /// An invalid statement, of the given kind. - #[codec(index = 1)] - Invalid(InvalidDisputeStatementKind), -} - -impl DisputeStatement { - /// Get the payload data for this type of dispute statement. - pub fn payload_data(&self, candidate_hash: CandidateHash, session: SessionIndex) -> Vec { - match *self { - DisputeStatement::Valid(ValidDisputeStatementKind::Explicit) => - ExplicitDisputeStatement { valid: true, candidate_hash, session }.signing_payload(), - DisputeStatement::Valid(ValidDisputeStatementKind::BackingSeconded( - inclusion_parent, - )) => CompactStatement::Seconded(candidate_hash).signing_payload(&SigningContext { - session_index: session, - parent_hash: inclusion_parent, - }), - DisputeStatement::Valid(ValidDisputeStatementKind::BackingValid(inclusion_parent)) => - CompactStatement::Valid(candidate_hash).signing_payload(&SigningContext { - session_index: session, - parent_hash: inclusion_parent, - }), - DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking) => - ApprovalVote(candidate_hash).signing_payload(session), - DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit) => - ExplicitDisputeStatement { valid: false, candidate_hash, session }.signing_payload(), - } - } - - /// Check the signature on a dispute statement. - pub fn check_signature( - &self, - validator_public: &ValidatorId, - candidate_hash: CandidateHash, - session: SessionIndex, - validator_signature: &ValidatorSignature, - ) -> Result<(), ()> { - let payload = self.payload_data(candidate_hash, session); - - if validator_signature.verify(&payload[..], &validator_public) { - Ok(()) - } else { - Err(()) - } - } - - /// Whether the statement indicates validity. - pub fn indicates_validity(&self) -> bool { - match *self { - DisputeStatement::Valid(_) => true, - DisputeStatement::Invalid(_) => false, - } - } - - /// Whether the statement indicates invalidity. - pub fn indicates_invalidity(&self) -> bool { - match *self { - DisputeStatement::Valid(_) => false, - DisputeStatement::Invalid(_) => true, - } - } - - /// Statement is backing statement. - pub fn is_backing(&self) -> bool { - match *self { - Self::Valid(ValidDisputeStatementKind::BackingSeconded(_)) | - Self::Valid(ValidDisputeStatementKind::BackingValid(_)) => true, - Self::Valid(ValidDisputeStatementKind::Explicit) | - Self::Valid(ValidDisputeStatementKind::ApprovalChecking) | - Self::Invalid(_) => false, - } - } -} - -/// Different kinds of statements of validity on a candidate. -#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)] -#[cfg_attr(feature = "std", derive(MallocSizeOf))] -pub enum ValidDisputeStatementKind { - /// An explicit statement issued as part of a dispute. - #[codec(index = 0)] - Explicit, - /// A seconded statement on a candidate from the backing phase. - #[codec(index = 1)] - BackingSeconded(Hash), - /// A valid statement on a candidate from the backing phase. - #[codec(index = 2)] - BackingValid(Hash), - /// An approval vote from the approval checking phase. - #[codec(index = 3)] - ApprovalChecking, -} - -/// Different kinds of statements of invalidity on a candidate. -#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)] -#[cfg_attr(feature = "std", derive(MallocSizeOf))] -pub enum InvalidDisputeStatementKind { - /// An explicit statement issued as part of a dispute. - #[codec(index = 0)] - Explicit, -} - -/// An explicit statement on a candidate issued as part of a dispute. -#[derive(Clone, PartialEq, RuntimeDebug)] -pub struct ExplicitDisputeStatement { - /// Whether the candidate is valid - pub valid: bool, - /// The candidate hash. - pub candidate_hash: CandidateHash, - /// The session index of the candidate. - pub session: SessionIndex, -} - -impl ExplicitDisputeStatement { - /// Produce the payload used for signing this type of statement. - pub fn signing_payload(&self) -> Vec { - const MAGIC: [u8; 4] = *b"DISP"; - - (MAGIC, self.valid, self.candidate_hash, self.session).encode() - } -} - -/// A set of statements about a specific candidate. -#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)] -#[cfg_attr(feature = "std", derive(MallocSizeOf))] -pub struct DisputeStatementSet { - /// The candidate referenced by this set. - pub candidate_hash: CandidateHash, - /// The session index of the candidate. - pub session: SessionIndex, - /// Statements about the candidate. - pub statements: Vec<(DisputeStatement, ValidatorIndex, ValidatorSignature)>, -} - -impl From for DisputeStatementSet { - fn from(other: CheckedDisputeStatementSet) -> Self { - other.0 - } -} - -impl AsRef for DisputeStatementSet { - fn as_ref(&self) -> &DisputeStatementSet { - &self - } -} - -/// A set of dispute statements. -pub type MultiDisputeStatementSet = Vec; - -/// A _checked_ set of dispute statements. -#[derive(Clone, PartialEq, RuntimeDebug)] -pub struct CheckedDisputeStatementSet(DisputeStatementSet); - -impl AsRef for CheckedDisputeStatementSet { - fn as_ref(&self) -> &DisputeStatementSet { - &self.0 - } -} - -impl core::cmp::PartialEq for CheckedDisputeStatementSet { - fn eq(&self, other: &DisputeStatementSet) -> bool { - self.0.eq(other) - } -} - -impl CheckedDisputeStatementSet { - /// Convert from an unchecked, the verification of correctness of the `unchecked` statement set - /// _must_ be done before calling this function! - pub fn unchecked_from_unchecked(unchecked: DisputeStatementSet) -> Self { - Self(unchecked) - } -} - -/// A set of _checked_ dispute statements. -pub type CheckedMultiDisputeStatementSet = Vec; - -/// The entire state of a dispute. -#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, TypeInfo)] -pub struct DisputeState { - /// A bitfield indicating all validators for the candidate. - pub validators_for: BitVec, // one bit per validator. - /// A bitfield indicating all validators against the candidate. - pub validators_against: BitVec, // one bit per validator. - /// The block number at which the dispute started on-chain. - pub start: N, - /// The block number at which the dispute concluded on-chain. - pub concluded_at: Option, -} - -/// Parachains inherent-data passed into the runtime by a block author -#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)] -pub struct InherentData { - /// Signed bitfields by validators about availability. - pub bitfields: UncheckedSignedAvailabilityBitfields, - /// Backed candidates for inclusion in the block. - pub backed_candidates: Vec>, - /// Sets of dispute votes for inclusion, - pub disputes: MultiDisputeStatementSet, - /// The parent block header. Used for checking state proofs. - pub parent_header: HDR, -} - -/// The maximum number of validators `f` which may safely be faulty. -/// -/// The total number of validators is `n = 3f + e` where `e in { 1, 2, 3 }`. -pub fn byzantine_threshold(n: usize) -> usize { - n.saturating_sub(1) / 3 -} - -/// The supermajority threshold of validators which represents a subset -/// guaranteed to have at least f+1 honest validators. -pub fn supermajority_threshold(n: usize) -> usize { - n - byzantine_threshold(n) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn group_rotation_info_calculations() { - let info = - GroupRotationInfo { session_start_block: 10u32, now: 15, group_rotation_frequency: 5 }; - - assert_eq!(info.next_rotation_at(), 20); - assert_eq!(info.last_rotation_at(), 15); - } - - #[test] - fn group_for_core_is_core_for_group() { - for cores in 1..=256 { - for rotations in 0..(cores * 2) { - let info = GroupRotationInfo { - session_start_block: 0u32, - now: rotations, - group_rotation_frequency: 1, - }; - - for core in 0..cores { - let group = info.group_for_core(CoreIndex(core), cores as usize); - assert_eq!(info.core_for_group(group, cores as usize).0, core); - } - } - } - } - - #[test] - fn collator_signature_payload_is_valid() { - // if this fails, collator signature verification code has to be updated. - let h = Hash::default(); - assert_eq!(h.as_ref().len(), 32); - - let _payload = collator_signature_payload( - &Hash::repeat_byte(1), - &5u32.into(), - &Hash::repeat_byte(2), - &Hash::repeat_byte(3), - &Hash::repeat_byte(4).into(), - ); - } - - #[test] - fn test_byzantine_threshold() { - assert_eq!(byzantine_threshold(0), 0); - assert_eq!(byzantine_threshold(1), 0); - assert_eq!(byzantine_threshold(2), 0); - assert_eq!(byzantine_threshold(3), 0); - assert_eq!(byzantine_threshold(4), 1); - assert_eq!(byzantine_threshold(5), 1); - assert_eq!(byzantine_threshold(6), 1); - assert_eq!(byzantine_threshold(7), 2); - } - - #[test] - fn test_supermajority_threshold() { - assert_eq!(supermajority_threshold(0), 0); - assert_eq!(supermajority_threshold(1), 1); - assert_eq!(supermajority_threshold(2), 2); - assert_eq!(supermajority_threshold(3), 3); - assert_eq!(supermajority_threshold(4), 3); - assert_eq!(supermajority_threshold(5), 4); - assert_eq!(supermajority_threshold(6), 5); - assert_eq!(supermajority_threshold(7), 5); - } -} diff --git a/primitives/src/v1/metrics.rs b/primitives/src/v2/metrics.rs similarity index 100% rename from primitives/src/v1/metrics.rs rename to primitives/src/v2/metrics.rs diff --git a/primitives/src/v2/mod.rs b/primitives/src/v2/mod.rs index 065d5cc3c057..9495978ba5e4 100644 --- a/primitives/src/v2/mod.rs +++ b/primitives/src/v2/mod.rs @@ -1,4 +1,4 @@ -// Copyright 2021 Parity Technologies (UK) Ltd. +// Copyright 2017-2020 Parity Technologies (UK) Ltd. // This file is part of Polkadot. // Polkadot is free software: you can redistribute it and/or modify @@ -14,17 +14,1531 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -//! `V2` Primitives. - -use crate::v1; +//! `V1` Primitives. +use bitvec::vec::BitVec; use parity_scale_codec::{Decode, Encode}; -use primitives::RuntimeDebug; use scale_info::TypeInfo; use sp_std::{collections::btree_map::BTreeMap, prelude::*}; +use application_crypto::KeyTypeId; +use inherents::InherentIdentifier; +use primitives::RuntimeDebug; +use runtime_primitives::traits::{AppVerify, Header as HeaderT}; +use sp_arithmetic::traits::{BaseArithmetic, Saturating}; + +pub use runtime_primitives::traits::{BlakeTwo256, Hash as HashT}; + +// Export some core primitives. +pub use polkadot_core_primitives::v2::{ + AccountId, AccountIndex, AccountPublic, Balance, Block, BlockId, BlockNumber, CandidateHash, + ChainId, DownwardMessage, Hash, Header, InboundDownwardMessage, InboundHrmpMessage, Moment, + Nonce, OutboundHrmpMessage, Remark, Signature, UncheckedExtrinsic, +}; + +// Export some polkadot-parachain primitives +pub use polkadot_parachain::primitives::{ + HeadData, HrmpChannelId, Id, UpwardMessage, ValidationCode, ValidationCodeHash, + LOWEST_PUBLIC_ID, LOWEST_USER_ID, +}; + +#[cfg(feature = "std")] +use parity_util_mem::{MallocSizeOf, MallocSizeOfOps}; +#[cfg(feature = "std")] +use serde::{Deserialize, Serialize}; + +pub use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; +pub use sp_consensus_slots::Slot; +pub use sp_staking::SessionIndex; + +/// Signed data. +mod signed; +pub use signed::{EncodeAs, Signed, UncheckedSigned}; + +mod metrics; +pub use metrics::{ + metric_definitions, RuntimeMetricLabel, RuntimeMetricLabelValue, RuntimeMetricLabelValues, + RuntimeMetricLabels, RuntimeMetricOp, RuntimeMetricUpdate, +}; + +/// The key type ID for a collator key. +pub const COLLATOR_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"coll"); + +mod collator_app { + use application_crypto::{app_crypto, sr25519}; + app_crypto!(sr25519, super::COLLATOR_KEY_TYPE_ID); +} + +/// Identity that collators use. +pub type CollatorId = collator_app::Public; + +#[cfg(feature = "std")] +impl MallocSizeOf for CollatorId { + fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { + 0 + } + fn constant_size() -> Option { + Some(0) + } +} + +/// A Parachain collator keypair. +#[cfg(feature = "std")] +pub type CollatorPair = collator_app::Pair; + +/// Signature on candidate's block data by a collator. +pub type CollatorSignature = collator_app::Signature; + +#[cfg(feature = "std")] +impl MallocSizeOf for CollatorSignature { + fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { + 0 + } + fn constant_size() -> Option { + Some(0) + } +} + +/// The key type ID for a parachain validator key. +pub const PARACHAIN_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"para"); + +mod validator_app { + use application_crypto::{app_crypto, sr25519}; + app_crypto!(sr25519, super::PARACHAIN_KEY_TYPE_ID); +} + +/// Identity that parachain validators use when signing validation messages. +/// +/// For now we assert that parachain validator set is exactly equivalent to the authority set, and +/// so we define it to be the same type as `SessionKey`. In the future it may have different crypto. +pub type ValidatorId = validator_app::Public; + +#[cfg(feature = "std")] +impl MallocSizeOf for ValidatorId { + fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { + 0 + } + fn constant_size() -> Option { + Some(0) + } +} + +/// Index of the validator is used as a lightweight replacement of the `ValidatorId` when appropriate. +#[derive(Eq, Ord, PartialEq, PartialOrd, Copy, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash, MallocSizeOf))] +pub struct ValidatorIndex(pub u32); + +// We should really get https://github.com/paritytech/polkadot/issues/2403 going .. +impl From for ValidatorIndex { + fn from(n: u32) -> Self { + ValidatorIndex(n) + } +} + +application_crypto::with_pair! { + /// A Parachain validator keypair. + pub type ValidatorPair = validator_app::Pair; +} + +/// Signature with which parachain validators sign blocks. +/// +/// For now we assert that parachain validator set is exactly equivalent to the authority set, and +/// so we define it to be the same type as `SessionKey`. In the future it may have different crypto. +pub type ValidatorSignature = validator_app::Signature; + +#[cfg(feature = "std")] +impl MallocSizeOf for ValidatorSignature { + fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { + 0 + } + fn constant_size() -> Option { + Some(0) + } +} + +/// A declarations of storage keys where an external observer can find some interesting data. +pub mod well_known_keys { + use super::{HrmpChannelId, Id}; + use hex_literal::hex; + use parity_scale_codec::Encode as _; + use sp_io::hashing::twox_64; + use sp_std::prelude::*; + + // A note on generating these magic values below: + // + // The `StorageValue`, such as `ACTIVE_CONFIG` was obtained by calling: + // + // ::ActiveConfig::hashed_key() + // + // The `StorageMap` values require `prefix`, and for example for `hrmp_egress_channel_index`, + // it could be obtained like: + // + // ::HrmpEgressChannelsIndex::prefix_hash(); + // + + /// The current slot number. + /// + /// The storage entry should be accessed as a `Slot` encoded value. + pub const CURRENT_SLOT: &[u8] = + &hex!["1cb6f36e027abb2091cfb5110ab5087f06155b3cd9a8c9e5e9a23fd5dc13a5ed"]; + + /// The currently active host configuration. + /// + /// The storage entry should be accessed as an `AbridgedHostConfiguration` encoded value. + pub const ACTIVE_CONFIG: &[u8] = + &hex!["06de3d8a54d27e44a9d5ce189618f22db4b49d95320d9021994c850f25b8e385"]; + + /// The upward message dispatch queue for the given para id. + /// + /// The storage entry stores a tuple of two values: + /// + /// - `count: u32`, the number of messages currently in the queue for given para, + /// - `total_size: u32`, the total size of all messages in the queue. + pub fn relay_dispatch_queue_size(para_id: Id) -> Vec { + let prefix = hex!["f5207f03cfdce586301014700e2c2593fad157e461d71fd4c1f936839a5f1f3e"]; + + para_id.using_encoded(|para_id: &[u8]| { + prefix + .as_ref() + .iter() + .chain(twox_64(para_id).iter()) + .chain(para_id.iter()) + .cloned() + .collect() + }) + } + + /// The HRMP channel for the given identifier. + /// + /// The storage entry should be accessed as an `AbridgedHrmpChannel` encoded value. + pub fn hrmp_channels(channel: HrmpChannelId) -> Vec { + let prefix = hex!["6a0da05ca59913bc38a8630590f2627cb6604cff828a6e3f579ca6c59ace013d"]; + + channel.using_encoded(|channel: &[u8]| { + prefix + .as_ref() + .iter() + .chain(twox_64(channel).iter()) + .chain(channel.iter()) + .cloned() + .collect() + }) + } + + /// The list of inbound channels for the given para. + /// + /// The storage entry stores a `Vec` + pub fn hrmp_ingress_channel_index(para_id: Id) -> Vec { + let prefix = hex!["6a0da05ca59913bc38a8630590f2627c1d3719f5b0b12c7105c073c507445948"]; + + para_id.using_encoded(|para_id: &[u8]| { + prefix + .as_ref() + .iter() + .chain(twox_64(para_id).iter()) + .chain(para_id.iter()) + .cloned() + .collect() + }) + } + + /// The list of outbound channels for the given para. + /// + /// The storage entry stores a `Vec` + pub fn hrmp_egress_channel_index(para_id: Id) -> Vec { + let prefix = hex!["6a0da05ca59913bc38a8630590f2627cf12b746dcf32e843354583c9702cc020"]; + + para_id.using_encoded(|para_id: &[u8]| { + prefix + .as_ref() + .iter() + .chain(twox_64(para_id).iter()) + .chain(para_id.iter()) + .cloned() + .collect() + }) + } + + /// The MQC head for the downward message queue of the given para. See more in the `Dmp` module. + /// + /// The storage entry stores a `Hash`. This is polkadot hash which is at the moment + /// `blake2b-256`. + pub fn dmq_mqc_head(para_id: Id) -> Vec { + let prefix = hex!["63f78c98723ddc9073523ef3beefda0c4d7fefc408aac59dbfe80a72ac8e3ce5"]; + + para_id.using_encoded(|para_id: &[u8]| { + prefix + .as_ref() + .iter() + .chain(twox_64(para_id).iter()) + .chain(para_id.iter()) + .cloned() + .collect() + }) + } + + /// The signal that indicates whether the parachain should go-ahead with the proposed validation + /// code upgrade. + /// + /// The storage entry stores a value of `UpgradeGoAhead` type. + pub fn upgrade_go_ahead_signal(para_id: Id) -> Vec { + let prefix = hex!["cd710b30bd2eab0352ddcc26417aa1949e94c040f5e73d9b7addd6cb603d15d3"]; + + para_id.using_encoded(|para_id: &[u8]| { + prefix + .as_ref() + .iter() + .chain(twox_64(para_id).iter()) + .chain(para_id.iter()) + .cloned() + .collect() + }) + } + + /// The signal that indicates whether the parachain is disallowed to signal an upgrade at this + /// relay-parent. + /// + /// The storage entry stores a value of `UpgradeRestriction` type. + pub fn upgrade_restriction_signal(para_id: Id) -> Vec { + let prefix = hex!["cd710b30bd2eab0352ddcc26417aa194f27bbb460270642b5bcaf032ea04d56a"]; + + para_id.using_encoded(|para_id: &[u8]| { + prefix + .as_ref() + .iter() + .chain(twox_64(para_id).iter()) + .chain(para_id.iter()) + .cloned() + .collect() + }) + } +} + +/// Unique identifier for the Parachains Inherent +pub const PARACHAINS_INHERENT_IDENTIFIER: InherentIdentifier = *b"parachn0"; + +/// The key type ID for parachain assignment key. +pub const ASSIGNMENT_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"asgn"); + +/// Maximum compressed code size we support right now. +/// At the moment we have runtime upgrade on chain, which restricts scalability severely. If we want +/// to have bigger values, we should fix that first. +/// +/// Used for: +/// * initial genesis for the Parachains configuration +/// * checking updates to this stored runtime configuration do not exceed this limit +/// * when detecting a code decompression bomb in the client +// NOTE: This value is used in the runtime so be careful when changing it. +pub const MAX_CODE_SIZE: u32 = 3 * 1024 * 1024; + +/// Maximum head data size we support right now. +/// +/// Used for: +/// * initial genesis for the Parachains configuration +/// * checking updates to this stored runtime configuration do not exceed this limit +// NOTE: This value is used in the runtime so be careful when changing it. +pub const MAX_HEAD_DATA_SIZE: u32 = 1 * 1024 * 1024; + +/// Maximum PoV size we support right now. +/// +/// Used for: +/// * initial genesis for the Parachains configuration +/// * checking updates to this stored runtime configuration do not exceed this limit +/// * when detecting a PoV decompression bomb in the client +// NOTE: This value is used in the runtime so be careful when changing it. +pub const MAX_POV_SIZE: u32 = 5 * 1024 * 1024; + +// The public key of a keypair used by a validator for determining assignments +/// to approve included parachain candidates. +mod assignment_app { + use application_crypto::{app_crypto, sr25519}; + app_crypto!(sr25519, super::ASSIGNMENT_KEY_TYPE_ID); +} + +/// The public key of a keypair used by a validator for determining assignments +/// to approve included parachain candidates. +pub type AssignmentId = assignment_app::Public; + +application_crypto::with_pair! { + /// The full keypair used by a validator for determining assignments to approve included + /// parachain candidates. + pub type AssignmentPair = assignment_app::Pair; +} + #[cfg(feature = "std")] -use parity_util_mem::MallocSizeOf; +impl MallocSizeOf for AssignmentId { + fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { + 0 + } + fn constant_size() -> Option { + Some(0) + } +} + +/// The index of the candidate in the list of candidates fully included as-of the block. +pub type CandidateIndex = u32; + +/// Get a collator signature payload on a relay-parent, block-data combo. +pub fn collator_signature_payload>( + relay_parent: &H, + para_id: &Id, + persisted_validation_data_hash: &Hash, + pov_hash: &Hash, + validation_code_hash: &ValidationCodeHash, +) -> [u8; 132] { + // 32-byte hash length is protected in a test below. + let mut payload = [0u8; 132]; + + payload[0..32].copy_from_slice(relay_parent.as_ref()); + u32::from(*para_id).using_encoded(|s| payload[32..32 + s.len()].copy_from_slice(s)); + payload[36..68].copy_from_slice(persisted_validation_data_hash.as_ref()); + payload[68..100].copy_from_slice(pov_hash.as_ref()); + payload[100..132].copy_from_slice(validation_code_hash.as_ref()); + + payload +} + +fn check_collator_signature>( + relay_parent: &H, + para_id: &Id, + persisted_validation_data_hash: &Hash, + pov_hash: &Hash, + validation_code_hash: &ValidationCodeHash, + collator: &CollatorId, + signature: &CollatorSignature, +) -> Result<(), ()> { + let payload = collator_signature_payload( + relay_parent, + para_id, + persisted_validation_data_hash, + pov_hash, + validation_code_hash, + ); + + if signature.verify(&payload[..], collator) { + Ok(()) + } else { + Err(()) + } +} + +/// A unique descriptor of the candidate receipt. +#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(Hash, MallocSizeOf))] +pub struct CandidateDescriptor { + /// The ID of the para this is a candidate for. + pub para_id: Id, + /// The hash of the relay-chain block this is executed in the context of. + pub relay_parent: H, + /// The collator's sr25519 public key. + pub collator: CollatorId, + /// The blake2-256 hash of the persisted validation data. This is extra data derived from + /// relay-chain state which may vary based on bitfields included before the candidate. + /// Thus it cannot be derived entirely from the relay-parent. + pub persisted_validation_data_hash: Hash, + /// The blake2-256 hash of the PoV. + pub pov_hash: Hash, + /// The root of a block's erasure encoding Merkle tree. + pub erasure_root: Hash, + /// Signature on blake2-256 of components of this receipt: + /// The parachain index, the relay parent, the validation data hash, and the `pov_hash`. + pub signature: CollatorSignature, + /// Hash of the para header that is being generated by this candidate. + pub para_head: Hash, + /// The blake2-256 hash of the validation code bytes. + pub validation_code_hash: ValidationCodeHash, +} + +impl> CandidateDescriptor { + /// Check the signature of the collator within this descriptor. + pub fn check_collator_signature(&self) -> Result<(), ()> { + check_collator_signature( + &self.relay_parent, + &self.para_id, + &self.persisted_validation_data_hash, + &self.pov_hash, + &self.validation_code_hash, + &self.collator, + &self.signature, + ) + } +} + +/// A candidate-receipt. +#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(MallocSizeOf))] +pub struct CandidateReceipt { + /// The descriptor of the candidate. + pub descriptor: CandidateDescriptor, + /// The hash of the encoded commitments made as a result of candidate execution. + pub commitments_hash: Hash, +} + +impl CandidateReceipt { + /// Get a reference to the candidate descriptor. + pub fn descriptor(&self) -> &CandidateDescriptor { + &self.descriptor + } + + /// Computes the blake2-256 hash of the receipt. + pub fn hash(&self) -> CandidateHash + where + H: Encode, + { + CandidateHash(BlakeTwo256::hash_of(self)) + } +} + +/// All data pertaining to the execution of a para candidate. +#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +pub struct FullCandidateReceipt { + /// The inner candidate receipt. + pub inner: CandidateReceipt, + /// The validation data derived from the relay-chain state at that + /// point. The hash of the persisted validation data should + /// match the `persisted_validation_data_hash` in the descriptor + /// of the receipt. + pub validation_data: PersistedValidationData, +} + +/// A candidate-receipt with commitments directly included. +#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(Hash, MallocSizeOf))] +pub struct CommittedCandidateReceipt { + /// The descriptor of the candidate. + pub descriptor: CandidateDescriptor, + /// The commitments of the candidate receipt. + pub commitments: CandidateCommitments, +} + +impl CommittedCandidateReceipt { + /// Get a reference to the candidate descriptor. + pub fn descriptor(&self) -> &CandidateDescriptor { + &self.descriptor + } +} + +impl CommittedCandidateReceipt { + /// Transforms this into a plain `CandidateReceipt`. + pub fn to_plain(&self) -> CandidateReceipt { + CandidateReceipt { + descriptor: self.descriptor.clone(), + commitments_hash: self.commitments.hash(), + } + } + + /// Computes the hash of the committed candidate receipt. + /// + /// This computes the canonical hash, not the hash of the directly encoded data. + /// Thus this is a shortcut for `candidate.to_plain().hash()`. + pub fn hash(&self) -> CandidateHash + where + H: Encode, + { + self.to_plain().hash() + } + + /// Does this committed candidate receipt corresponds to the given [`CandidateReceipt`]? + pub fn corresponds_to(&self, receipt: &CandidateReceipt) -> bool + where + H: PartialEq, + { + receipt.descriptor == self.descriptor && receipt.commitments_hash == self.commitments.hash() + } +} + +impl PartialOrd for CommittedCandidateReceipt { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for CommittedCandidateReceipt { + fn cmp(&self, other: &Self) -> sp_std::cmp::Ordering { + // TODO: compare signatures or something more sane + // https://github.com/paritytech/polkadot/issues/222 + self.descriptor() + .para_id + .cmp(&other.descriptor().para_id) + .then_with(|| self.commitments.head_data.cmp(&other.commitments.head_data)) + } +} + +/// The validation data provides information about how to create the inputs for validation of a candidate. +/// This information is derived from the chain state and will vary from para to para, although some +/// fields may be the same for every para. +/// +/// Since this data is used to form inputs to the validation function, it needs to be persisted by the +/// availability system to avoid dependence on availability of the relay-chain state. +/// +/// Furthermore, the validation data acts as a way to authorize the additional data the collator needs +/// to pass to the validation function. For example, the validation function can check whether the incoming +/// messages (e.g. downward messages) were actually sent by using the data provided in the validation data +/// using so called MQC heads. +/// +/// Since the commitments of the validation function are checked by the relay-chain, secondary checkers +/// can rely on the invariant that the relay-chain only includes para-blocks for which these checks have +/// already been done. As such, there is no need for the validation data used to inform validators and +/// collators about the checks the relay-chain will perform to be persisted by the availability system. +/// +/// The `PersistedValidationData` should be relatively lightweight primarily because it is constructed +/// during inclusion for each candidate and therefore lies on the critical path of inclusion. +#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(Default, MallocSizeOf))] +pub struct PersistedValidationData { + /// The parent head-data. + pub parent_head: HeadData, + /// The relay-chain block number this is in the context of. + pub relay_parent_number: N, + /// The relay-chain block storage root this is in the context of. + pub relay_parent_storage_root: H, + /// The maximum legal size of a POV block, in bytes. + pub max_pov_size: u32, +} + +impl PersistedValidationData { + /// Compute the blake2-256 hash of the persisted validation data. + pub fn hash(&self) -> Hash { + BlakeTwo256::hash_of(self) + } +} + +/// Commitments made in a `CandidateReceipt`. Many of these are outputs of validation. +#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(Hash, MallocSizeOf, Default))] +pub struct CandidateCommitments { + /// Messages destined to be interpreted by the Relay chain itself. + pub upward_messages: Vec, + /// Horizontal messages sent by the parachain. + pub horizontal_messages: Vec>, + /// New validation code. + pub new_validation_code: Option, + /// The head-data produced as a result of execution. + pub head_data: HeadData, + /// The number of messages processed from the DMQ. + pub processed_downward_messages: u32, + /// The mark which specifies the block number up to which all inbound HRMP messages are processed. + pub hrmp_watermark: N, +} + +impl CandidateCommitments { + /// Compute the blake2-256 hash of the commitments. + pub fn hash(&self) -> Hash { + BlakeTwo256::hash_of(self) + } +} + +/// A bitfield concerning availability of backed candidates. +/// +/// Every bit refers to an availability core index. +#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)] +pub struct AvailabilityBitfield(pub BitVec); + +impl From> for AvailabilityBitfield { + fn from(inner: BitVec) -> Self { + AvailabilityBitfield(inner) + } +} + +/// A signed compact statement, suitable to be sent to the chain. +pub type SignedStatement = Signed; + +/// A bitfield signed by a particular validator about the availability of pending candidates. +pub type SignedAvailabilityBitfield = Signed; +/// A signed bitfield with signature not yet checked. +pub type UncheckedSignedAvailabilityBitfield = UncheckedSigned; + +/// A set of signed availability bitfields. Should be sorted by validator index, ascending. +pub type SignedAvailabilityBitfields = Vec; +/// A set of unchecked signed availability bitfields. Should be sorted by validator index, ascending. +pub type UncheckedSignedAvailabilityBitfields = Vec; + +/// A backed (or backable, depending on context) candidate. +#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] +pub struct BackedCandidate { + /// The candidate referred to. + pub candidate: CommittedCandidateReceipt, + /// The validity votes themselves, expressed as signatures. + pub validity_votes: Vec, + /// The indices of the validators within the group, expressed as a bitfield. + pub validator_indices: BitVec, +} + +impl BackedCandidate { + /// Get a reference to the descriptor of the para. + pub fn descriptor(&self) -> &CandidateDescriptor { + &self.candidate.descriptor + } + + /// Compute this candidate's hash. + pub fn hash(&self) -> CandidateHash + where + H: Clone + Encode, + { + self.candidate.hash() + } + + /// Get this candidate's receipt. + pub fn receipt(&self) -> CandidateReceipt + where + H: Clone, + { + self.candidate.to_plain() + } +} + +/// Verify the backing of the given candidate. +/// +/// Provide a lookup from the index of a validator within the group assigned to this para, +/// as opposed to the index of the validator within the overall validator set, as well as +/// the number of validators in the group. +/// +/// Also provide the signing context. +/// +/// Returns either an error, indicating that one of the signatures was invalid or that the index +/// was out-of-bounds, or the number of signatures checked. +pub fn check_candidate_backing + Clone + Encode>( + backed: &BackedCandidate, + signing_context: &SigningContext, + group_len: usize, + validator_lookup: impl Fn(usize) -> Option, +) -> Result { + if backed.validator_indices.len() != group_len { + return Err(()) + } + + if backed.validity_votes.len() > group_len { + return Err(()) + } + + // this is known, even in runtime, to be blake2-256. + let hash = backed.candidate.hash(); + + let mut signed = 0; + for ((val_in_group_idx, _), attestation) in backed + .validator_indices + .iter() + .enumerate() + .filter(|(_, signed)| **signed) + .zip(backed.validity_votes.iter()) + { + let validator_id = validator_lookup(val_in_group_idx).ok_or(())?; + let payload = attestation.signed_payload(hash.clone(), signing_context); + let sig = attestation.signature(); + + if sig.verify(&payload[..], &validator_id) { + signed += 1; + } else { + return Err(()) + } + } + + if signed != backed.validity_votes.len() { + return Err(()) + } + + Ok(signed) +} + +/// The unique (during session) index of a core. +#[derive( + Encode, Decode, Default, PartialOrd, Ord, Eq, PartialEq, Clone, Copy, TypeInfo, RuntimeDebug, +)] +#[cfg_attr(feature = "std", derive(Hash, MallocSizeOf))] +pub struct CoreIndex(pub u32); + +impl From for CoreIndex { + fn from(i: u32) -> CoreIndex { + CoreIndex(i) + } +} + +/// The unique (during session) index of a validator group. +#[derive(Encode, Decode, Default, Clone, Copy, Debug, PartialEq, Eq, TypeInfo)] +#[cfg_attr(feature = "std", derive(Hash, MallocSizeOf))] +pub struct GroupIndex(pub u32); + +impl From for GroupIndex { + fn from(i: u32) -> GroupIndex { + GroupIndex(i) + } +} + +/// A claim on authoring the next block for a given parathread. +#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(PartialEq))] +pub struct ParathreadClaim(pub Id, pub CollatorId); + +/// An entry tracking a claim to ensure it does not pass the maximum number of retries. +#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(PartialEq))] +pub struct ParathreadEntry { + /// The claim. + pub claim: ParathreadClaim, + /// Number of retries. + pub retries: u32, +} + +/// What is occupying a specific availability core. +#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(PartialEq))] +pub enum CoreOccupied { + /// A parathread. + Parathread(ParathreadEntry), + /// A parachain. + Parachain, +} + +/// A helper data-type for tracking validator-group rotations. +#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] +pub struct GroupRotationInfo { + /// The block number where the session started. + pub session_start_block: N, + /// How often groups rotate. 0 means never. + pub group_rotation_frequency: N, + /// The current block number. + pub now: N, +} + +impl GroupRotationInfo { + /// Returns the index of the group needed to validate the core at the given index, assuming + /// the given number of cores. + /// + /// `core_index` should be less than `cores`, which is capped at `u32::max()`. + pub fn group_for_core(&self, core_index: CoreIndex, cores: usize) -> GroupIndex { + if self.group_rotation_frequency == 0 { + return GroupIndex(core_index.0) + } + if cores == 0 { + return GroupIndex(0) + } + + let cores = sp_std::cmp::min(cores, u32::MAX as usize); + let blocks_since_start = self.now.saturating_sub(self.session_start_block); + let rotations = blocks_since_start / self.group_rotation_frequency; + + // g = c + r mod cores + + let idx = (core_index.0 as usize + rotations as usize) % cores; + GroupIndex(idx as u32) + } + + /// Returns the index of the group assigned to the given core. This does no checking or + /// whether the group index is in-bounds. + /// + /// `core_index` should be less than `cores`, which is capped at `u32::max()`. + pub fn core_for_group(&self, group_index: GroupIndex, cores: usize) -> CoreIndex { + if self.group_rotation_frequency == 0 { + return CoreIndex(group_index.0) + } + if cores == 0 { + return CoreIndex(0) + } + + let cores = sp_std::cmp::min(cores, u32::MAX as usize); + let blocks_since_start = self.now.saturating_sub(self.session_start_block); + let rotations = blocks_since_start / self.group_rotation_frequency; + let rotations = rotations % cores as u32; + + // g = c + r mod cores + // c = g - r mod cores + // x = x + cores mod cores + // c = (g + cores) - r mod cores + + let idx = (group_index.0 as usize + cores - rotations as usize) % cores; + CoreIndex(idx as u32) + } + + /// Create a new `GroupRotationInfo` with one further rotation applied. + pub fn bump_rotation(&self) -> Self { + GroupRotationInfo { + session_start_block: self.session_start_block, + group_rotation_frequency: self.group_rotation_frequency, + now: self.next_rotation_at(), + } + } +} + +impl GroupRotationInfo { + /// Returns the block number of the next rotation after the current block. If the current block + /// is 10 and the rotation frequency is 5, this should return 15. + pub fn next_rotation_at(&self) -> N { + let cycle_once = self.now + self.group_rotation_frequency; + cycle_once - + (cycle_once.saturating_sub(self.session_start_block) % self.group_rotation_frequency) + } + + /// Returns the block number of the last rotation before or including the current block. If the + /// current block is 10 and the rotation frequency is 5, this should return 10. + pub fn last_rotation_at(&self) -> N { + self.now - + (self.now.saturating_sub(self.session_start_block) % self.group_rotation_frequency) + } +} + +/// Information about a core which is currently occupied. +#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] +pub struct OccupiedCore { + // NOTE: this has no ParaId as it can be deduced from the candidate descriptor. + /// If this core is freed by availability, this is the assignment that is next up on this + /// core, if any. None if there is nothing queued for this core. + pub next_up_on_available: Option, + /// The relay-chain block number this began occupying the core at. + pub occupied_since: N, + /// The relay-chain block this will time-out at, if any. + pub time_out_at: N, + /// If this core is freed by being timed-out, this is the assignment that is next up on this + /// core. None if there is nothing queued for this core or there is no possibility of timing + /// out. + pub next_up_on_time_out: Option, + /// A bitfield with 1 bit for each validator in the set. `1` bits mean that the corresponding + /// validators has attested to availability on-chain. A 2/3+ majority of `1` bits means that + /// this will be available. + #[cfg_attr(feature = "std", ignore_malloc_size_of = "outside type")] + pub availability: BitVec, + /// The group assigned to distribute availability pieces of this candidate. + pub group_responsible: GroupIndex, + /// The hash of the candidate occupying the core. + pub candidate_hash: CandidateHash, + /// The descriptor of the candidate occupying the core. + pub candidate_descriptor: CandidateDescriptor, +} + +impl OccupiedCore { + /// Get the Para currently occupying this core. + pub fn para_id(&self) -> Id { + self.candidate_descriptor.para_id + } +} + +/// Information about a core which is currently occupied. +#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] +pub struct ScheduledCore { + /// The ID of a para scheduled. + pub para_id: Id, + /// The collator required to author the block, if any. + pub collator: Option, +} + +/// The state of a particular availability core. +#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] +pub enum CoreState { + /// The core is currently occupied. + #[codec(index = 0)] + Occupied(OccupiedCore), + /// The core is currently free, with a para scheduled and given the opportunity + /// to occupy. + /// + /// If a particular Collator is required to author this block, that is also present in this + /// variant. + #[codec(index = 1)] + Scheduled(ScheduledCore), + /// The core is currently free and there is nothing scheduled. This can be the case for parathread + /// cores when there are no parathread blocks queued. Parachain cores will never be left idle. + #[codec(index = 2)] + Free, +} + +impl CoreState { + /// If this core state has a `para_id`, return it. + pub fn para_id(&self) -> Option { + match self { + Self::Occupied(ref core) => Some(core.para_id()), + Self::Scheduled(ScheduledCore { para_id, .. }) => Some(*para_id), + Self::Free => None, + } + } + + /// Is this core state `Self::Occupied`? + pub fn is_occupied(&self) -> bool { + matches!(self, Self::Occupied(_)) + } +} + +/// An assumption being made about the state of an occupied core. +#[derive(Clone, Copy, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(PartialEq, Eq, Hash))] +pub enum OccupiedCoreAssumption { + /// The candidate occupying the core was made available and included to free the core. + #[codec(index = 0)] + Included, + /// The candidate occupying the core timed out and freed the core without advancing the para. + #[codec(index = 1)] + TimedOut, + /// The core was not occupied to begin with. + #[codec(index = 2)] + Free, +} + +/// An even concerning a candidate. +#[derive(Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] +pub enum CandidateEvent { + /// This candidate receipt was backed in the most recent block. + /// This includes the core index the candidate is now occupying. + #[codec(index = 0)] + CandidateBacked(CandidateReceipt, HeadData, CoreIndex, GroupIndex), + /// This candidate receipt was included and became a parablock at the most recent block. + /// This includes the core index the candidate was occupying as well as the group responsible + /// for backing the candidate. + #[codec(index = 1)] + CandidateIncluded(CandidateReceipt, HeadData, CoreIndex, GroupIndex), + /// This candidate receipt was not made available in time and timed out. + /// This includes the core index the candidate was occupying. + #[codec(index = 2)] + CandidateTimedOut(CandidateReceipt, HeadData, CoreIndex), +} + +/// Scraped runtime backing votes and resolved disputes. +#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] +#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] +pub struct ScrapedOnChainVotes { + /// The session in which the block was included. + pub session: SessionIndex, + /// Set of backing validators for each candidate, represented by its candidate + /// receipt. + pub backing_validators_per_candidate: + Vec<(CandidateReceipt, Vec<(ValidatorIndex, ValidityAttestation)>)>, + /// On-chain-recorded set of disputes. + /// Note that the above `backing_validators` are + /// unrelated to the backers of the disputes candidates. + pub disputes: MultiDisputeStatementSet, +} + +/// A vote of approval on a candidate. +#[derive(Clone, RuntimeDebug)] +pub struct ApprovalVote(pub CandidateHash); + +impl ApprovalVote { + /// Yields the signing payload for this approval vote. + pub fn signing_payload(&self, session_index: SessionIndex) -> Vec { + const MAGIC: [u8; 4] = *b"APPR"; + + (MAGIC, &self.0, session_index).encode() + } +} + +/// Custom validity errors used in Polkadot while validating transactions. +#[repr(u8)] +pub enum ValidityError { + /// The Ethereum signature is invalid. + InvalidEthereumSignature = 0, + /// The signer has no claim. + SignerHasNoClaim = 1, + /// No permission to execute the call. + NoPermission = 2, + /// An invalid statement was made for a claim. + InvalidStatement = 3, +} + +impl From for u8 { + fn from(err: ValidityError) -> Self { + err as u8 + } +} + +/// Abridged version of `HostConfiguration` (from the `Configuration` parachains host runtime module) +/// meant to be used by a parachain or PDK such as cumulus. +#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] +#[cfg_attr(feature = "std", derive(PartialEq))] +pub struct AbridgedHostConfiguration { + /// The maximum validation code size, in bytes. + pub max_code_size: u32, + /// The maximum head-data size, in bytes. + pub max_head_data_size: u32, + /// Total number of individual messages allowed in the parachain -> relay-chain message queue. + pub max_upward_queue_count: u32, + /// Total size of messages allowed in the parachain -> relay-chain message queue before which + /// no further messages may be added to it. If it exceeds this then the queue may contain only + /// a single message. + pub max_upward_queue_size: u32, + /// The maximum size of an upward message that can be sent by a candidate. + /// + /// This parameter affects the size upper bound of the `CandidateCommitments`. + pub max_upward_message_size: u32, + /// The maximum number of messages that a candidate can contain. + /// + /// This parameter affects the size upper bound of the `CandidateCommitments`. + pub max_upward_message_num_per_candidate: u32, + /// The maximum number of outbound HRMP messages can be sent by a candidate. + /// + /// This parameter affects the upper bound of size of `CandidateCommitments`. + pub hrmp_max_message_num_per_candidate: u32, + /// The minimum period, in blocks, between which parachains can update their validation code. + pub validation_upgrade_cooldown: BlockNumber, + /// The delay, in blocks, before a validation upgrade is applied. + pub validation_upgrade_delay: BlockNumber, +} + +/// Abridged version of `HrmpChannel` (from the `Hrmp` parachains host runtime module) meant to be +/// used by a parachain or PDK such as cumulus. +#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] +#[cfg_attr(feature = "std", derive(PartialEq))] +pub struct AbridgedHrmpChannel { + /// The maximum number of messages that can be pending in the channel at once. + pub max_capacity: u32, + /// The maximum total size of the messages that can be pending in the channel at once. + pub max_total_size: u32, + /// The maximum message size that could be put into the channel. + pub max_message_size: u32, + /// The current number of messages pending in the channel. + /// Invariant: should be less or equal to `max_capacity`.s`. + pub msg_count: u32, + /// The total size in bytes of all message payloads in the channel. + /// Invariant: should be less or equal to `max_total_size`. + pub total_size: u32, + /// A head of the Message Queue Chain for this channel. Each link in this chain has a form: + /// `(prev_head, B, H(M))`, where + /// - `prev_head`: is the previous value of `mqc_head` or zero if none. + /// - `B`: is the [relay-chain] block number in which a message was appended + /// - `H(M)`: is the hash of the message being appended. + /// This value is initialized to a special value that consists of all zeroes which indicates + /// that no messages were previously added. + pub mqc_head: Option, +} + +/// A possible upgrade restriction that prevents a parachain from performing an upgrade. +#[derive(Copy, Clone, Encode, Decode, PartialEq, RuntimeDebug, TypeInfo)] +pub enum UpgradeRestriction { + /// There is an upgrade restriction and there are no details about its specifics nor how long + /// it could last. + #[codec(index = 0)] + Present, +} + +/// A struct that the relay-chain communicates to a parachain indicating what course of action the +/// parachain should take in the coordinated parachain validation code upgrade process. +/// +/// This data type appears in the last step of the upgrade process. After the parachain observes it +/// and reacts to it the upgrade process concludes. +#[derive(Copy, Clone, Encode, Decode, PartialEq, RuntimeDebug, TypeInfo)] +pub enum UpgradeGoAhead { + /// Abort the upgrade process. There is something wrong with the validation code previously + /// submitted by the parachain. This variant can also be used to prevent upgrades by the governance + /// should an emergency emerge. + /// + /// The expected reaction on this variant is that the parachain will admit this message and + /// remove all the data about the pending upgrade. Depending on the nature of the problem (to + /// be examined offchain for now), it can try to send another validation code or just retry later. + #[codec(index = 0)] + Abort, + /// Apply the pending code change. The parablock that is built on a relay-parent that is descendant + /// of the relay-parent where the parachain observed this signal must use the upgraded validation + /// code. + #[codec(index = 1)] + GoAhead, +} + +/// Consensus engine id for polkadot v1 consensus engine. +pub const POLKADOT_ENGINE_ID: runtime_primitives::ConsensusEngineId = *b"POL1"; + +/// A consensus log item for polkadot validation. To be used with [`POLKADOT_ENGINE_ID`]. +#[derive(Decode, Encode, Clone, PartialEq, Eq)] +pub enum ConsensusLog { + /// A parachain or parathread upgraded its code. + #[codec(index = 1)] + ParaUpgradeCode(Id, ValidationCodeHash), + /// A parachain or parathread scheduled a code upgrade. + #[codec(index = 2)] + ParaScheduleUpgradeCode(Id, ValidationCodeHash, BlockNumber), + /// Governance requests to auto-approve every candidate included up to the given block + /// number in the current chain, inclusive. + #[codec(index = 3)] + ForceApprove(BlockNumber), + /// A signal to revert the block number in the same chain as the + /// header this digest is part of and all of its descendants. + /// + /// It is a no-op for a block to contain a revert digest targeting + /// its own number or a higher number. + /// + /// In practice, these are issued when on-chain logic has detected an + /// invalid parachain block within its own chain, due to a dispute. + #[codec(index = 4)] + Revert(BlockNumber), +} + +impl ConsensusLog { + /// Attempt to convert a reference to a generic digest item into a consensus log. + pub fn from_digest_item( + digest_item: &runtime_primitives::DigestItem, + ) -> Result, parity_scale_codec::Error> { + match digest_item { + runtime_primitives::DigestItem::Consensus(id, encoded) if id == &POLKADOT_ENGINE_ID => + Ok(Some(Self::decode(&mut &encoded[..])?)), + _ => Ok(None), + } + } +} + +impl From for runtime_primitives::DigestItem { + fn from(c: ConsensusLog) -> runtime_primitives::DigestItem { + Self::Consensus(POLKADOT_ENGINE_ID, c.encode()) + } +} + +/// A statement about a candidate, to be used within the dispute resolution process. +/// +/// Statements are either in favor of the candidate's validity or against it. +#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)] +#[cfg_attr(feature = "std", derive(MallocSizeOf))] +pub enum DisputeStatement { + /// A valid statement, of the given kind. + #[codec(index = 0)] + Valid(ValidDisputeStatementKind), + /// An invalid statement, of the given kind. + #[codec(index = 1)] + Invalid(InvalidDisputeStatementKind), +} + +impl DisputeStatement { + /// Get the payload data for this type of dispute statement. + pub fn payload_data(&self, candidate_hash: CandidateHash, session: SessionIndex) -> Vec { + match *self { + DisputeStatement::Valid(ValidDisputeStatementKind::Explicit) => + ExplicitDisputeStatement { valid: true, candidate_hash, session }.signing_payload(), + DisputeStatement::Valid(ValidDisputeStatementKind::BackingSeconded( + inclusion_parent, + )) => CompactStatement::Seconded(candidate_hash).signing_payload(&SigningContext { + session_index: session, + parent_hash: inclusion_parent, + }), + DisputeStatement::Valid(ValidDisputeStatementKind::BackingValid(inclusion_parent)) => + CompactStatement::Valid(candidate_hash).signing_payload(&SigningContext { + session_index: session, + parent_hash: inclusion_parent, + }), + DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking) => + ApprovalVote(candidate_hash).signing_payload(session), + DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit) => + ExplicitDisputeStatement { valid: false, candidate_hash, session }.signing_payload(), + } + } + + /// Check the signature on a dispute statement. + pub fn check_signature( + &self, + validator_public: &ValidatorId, + candidate_hash: CandidateHash, + session: SessionIndex, + validator_signature: &ValidatorSignature, + ) -> Result<(), ()> { + let payload = self.payload_data(candidate_hash, session); + + if validator_signature.verify(&payload[..], &validator_public) { + Ok(()) + } else { + Err(()) + } + } + + /// Whether the statement indicates validity. + pub fn indicates_validity(&self) -> bool { + match *self { + DisputeStatement::Valid(_) => true, + DisputeStatement::Invalid(_) => false, + } + } + + /// Whether the statement indicates invalidity. + pub fn indicates_invalidity(&self) -> bool { + match *self { + DisputeStatement::Valid(_) => false, + DisputeStatement::Invalid(_) => true, + } + } + + /// Statement is backing statement. + pub fn is_backing(&self) -> bool { + match *self { + Self::Valid(ValidDisputeStatementKind::BackingSeconded(_)) | + Self::Valid(ValidDisputeStatementKind::BackingValid(_)) => true, + Self::Valid(ValidDisputeStatementKind::Explicit) | + Self::Valid(ValidDisputeStatementKind::ApprovalChecking) | + Self::Invalid(_) => false, + } + } +} + +/// Different kinds of statements of validity on a candidate. +#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)] +#[cfg_attr(feature = "std", derive(MallocSizeOf))] +pub enum ValidDisputeStatementKind { + /// An explicit statement issued as part of a dispute. + #[codec(index = 0)] + Explicit, + /// A seconded statement on a candidate from the backing phase. + #[codec(index = 1)] + BackingSeconded(Hash), + /// A valid statement on a candidate from the backing phase. + #[codec(index = 2)] + BackingValid(Hash), + /// An approval vote from the approval checking phase. + #[codec(index = 3)] + ApprovalChecking, +} + +/// Different kinds of statements of invalidity on a candidate. +#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)] +#[cfg_attr(feature = "std", derive(MallocSizeOf))] +pub enum InvalidDisputeStatementKind { + /// An explicit statement issued as part of a dispute. + #[codec(index = 0)] + Explicit, +} + +/// An explicit statement on a candidate issued as part of a dispute. +#[derive(Clone, PartialEq, RuntimeDebug)] +pub struct ExplicitDisputeStatement { + /// Whether the candidate is valid + pub valid: bool, + /// The candidate hash. + pub candidate_hash: CandidateHash, + /// The session index of the candidate. + pub session: SessionIndex, +} + +impl ExplicitDisputeStatement { + /// Produce the payload used for signing this type of statement. + pub fn signing_payload(&self) -> Vec { + const MAGIC: [u8; 4] = *b"DISP"; + + (MAGIC, self.valid, self.candidate_hash, self.session).encode() + } +} + +/// A set of statements about a specific candidate. +#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)] +#[cfg_attr(feature = "std", derive(MallocSizeOf))] +pub struct DisputeStatementSet { + /// The candidate referenced by this set. + pub candidate_hash: CandidateHash, + /// The session index of the candidate. + pub session: SessionIndex, + /// Statements about the candidate. + pub statements: Vec<(DisputeStatement, ValidatorIndex, ValidatorSignature)>, +} + +impl From for DisputeStatementSet { + fn from(other: CheckedDisputeStatementSet) -> Self { + other.0 + } +} + +impl AsRef for DisputeStatementSet { + fn as_ref(&self) -> &DisputeStatementSet { + &self + } +} + +/// A set of dispute statements. +pub type MultiDisputeStatementSet = Vec; + +/// A _checked_ set of dispute statements. +#[derive(Clone, PartialEq, RuntimeDebug)] +pub struct CheckedDisputeStatementSet(DisputeStatementSet); + +impl AsRef for CheckedDisputeStatementSet { + fn as_ref(&self) -> &DisputeStatementSet { + &self.0 + } +} + +impl core::cmp::PartialEq for CheckedDisputeStatementSet { + fn eq(&self, other: &DisputeStatementSet) -> bool { + self.0.eq(other) + } +} + +impl CheckedDisputeStatementSet { + /// Convert from an unchecked, the verification of correctness of the `unchecked` statement set + /// _must_ be done before calling this function! + pub fn unchecked_from_unchecked(unchecked: DisputeStatementSet) -> Self { + Self(unchecked) + } +} + +/// A set of _checked_ dispute statements. +pub type CheckedMultiDisputeStatementSet = Vec; + +/// The entire state of a dispute. +#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, TypeInfo)] +pub struct DisputeState { + /// A bitfield indicating all validators for the candidate. + pub validators_for: BitVec, // one bit per validator. + /// A bitfield indicating all validators against the candidate. + pub validators_against: BitVec, // one bit per validator. + /// The block number at which the dispute started on-chain. + pub start: N, + /// The block number at which the dispute concluded on-chain. + pub concluded_at: Option, +} + +/// Parachains inherent-data passed into the runtime by a block author +#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)] +pub struct InherentData { + /// Signed bitfields by validators about availability. + pub bitfields: UncheckedSignedAvailabilityBitfields, + /// Backed candidates for inclusion in the block. + pub backed_candidates: Vec>, + /// Sets of dispute votes for inclusion, + pub disputes: MultiDisputeStatementSet, + /// The parent block header. Used for checking state proofs. + pub parent_header: HDR, +} + +/// An either implicit or explicit attestation to the validity of a parachain +/// candidate. +#[derive(Clone, Eq, PartialEq, Decode, Encode, RuntimeDebug, TypeInfo)] +#[cfg_attr(feature = "std", derive(MallocSizeOf))] +pub enum ValidityAttestation { + /// Implicit validity attestation by issuing. + /// This corresponds to issuance of a `Candidate` statement. + #[codec(index = 1)] + Implicit(ValidatorSignature), + /// An explicit attestation. This corresponds to issuance of a + /// `Valid` statement. + #[codec(index = 2)] + Explicit(ValidatorSignature), +} + +impl ValidityAttestation { + /// Produce the underlying signed payload of the attestation, given the hash of the candidate, + /// which should be known in context. + pub fn to_compact_statement(&self, candidate_hash: CandidateHash) -> CompactStatement { + // Explicit and implicit map directly from + // `ValidityVote::Valid` and `ValidityVote::Issued`, and hence there is a + // `1:1` relationshow which enables the conversion. + match *self { + ValidityAttestation::Implicit(_) => CompactStatement::Seconded(candidate_hash), + ValidityAttestation::Explicit(_) => CompactStatement::Valid(candidate_hash), + } + } + + /// Get a reference to the signature. + pub fn signature(&self) -> &ValidatorSignature { + match *self { + ValidityAttestation::Implicit(ref sig) => sig, + ValidityAttestation::Explicit(ref sig) => sig, + } + } + + /// Produce the underlying signed payload of the attestation, given the hash of the candidate, + /// which should be known in context. + pub fn signed_payload( + &self, + candidate_hash: CandidateHash, + signing_context: &SigningContext, + ) -> Vec { + match *self { + ValidityAttestation::Implicit(_) => + (CompactStatement::Seconded(candidate_hash), signing_context).encode(), + ValidityAttestation::Explicit(_) => + (CompactStatement::Valid(candidate_hash), signing_context).encode(), + } + } +} + +/// A type returned by runtime with current session index and a parent hash. +#[derive(Clone, Eq, PartialEq, Default, Decode, Encode, RuntimeDebug)] +pub struct SigningContext { + /// Current session index. + pub session_index: sp_staking::SessionIndex, + /// Hash of the parent. + pub parent_hash: H, +} + +const BACKING_STATEMENT_MAGIC: [u8; 4] = *b"BKNG"; + +/// Statements that can be made about parachain candidates. These are the +/// actual values that are signed. +#[derive(Clone, PartialEq, Eq, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(Hash))] +pub enum CompactStatement { + /// Proposal of a parachain candidate. + Seconded(CandidateHash), + /// State that a parachain candidate is valid. + Valid(CandidateHash), +} + +impl CompactStatement { + /// Yields the payload used for validator signatures on this kind + /// of statement. + pub fn signing_payload(&self, context: &SigningContext) -> Vec { + (self, context).encode() + } +} + +// Inner helper for codec on `CompactStatement`. +#[derive(Encode, Decode, TypeInfo)] +enum CompactStatementInner { + #[codec(index = 1)] + Seconded(CandidateHash), + #[codec(index = 2)] + Valid(CandidateHash), +} + +impl From for CompactStatementInner { + fn from(s: CompactStatement) -> Self { + match s { + CompactStatement::Seconded(h) => CompactStatementInner::Seconded(h), + CompactStatement::Valid(h) => CompactStatementInner::Valid(h), + } + } +} + +impl parity_scale_codec::Encode for CompactStatement { + fn size_hint(&self) -> usize { + // magic + discriminant + payload + 4 + 1 + 32 + } + + fn encode_to(&self, dest: &mut T) { + dest.write(&BACKING_STATEMENT_MAGIC); + CompactStatementInner::from(self.clone()).encode_to(dest) + } +} + +impl parity_scale_codec::Decode for CompactStatement { + fn decode( + input: &mut I, + ) -> Result { + let maybe_magic = <[u8; 4]>::decode(input)?; + if maybe_magic != BACKING_STATEMENT_MAGIC { + return Err(parity_scale_codec::Error::from("invalid magic string")) + } + + Ok(match CompactStatementInner::decode(input)? { + CompactStatementInner::Seconded(h) => CompactStatement::Seconded(h), + CompactStatementInner::Valid(h) => CompactStatement::Valid(h), + }) + } +} + +impl CompactStatement { + /// Get the underlying candidate hash this references. + pub fn candidate_hash(&self) -> &CandidateHash { + match *self { + CompactStatement::Seconded(ref h) | CompactStatement::Valid(ref h) => h, + } + } +} + +/// The maximum number of validators `f` which may safely be faulty. +/// +/// The total number of validators is `n = 3f + e` where `e in { 1, 2, 3 }`. +pub fn byzantine_threshold(n: usize) -> usize { + n.saturating_sub(1) / 3 +} + +/// The supermajority threshold of validators which represents a subset +/// guaranteed to have at least f+1 honest validators. +pub fn supermajority_threshold(n: usize) -> usize { + n - byzantine_threshold(n) +} /// Information about validator sets of a session. #[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] @@ -33,11 +1547,11 @@ pub struct SessionInfo { /****** New in v2 *******/ /// All the validators actively participating in parachain consensus. /// Indices are into the broader validator set. - pub active_validator_indices: Vec, + pub active_validator_indices: Vec, /// A secure random seed for the session, gathered from BABE. pub random_seed: [u8; 32], /// The amount of sessions to keep for disputes. - pub dispute_period: v1::SessionIndex, + pub dispute_period: SessionIndex, /****** Old fields ******/ /// Validators in canonical ordering. @@ -47,7 +1561,7 @@ pub struct SessionInfo { /// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148). /// /// `SessionInfo::validators` will be limited to to `max_validators` when set. - pub validators: Vec, + pub validators: Vec, /// Validators' authority discovery keys for the session in canonical ordering. /// /// NOTE: The first `validators.len()` entries will match the corresponding validators in @@ -55,7 +1569,7 @@ pub struct SessionInfo { /// participating in parachain consensus - see /// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148) #[cfg_attr(feature = "std", ignore_malloc_size_of = "outside type")] - pub discovery_keys: Vec, + pub discovery_keys: Vec, /// The assignment keys for validators. /// /// NOTE: There might be more authorities in the current session, than validators participating @@ -66,11 +1580,11 @@ pub struct SessionInfo { /// ```ignore /// assignment_keys.len() == validators.len() && validators.len() <= discovery_keys.len() /// ``` - pub assignment_keys: Vec, + pub assignment_keys: Vec, /// Validators in shuffled ordering - these are the validator groups as produced /// by the `Scheduler` module for the session and are typically referred to by /// `GroupIndex`. - pub validator_groups: Vec>, + pub validator_groups: Vec>, /// The number of availability cores used by the protocol during this session. pub n_cores: u32, /// The zeroth delay tranche width. @@ -86,28 +1600,6 @@ pub struct SessionInfo { pub needed_approvals: u32, } -impl From for SessionInfo { - fn from(old: v1::SessionInfo) -> SessionInfo { - SessionInfo { - // new fields - active_validator_indices: Vec::new(), - random_seed: [0u8; 32], - dispute_period: 6, - // old fields - validators: old.validators, - discovery_keys: old.discovery_keys, - assignment_keys: old.assignment_keys, - validator_groups: old.validator_groups, - n_cores: old.n_cores, - zeroth_delay_tranche_width: old.zeroth_delay_tranche_width, - relay_vrf_modulo_samples: old.relay_vrf_modulo_samples, - n_delay_tranches: old.n_delay_tranches, - no_show_slots: old.no_show_slots, - needed_approvals: old.needed_approvals, - } - } -} - /// A statement from the specified validator whether the given validation code passes PVF /// pre-checking or not anchored to the given session index. #[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)] @@ -115,11 +1607,11 @@ pub struct PvfCheckStatement { /// `true` if the subject passed pre-checking and `false` otherwise. pub accept: bool, /// The validation code hash that was checked. - pub subject: v1::ValidationCodeHash, + pub subject: ValidationCodeHash, /// The index of a session during which this statement is considered valid. - pub session_index: v1::SessionIndex, + pub session_index: SessionIndex, /// The index of the validator from which this statement originates. - pub validator_index: v1::ValidatorIndex, + pub validator_index: ValidatorIndex, } impl PvfCheckStatement { @@ -136,97 +1628,252 @@ impl PvfCheckStatement { sp_api::decl_runtime_apis! { /// The API for querying the state of parachains on-chain. #[api_version(2)] - pub trait ParachainHost { + pub trait ParachainHost { /// Get the current validators. - fn validators() -> Vec; + fn validators() -> Vec; /// Returns the validator groups and rotation info localized based on the hypothetical child /// of a block whose state this is invoked on. Note that `now` in the `GroupRotationInfo` /// should be the successor of the number of the block. - fn validator_groups() -> (Vec>, v1::GroupRotationInfo); + fn validator_groups() -> (Vec>, GroupRotationInfo); /// Yields information on all availability cores as relevant to the child block. /// Cores are either free or occupied. Free cores can have paras assigned to them. - fn availability_cores() -> Vec>; + fn availability_cores() -> Vec>; /// Yields the persisted validation data for the given `ParaId` along with an assumption that /// should be used if the para currently occupies a core. /// /// Returns `None` if either the para is not registered or the assumption is `Freed` /// and the para already occupies a core. - fn persisted_validation_data(para_id: v1::Id, assumption: v1::OccupiedCoreAssumption) - -> Option>; + fn persisted_validation_data(para_id: Id, assumption: OccupiedCoreAssumption) + -> Option>; /// Returns the persisted validation data for the given `ParaId` along with the corresponding /// validation code hash. Instead of accepting assumption about the para, matches the validation /// data hash against an expected one and yields `None` if they're not equal. fn assumed_validation_data( - para_id: v1::Id, - expected_persisted_validation_data_hash: v1::Hash, - ) -> Option<(v1::PersistedValidationData, v1::ValidationCodeHash)>; + para_id: Id, + expected_persisted_validation_data_hash: Hash, + ) -> Option<(PersistedValidationData, ValidationCodeHash)>; /// Checks if the given validation outputs pass the acceptance criteria. - fn check_validation_outputs(para_id: v1::Id, outputs: v1::CandidateCommitments) -> bool; + fn check_validation_outputs(para_id: Id, outputs: CandidateCommitments) -> bool; /// Returns the session index expected at a child of the block. /// /// This can be used to instantiate a `SigningContext`. - fn session_index_for_child() -> v1::SessionIndex; - - /// Old method to fetch v1 session info. - #[changed_in(2)] - fn session_info(index: v1::SessionIndex) -> Option; + fn session_index_for_child() -> SessionIndex; /// Fetch the validation code used by a para, making the given `OccupiedCoreAssumption`. /// /// Returns `None` if either the para is not registered or the assumption is `Freed` /// and the para already occupies a core. - fn validation_code(para_id: v1::Id, assumption: v1::OccupiedCoreAssumption) - -> Option; + fn validation_code(para_id: Id, assumption: OccupiedCoreAssumption) + -> Option; /// Get the receipt of a candidate pending availability. This returns `Some` for any paras /// assigned to occupied cores in `availability_cores` and `None` otherwise. - fn candidate_pending_availability(para_id: v1::Id) -> Option>; + fn candidate_pending_availability(para_id: Id) -> Option>; /// Get a vector of events concerning candidates that occurred within a block. - fn candidate_events() -> Vec>; + fn candidate_events() -> Vec>; /// Get all the pending inbound messages in the downward message queue for a para. fn dmq_contents( - recipient: v1::Id, - ) -> Vec>; + recipient: Id, + ) -> Vec>; /// Get the contents of all channels addressed to the given recipient. Channels that have no /// messages in them are also included. - fn inbound_hrmp_channels_contents(recipient: v1::Id) -> BTreeMap>>; + fn inbound_hrmp_channels_contents(recipient: Id) -> BTreeMap>>; /// Get the validation code from its hash. - fn validation_code_by_hash(hash: v1::ValidationCodeHash) -> Option; + fn validation_code_by_hash(hash: ValidationCodeHash) -> Option; /// Scrape dispute relevant from on-chain, backing votes and resolved disputes. - fn on_chain_votes() -> Option>; + fn on_chain_votes() -> Option>; /***** Added in v2 *****/ /// Get the session info for the given session, if stored. /// /// NOTE: This function is only available since parachain host version 2. - fn session_info(index: v1::SessionIndex) -> Option; + fn session_info(index: SessionIndex) -> Option; /// Submits a PVF pre-checking statement into the transaction pool. /// /// NOTE: This function is only available since parachain host version 2. - fn submit_pvf_check_statement(stmt: PvfCheckStatement, signature: v1::ValidatorSignature); + fn submit_pvf_check_statement(stmt: PvfCheckStatement, signature: ValidatorSignature); /// Returns code hashes of PVFs that require pre-checking by validators in the active set. /// /// NOTE: This function is only available since parachain host version 2. - fn pvfs_require_precheck() -> Vec; + fn pvfs_require_precheck() -> Vec; /// Fetch the hash of the validation code used by a para, making the given `OccupiedCoreAssumption`. /// /// NOTE: This function is only available since parachain host version 2. - fn validation_code_hash(para_id: v1::Id, assumption: v1::OccupiedCoreAssumption) - -> Option; + fn validation_code_hash(para_id: Id, assumption: OccupiedCoreAssumption) + -> Option; + + + /***** Replaced in v2 *****/ + + /// Old method to fetch v1 session info. + #[changed_in(2)] + fn session_info(index: SessionIndex) -> Option; + } +} + +/// Old, v1-style info about session info. Only needed for limited +/// backwards-compatibility. +#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] +#[cfg_attr(feature = "std", derive(PartialEq, MallocSizeOf))] +pub struct OldV1SessionInfo { + /// Validators in canonical ordering. + /// + /// NOTE: There might be more authorities in the current session, than `validators` participating + /// in parachain consensus. See + /// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148). + /// + /// `SessionInfo::validators` will be limited to to `max_validators` when set. + pub validators: Vec, + /// Validators' authority discovery keys for the session in canonical ordering. + /// + /// NOTE: The first `validators.len()` entries will match the corresponding validators in + /// `validators`, afterwards any remaining authorities can be found. This is any authorities not + /// participating in parachain consensus - see + /// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148) + #[cfg_attr(feature = "std", ignore_malloc_size_of = "outside type")] + pub discovery_keys: Vec, + /// The assignment keys for validators. + /// + /// NOTE: There might be more authorities in the current session, than validators participating + /// in parachain consensus. See + /// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148). + /// + /// Therefore: + /// ```ignore + /// assignment_keys.len() == validators.len() && validators.len() <= discovery_keys.len() + /// ``` + pub assignment_keys: Vec, + /// Validators in shuffled ordering - these are the validator groups as produced + /// by the `Scheduler` module for the session and are typically referred to by + /// `GroupIndex`. + pub validator_groups: Vec>, + /// The number of availability cores used by the protocol during this session. + pub n_cores: u32, + /// The zeroth delay tranche width. + pub zeroth_delay_tranche_width: u32, + /// The number of samples we do of `relay_vrf_modulo`. + pub relay_vrf_modulo_samples: u32, + /// The number of delay tranches in total. + pub n_delay_tranches: u32, + /// How many slots (BABE / SASSAFRAS) must pass before an assignment is considered a + /// no-show. + pub no_show_slots: u32, + /// The number of validators needed to approve a block. + pub needed_approvals: u32, +} + +impl From for SessionInfo { + fn from(old: OldV1SessionInfo) -> SessionInfo { + SessionInfo { + // new fields + active_validator_indices: Vec::new(), + random_seed: [0u8; 32], + dispute_period: 6, + // old fields + validators: old.validators, + discovery_keys: old.discovery_keys, + assignment_keys: old.assignment_keys, + validator_groups: old.validator_groups, + n_cores: old.n_cores, + zeroth_delay_tranche_width: old.zeroth_delay_tranche_width, + relay_vrf_modulo_samples: old.relay_vrf_modulo_samples, + n_delay_tranches: old.n_delay_tranches, + no_show_slots: old.no_show_slots, + needed_approvals: old.needed_approvals, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn group_rotation_info_calculations() { + let info = + GroupRotationInfo { session_start_block: 10u32, now: 15, group_rotation_frequency: 5 }; + + assert_eq!(info.next_rotation_at(), 20); + assert_eq!(info.last_rotation_at(), 15); + } + + #[test] + fn group_for_core_is_core_for_group() { + for cores in 1..=256 { + for rotations in 0..(cores * 2) { + let info = GroupRotationInfo { + session_start_block: 0u32, + now: rotations, + group_rotation_frequency: 1, + }; + + for core in 0..cores { + let group = info.group_for_core(CoreIndex(core), cores as usize); + assert_eq!(info.core_for_group(group, cores as usize).0, core); + } + } + } + } + + #[test] + fn collator_signature_payload_is_valid() { + // if this fails, collator signature verification code has to be updated. + let h = Hash::default(); + assert_eq!(h.as_ref().len(), 32); + + let _payload = collator_signature_payload( + &Hash::repeat_byte(1), + &5u32.into(), + &Hash::repeat_byte(2), + &Hash::repeat_byte(3), + &Hash::repeat_byte(4).into(), + ); + } + + #[test] + fn test_byzantine_threshold() { + assert_eq!(byzantine_threshold(0), 0); + assert_eq!(byzantine_threshold(1), 0); + assert_eq!(byzantine_threshold(2), 0); + assert_eq!(byzantine_threshold(3), 0); + assert_eq!(byzantine_threshold(4), 1); + assert_eq!(byzantine_threshold(5), 1); + assert_eq!(byzantine_threshold(6), 1); + assert_eq!(byzantine_threshold(7), 2); + } + + #[test] + fn test_supermajority_threshold() { + assert_eq!(supermajority_threshold(0), 0); + assert_eq!(supermajority_threshold(1), 1); + assert_eq!(supermajority_threshold(2), 2); + assert_eq!(supermajority_threshold(3), 3); + assert_eq!(supermajority_threshold(4), 3); + assert_eq!(supermajority_threshold(5), 4); + assert_eq!(supermajority_threshold(6), 5); + assert_eq!(supermajority_threshold(7), 5); + } + + #[test] + fn balance_bigger_than_usize() { + let zero_b: Balance = 0; + let zero_u: usize = 0; + + assert!(zero_b.leading_zeros() >= zero_u.leading_zeros()); } } diff --git a/primitives/src/v1/signed.rs b/primitives/src/v2/signed.rs similarity index 98% rename from primitives/src/v1/signed.rs rename to primitives/src/v2/signed.rs index 0b123ede6b82..9e199033a61d 100644 --- a/primitives/src/v1/signed.rs +++ b/primitives/src/v2/signed.rs @@ -28,7 +28,7 @@ use sp_std::prelude::Vec; use primitives::RuntimeDebug; use runtime_primitives::traits::AppVerify; -use crate::v0::{SigningContext, ValidatorId, ValidatorIndex, ValidatorSignature}; +use super::{SigningContext, ValidatorId, ValidatorIndex, ValidatorSignature}; /// Signed data with signature already verified. /// @@ -265,7 +265,7 @@ impl, RealPayload: Encode> UncheckedSigned( - public: &crate::v0::ValidatorId, + public: &super::ValidatorId, payload: Payload, context: &SigningContext, validator_index: ValidatorIndex, diff --git a/primitives/test-helpers/src/lib.rs b/primitives/test-helpers/src/lib.rs index ccf103d79e58..9d98cd0b55f5 100644 --- a/primitives/test-helpers/src/lib.rs +++ b/primitives/test-helpers/src/lib.rs @@ -21,7 +21,7 @@ //! //! Note that `dummy_` prefixed values are meant to be fillers, that should not matter, and will //! contain randomness based data. -use polkadot_primitives::v1::{ +use polkadot_primitives::v2::{ CandidateCommitments, CandidateDescriptor, CandidateReceipt, CollatorId, CollatorSignature, CommittedCandidateReceipt, Hash, HeadData, Id as ParaId, ValidationCode, ValidationCodeHash, ValidatorId, @@ -158,7 +158,7 @@ pub fn make_valid_candidate_descriptor>( collator: Sr25519Keyring, ) -> CandidateDescriptor { let validation_code_hash = validation_code_hash.into(); - let payload = polkadot_primitives::v1::collator_signature_payload::( + let payload = polkadot_primitives::v2::collator_signature_payload::( &relay_parent, ¶_id, &persisted_validation_data_hash, @@ -189,7 +189,7 @@ pub fn resign_candidate_descriptor_with_collator>( collator: Sr25519Keyring, ) { descriptor.collator = collator.public().into(); - let payload = polkadot_primitives::v1::collator_signature_payload::( + let payload = polkadot_primitives::v2::collator_signature_payload::( &descriptor.relay_parent, &descriptor.para_id, &descriptor.persisted_validation_data_hash, diff --git a/roadmap/implementers-guide/src/node/utility/runtime-api.md b/roadmap/implementers-guide/src/node/utility/runtime-api.md index 21ace3c70687..6271429c2666 100644 --- a/roadmap/implementers-guide/src/node/utility/runtime-api.md +++ b/roadmap/implementers-guide/src/node/utility/runtime-api.md @@ -12,8 +12,6 @@ Output: None On receipt of `RuntimeApiMessage::Request(relay_parent, request)`, answer the request using the post-state of the `relay_parent` provided and provide the response to the side-channel embedded within the request. -> TODO Do some caching. The underlying rocksdb already has a cache of trie nodes so duplicate requests are unlikely to hit disk. Not required for functionality. - ## Jobs > TODO Don't limit requests based on parent hash, but limit caching. No caching should be done for any requests on `relay_parent`s that are not active based on `ActiveLeavesUpdate` messages. Maybe with some leeway for things that have just been stopped. diff --git a/roadmap/implementers-guide/src/types/README.md b/roadmap/implementers-guide/src/types/README.md index 31f2889921fd..807130a5e66b 100644 --- a/roadmap/implementers-guide/src/types/README.md +++ b/roadmap/implementers-guide/src/types/README.md @@ -32,7 +32,7 @@ digraph { CandidateDescriptor:persisted_validation_data_hash -> PersistedValidationDataHash Id [label="polkadot_parachain::primitives::Id"] - CollatorId [label="polkadot_primitives::v0::CollatorId"] + CollatorId [label="polkadot_primitives::v2::CollatorId"] PoVHash [label = "Hash", shape="doublecircle", fill="gray90"] @@ -114,7 +114,7 @@ digraph { >] - TransientValidationData:balance -> "polkadot_core_primitives::v1::Balance":w + TransientValidationData:balance -> "polkadot_core_primitives::v2::Balance":w CandidateCommitments [label = < @@ -129,7 +129,7 @@ digraph { >] CandidateCommitments:upward_messages -> "polkadot_parachain::primitives::UpwardMessage":w - CandidateCommitments:horizontal_messages -> "polkadot_core_primitives::v1::OutboundHrmpMessage":w + CandidateCommitments:horizontal_messages -> "polkadot_core_primitives::v2::OutboundHrmpMessage":w CandidateCommitments:head_data -> HeadData:w CandidateCommitments:horizontal_messages -> "polkadot_parachain::primitives::Id":w CandidateCommitments:new_validation_code -> "polkadot_parachain::primitives::ValidationCode":w @@ -302,9 +302,9 @@ digraph { SessionInfo:discovery_keys -> AuthorityDiscoveryId:w SessionInfo:validator_groups -> ValidatorIndex:w - ValidatorId [label = "polkadot_primitives::v0::ValidatorId"] + ValidatorId [label = "polkadot_primitives::v2::ValidatorId"] AuthorityDiscoveryId [label = "sp_authority_discovery::AuthorityId"] - ValidatorIndex [label = "polkadot_primitives::v0::ValidatorIndex"] + ValidatorIndex [label = "polkadot_primitives::v2::ValidatorIndex"] AbridgedHostConfiguration [label = <
diff --git a/roadmap/implementers-guide/src/types/overseer-protocol.md b/roadmap/implementers-guide/src/types/overseer-protocol.md index e5538a168d02..3fabdd59540f 100644 --- a/roadmap/implementers-guide/src/types/overseer-protocol.md +++ b/roadmap/implementers-guide/src/types/overseer-protocol.md @@ -679,6 +679,8 @@ This is fueled by an auxiliary type encapsulating all request types defined in t ```rust enum RuntimeApiRequest { + /// Get the version of the runtime API at the given parent hash, if any. + Version(ResponseChannel), /// Get the current validator set. Validators(ResponseChannel>), /// Get the validator groups and rotation info. @@ -723,6 +725,8 @@ enum RuntimeApiRequest { enum RuntimeApiMessage { /// Make a request of the runtime API against the post-state of the given relay-parent. Request(Hash, RuntimeApiRequest), + /// Get the version of the runtime API at the given parent hash, if any. + Version(Hash, ResponseChannel>) } ``` diff --git a/rpc/src/lib.rs b/rpc/src/lib.rs index ab32e1c172de..048afa063eff 100644 --- a/rpc/src/lib.rs +++ b/rpc/src/lib.rs @@ -20,7 +20,7 @@ use std::sync::Arc; -use polkadot_primitives::v0::{AccountId, Balance, Block, BlockNumber, Hash, Nonce}; +use polkadot_primitives::v2::{AccountId, Balance, Block, BlockNumber, Hash, Nonce}; use sc_client_api::AuxStore; use sc_consensus_babe::Epoch; use sc_finality_grandpa::FinalityProofProvider; diff --git a/runtime/common/src/assigned_slots.rs b/runtime/common/src/assigned_slots.rs index 432536b53b9c..d03e65ade107 100644 --- a/runtime/common/src/assigned_slots.rs +++ b/runtime/common/src/assigned_slots.rs @@ -32,7 +32,7 @@ use frame_support::{pallet_prelude::*, traits::Currency}; use frame_system::pallet_prelude::*; pub use pallet::*; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; -use primitives::v1::Id as ParaId; +use primitives::v2::Id as ParaId; use runtime_parachains::{ configuration, paras::{self}, @@ -546,7 +546,7 @@ mod tests { use frame_support::{assert_noop, assert_ok, parameter_types}; use frame_system::EnsureRoot; use pallet_balances; - use primitives::v1::{BlockNumber, Header}; + use primitives::v2::{BlockNumber, Header}; use runtime_parachains::{ configuration as parachains_configuration, paras as parachains_paras, shared as parachains_shared, diff --git a/runtime/common/src/auctions.rs b/runtime/common/src/auctions.rs index 597fe846334e..d20adf7386ce 100644 --- a/runtime/common/src/auctions.rs +++ b/runtime/common/src/auctions.rs @@ -30,7 +30,7 @@ use frame_support::{ }; pub use pallet::*; use parity_scale_codec::Decode; -use primitives::v1::Id as ParaId; +use primitives::v2::Id as ParaId; use sp_runtime::traits::{CheckedSub, One, Saturating, Zero}; use sp_std::{mem::swap, prelude::*}; @@ -658,7 +658,7 @@ mod tests { }; use frame_system::{EnsureRoot, EnsureSignedBy}; use pallet_balances; - use primitives::v1::{BlockNumber, Header, Id as ParaId}; + use primitives::v2::{BlockNumber, Header, Id as ParaId}; use sp_core::H256; use sp_runtime::traits::{BlakeTwo256, IdentityLookup}; use std::{cell::RefCell, collections::BTreeMap}; diff --git a/runtime/common/src/claims.rs b/runtime/common/src/claims.rs index 0cc96b44f971..f22b6636c33c 100644 --- a/runtime/common/src/claims.rs +++ b/runtime/common/src/claims.rs @@ -23,7 +23,7 @@ use frame_support::{ }; pub use pallet::*; use parity_scale_codec::{Decode, Encode}; -use primitives::v1::ValidityError; +use primitives::v2::ValidityError; use scale_info::TypeInfo; #[cfg(feature = "std")] use serde::{self, Deserialize, Deserializer, Serialize, Serializer}; diff --git a/runtime/common/src/crowdloan/mod.rs b/runtime/common/src/crowdloan/mod.rs index 44d45e6ec790..3175183184f3 100644 --- a/runtime/common/src/crowdloan/mod.rs +++ b/runtime/common/src/crowdloan/mod.rs @@ -68,7 +68,7 @@ use frame_support::{ }; pub use pallet::*; use parity_scale_codec::{Decode, Encode}; -use primitives::v1::Id as ParaId; +use primitives::v2::Id as ParaId; use scale_info::TypeInfo; use sp_runtime::{ traits::{ @@ -847,7 +847,7 @@ mod tests { assert_noop, assert_ok, parameter_types, traits::{OnFinalize, OnInitialize}, }; - use primitives::v1::Id as ParaId; + use primitives::v2::Id as ParaId; use sp_core::H256; use std::{cell::RefCell, collections::BTreeMap, sync::Arc}; // The testing primitives are very useful for avoiding having to work with signatures diff --git a/runtime/common/src/impls.rs b/runtime/common/src/impls.rs index fe60c7057746..7066c9a6a955 100644 --- a/runtime/common/src/impls.rs +++ b/runtime/common/src/impls.rs @@ -24,8 +24,8 @@ pub struct ToAuthor(sp_std::marker::PhantomData); impl OnUnbalanced> for ToAuthor where R: pallet_balances::Config + pallet_authorship::Config, - ::AccountId: From, - ::AccountId: Into, + ::AccountId: From, + ::AccountId: Into, ::Event: From>, { fn on_nonzero_unbalanced(amount: NegativeImbalance) { @@ -40,8 +40,8 @@ impl OnUnbalanced> for DealWithFees where R: pallet_balances::Config + pallet_treasury::Config + pallet_authorship::Config, pallet_treasury::Pallet: OnUnbalanced>, - ::AccountId: From, - ::AccountId: Into, + ::AccountId: From, + ::AccountId: Into, ::Event: From>, { fn on_unbalanceds(mut fees_then_tips: impl Iterator>) { @@ -64,7 +64,7 @@ mod tests { use super::*; use frame_support::{parameter_types, traits::FindAuthor, weights::DispatchClass, PalletId}; use frame_system::limits; - use primitives::v1::AccountId; + use primitives::v2::AccountId; use sp_core::H256; use sp_runtime::{ testing::Header, diff --git a/runtime/common/src/integration_tests.rs b/runtime/common/src/integration_tests.rs index 7032c6badc82..63f654bb01c3 100644 --- a/runtime/common/src/integration_tests.rs +++ b/runtime/common/src/integration_tests.rs @@ -30,7 +30,7 @@ use frame_support::{ use frame_support_test::TestRandomness; use frame_system::EnsureRoot; use parity_scale_codec::Encode; -use primitives::v1::{ +use primitives::v2::{ BlockNumber, HeadData, Header, Id as ParaId, ValidationCode, LOWEST_PUBLIC_ID, }; use runtime_parachains::{ diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index 2170ba1c72e6..1aa464be111c 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -47,7 +47,7 @@ use frame_support::{ }; use frame_system::limits; use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment}; -use primitives::v1::{AssignmentId, BlockNumber, ValidatorId}; +use primitives::v2::{AssignmentId, BlockNumber, ValidatorId}; use sp_runtime::{FixedPointNumber, Perbill, Perquintill}; use static_assertions::const_assert; @@ -123,7 +123,7 @@ pub type SlowAdjustingFeeUpdate = /// /// This must only be used as long as the balance type is `u128`. pub type CurrencyToVote = frame_support::traits::U128CurrencyToVote; -static_assertions::assert_eq_size!(primitives::v1::Balance, u128); +static_assertions::assert_eq_size!(primitives::v2::Balance, u128); /// A placeholder since there is currently no provided session key handler for parachain validator /// keys. diff --git a/runtime/common/src/mock.rs b/runtime/common/src/mock.rs index ae664e25efd4..7f4c9ad937ff 100644 --- a/runtime/common/src/mock.rs +++ b/runtime/common/src/mock.rs @@ -22,7 +22,7 @@ use frame_support::{ weights::Weight, }; use parity_scale_codec::{Decode, Encode}; -use primitives::v1::{HeadData, Id as ParaId, ValidationCode}; +use primitives::v2::{HeadData, Id as ParaId, ValidationCode}; use sp_runtime::{traits::SaturatedConversion, Permill}; use std::{cell::RefCell, collections::HashMap}; diff --git a/runtime/common/src/paras_registrar.rs b/runtime/common/src/paras_registrar.rs index 88828283ceee..59806e0cf639 100644 --- a/runtime/common/src/paras_registrar.rs +++ b/runtime/common/src/paras_registrar.rs @@ -24,7 +24,7 @@ use frame_support::{ traits::{Currency, Get, ReservableCurrency}, }; use frame_system::{self, ensure_root, ensure_signed}; -use primitives::v1::{HeadData, Id as ParaId, ValidationCode, LOWEST_PUBLIC_ID}; +use primitives::v2::{HeadData, Id as ParaId, ValidationCode, LOWEST_PUBLIC_ID}; use runtime_parachains::{ configuration, ensure_parachain, paras::{self, ParaGenesisArgs}, @@ -599,7 +599,7 @@ mod tests { }; use frame_system::limits; use pallet_balances::Error as BalancesError; - use primitives::v1::{Balance, BlockNumber, Header}; + use primitives::v2::{Balance, BlockNumber, Header}; use runtime_parachains::{configuration, origin, shared}; use sp_core::H256; use sp_io::TestExternalities; diff --git a/runtime/common/src/paras_sudo_wrapper.rs b/runtime/common/src/paras_sudo_wrapper.rs index 91430155b34d..49f27a8d44c3 100644 --- a/runtime/common/src/paras_sudo_wrapper.rs +++ b/runtime/common/src/paras_sudo_wrapper.rs @@ -20,7 +20,7 @@ use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; pub use pallet::*; use parity_scale_codec::Encode; -use primitives::v1::Id as ParaId; +use primitives::v2::Id as ParaId; use runtime_parachains::{ configuration, dmp, hrmp, paras::{self, ParaGenesisArgs}, diff --git a/runtime/common/src/slots.rs b/runtime/common/src/slots.rs index e349c4f9ac57..6625fc459fac 100644 --- a/runtime/common/src/slots.rs +++ b/runtime/common/src/slots.rs @@ -29,7 +29,7 @@ use frame_support::{ }; use frame_system::pallet_prelude::*; pub use pallet::*; -use primitives::v1::Id as ParaId; +use primitives::v2::Id as ParaId; use sp_runtime::traits::{CheckedConversion, CheckedSub, Saturating, Zero}; use sp_std::prelude::*; @@ -502,7 +502,7 @@ mod tests { use frame_support::{assert_noop, assert_ok, parameter_types}; use frame_system::EnsureRoot; use pallet_balances; - use primitives::v1::{BlockNumber, Header}; + use primitives::v2::{BlockNumber, Header}; use sp_core::H256; use sp_runtime::traits::{BlakeTwo256, IdentityLookup}; diff --git a/runtime/common/src/traits.rs b/runtime/common/src/traits.rs index 98abe62c2a11..bb05a2ff9081 100644 --- a/runtime/common/src/traits.rs +++ b/runtime/common/src/traits.rs @@ -20,7 +20,7 @@ use frame_support::{ dispatch::DispatchResult, traits::{Currency, ReservableCurrency}, }; -use primitives::v1::{HeadData, Id as ParaId, ValidationCode}; +use primitives::v2::{HeadData, Id as ParaId, ValidationCode}; use sp_std::vec::*; /// Parachain registration API. diff --git a/runtime/kusama/constants/src/lib.rs b/runtime/kusama/constants/src/lib.rs index f9cdf807c27d..800a4c026715 100644 --- a/runtime/kusama/constants/src/lib.rs +++ b/runtime/kusama/constants/src/lib.rs @@ -17,7 +17,7 @@ #![cfg_attr(not(feature = "std"), no_std)] /// Money matters. pub mod currency { - use primitives::v0::Balance; + use primitives::v2::Balance; /// The existential deposit. pub const EXISTENTIAL_DEPOSIT: Balance = 1 * CENTS; @@ -34,7 +34,7 @@ pub mod currency { /// Time and blocks. pub mod time { - use primitives::v0::{BlockNumber, Moment}; + use primitives::v2::{BlockNumber, Moment}; pub const MILLISECS_PER_BLOCK: Moment = 6000; pub const SLOT_DURATION: Moment = MILLISECS_PER_BLOCK; pub const EPOCH_DURATION_IN_SLOTS: BlockNumber = 1 * HOURS; @@ -54,7 +54,7 @@ pub mod fee { use frame_support::weights::{ WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, }; - use primitives::v0::Balance; + use primitives::v2::Balance; use runtime_common::ExtrinsicBaseWeight; use smallvec::smallvec; pub use sp_runtime::Perbill; diff --git a/runtime/kusama/src/lib.rs b/runtime/kusama/src/lib.rs index 3b7cfe528c04..fd9cfdcaf1e5 100644 --- a/runtime/kusama/src/lib.rs +++ b/runtime/kusama/src/lib.rs @@ -22,15 +22,11 @@ use pallet_transaction_payment::CurrencyAdapter; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; -use primitives::{ - v1::{ - AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt, - CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, - InboundHrmpMessage, Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, - ScrapedOnChainVotes, Signature, ValidationCode, ValidationCodeHash, ValidatorId, - ValidatorIndex, - }, - v2::SessionInfo, +use primitives::v2::{ + AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt, + CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, + Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes, + SessionInfo, Signature, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, }; use runtime_common::{ auctions, claims, crowdloan, impls::DealWithFees, paras_registrar, prod_or_fast, slots, @@ -44,7 +40,7 @@ use runtime_parachains::{ dmp as parachains_dmp, hrmp as parachains_hrmp, inclusion as parachains_inclusion, initializer as parachains_initializer, origin as parachains_origin, paras as parachains_paras, paras_inherent as parachains_paras_inherent, reward_points as parachains_reward_points, - runtime_api_impl::v1 as parachains_runtime_api_impl, scheduler as parachains_scheduler, + runtime_api_impl::v2 as parachains_runtime_api_impl, scheduler as parachains_scheduler, session_info as parachains_session_info, shared as parachains_shared, ump as parachains_ump, }; @@ -1366,7 +1362,7 @@ impl pallet_gilt::Config for Runtime { construct_runtime! { pub enum Runtime where Block = Block, - NodeBlock = primitives::v1::Block, + NodeBlock = primitives::v2::Block, UncheckedExtrinsic = UncheckedExtrinsic { // Basic stuff; balances is uncallable initially. @@ -1666,7 +1662,7 @@ sp_api::impl_runtime_apis! { fn check_validation_outputs( para_id: ParaId, - outputs: primitives::v1::CandidateCommitments, + outputs: primitives::v2::CandidateCommitments, ) -> bool { parachains_runtime_api_impl::check_validation_outputs::(para_id, outputs) } @@ -1719,7 +1715,7 @@ sp_api::impl_runtime_apis! { fn submit_pvf_check_statement( stmt: primitives::v2::PvfCheckStatement, - signature: primitives::v1::ValidatorSignature, + signature: primitives::v2::ValidatorSignature, ) { parachains_runtime_api_impl::submit_pvf_check_statement::(stmt, signature) } diff --git a/runtime/metrics/src/with_runtime_metrics.rs b/runtime/metrics/src/with_runtime_metrics.rs index f95b659a06ca..439b0f3801a2 100644 --- a/runtime/metrics/src/with_runtime_metrics.rs +++ b/runtime/metrics/src/with_runtime_metrics.rs @@ -23,7 +23,7 @@ const TRACING_TARGET: &'static str = "metrics"; use parity_scale_codec::Encode; -use primitives::v1::{ +use primitives::v2::{ metric_definitions::{CounterDefinition, CounterVecDefinition}, RuntimeMetricLabelValues, RuntimeMetricOp, RuntimeMetricUpdate, }; diff --git a/runtime/metrics/src/without_runtime_metrics.rs b/runtime/metrics/src/without_runtime_metrics.rs index 140ea7f65188..27381a0a2aa1 100644 --- a/runtime/metrics/src/without_runtime_metrics.rs +++ b/runtime/metrics/src/without_runtime_metrics.rs @@ -18,7 +18,7 @@ //! provide a dummy implementation for the native runtime to avoid cluttering the runtime code //! with `#[cfg(feature = "runtime-metrics")]`. -use primitives::v1::metric_definitions::{CounterDefinition, CounterVecDefinition}; +use primitives::v2::metric_definitions::{CounterDefinition, CounterVecDefinition}; /// A dummy `Counter`. pub struct Counter; diff --git a/runtime/parachains/src/builder.rs b/runtime/parachains/src/builder.rs index 2cfd27ec9461..549f1428ab73 100644 --- a/runtime/parachains/src/builder.rs +++ b/runtime/parachains/src/builder.rs @@ -21,7 +21,7 @@ use crate::{ }; use bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec}; use frame_support::pallet_prelude::*; -use primitives::v1::{ +use primitives::v2::{ collator_signature_payload, AvailabilityBitfield, BackedCandidate, CandidateCommitments, CandidateDescriptor, CandidateHash, CollatorId, CollatorSignature, CommittedCandidateReceipt, CompactStatement, CoreIndex, CoreOccupied, DisputeStatement, DisputeStatementSet, GroupIndex, diff --git a/runtime/parachains/src/configuration.rs b/runtime/parachains/src/configuration.rs index 4c296a2533e8..e4212d6273a4 100644 --- a/runtime/parachains/src/configuration.rs +++ b/runtime/parachains/src/configuration.rs @@ -22,7 +22,7 @@ use crate::shared; use frame_support::{pallet_prelude::*, weights::constants::WEIGHT_PER_MILLIS}; use frame_system::pallet_prelude::*; use parity_scale_codec::{Decode, Encode}; -use primitives::v1::{Balance, SessionIndex, MAX_CODE_SIZE, MAX_HEAD_DATA_SIZE, MAX_POV_SIZE}; +use primitives::v2::{Balance, SessionIndex, MAX_CODE_SIZE, MAX_HEAD_DATA_SIZE, MAX_POV_SIZE}; use sp_runtime::traits::Zero; use sp_std::prelude::*; @@ -1127,7 +1127,7 @@ pub mod pallet { fn integrity_test() { assert_eq!( &ActiveConfig::::hashed_key(), - primitives::v1::well_known_keys::ACTIVE_CONFIG, + primitives::v2::well_known_keys::ACTIVE_CONFIG, "`well_known_keys::ACTIVE_CONFIG` doesn't match key of `ActiveConfig`! Make sure that the name of the\ configuration pallet is `Configuration` in the runtime!", ); diff --git a/runtime/parachains/src/configuration/migration.rs b/runtime/parachains/src/configuration/migration.rs index 4963b61acb5d..421405edea73 100644 --- a/runtime/parachains/src/configuration/migration.rs +++ b/runtime/parachains/src/configuration/migration.rs @@ -39,7 +39,7 @@ pub fn migrate_to_latest() -> Weight { pub mod v1 { use super::*; - use primitives::v1::{Balance, SessionIndex}; + use primitives::v2::{Balance, SessionIndex}; // Copied over from configuration.rs @ 656dd280f266dc56bd0cf1dbe3ca232960912f34 and removed // all the comments. @@ -246,7 +246,7 @@ mod tests { // doesn't need to be read and also leaving it as one line allows to easily copy it. let raw_config = hex_literal::hex!["0000a000005000000a00000000c8000000c800000a0000000a00000040380000580200000000500000c8000000e87648170000000a00000000000000005039278c0400000000000000000000005039278c0400000000000000000000e8030000009001000a00000000000000009001008070000000000000000000000a0000000a0000000a00000001000000010500000001c8000000060000005802000002000000580200000200000059000000000000001e0000002800000000c817a804000000"]; - let v1 = v1::HostConfiguration::::decode(&mut &raw_config[..]) + let v1 = v1::HostConfiguration::::decode(&mut &raw_config[..]) .unwrap(); // We check only a sample of the values here. If we missed any fields or messed up data types @@ -270,7 +270,7 @@ mod tests { // We specify only the picked fields and the rest should be provided by the `Default` // implementation. That implementation is copied over between the two types and should work // fine. - let v1 = v1::HostConfiguration:: { + let v1 = v1::HostConfiguration:: { ump_max_individual_weight: 0x71616e6f6e0au64, needed_approvals: 69, thread_availability_period: 55, @@ -282,21 +282,21 @@ mod tests { let pending_configs_v1 = vec![ ( 1, - v1::HostConfiguration:: { + v1::HostConfiguration:: { n_delay_tranches: 150, ..v1.clone() }, ), ( 2, - v1::HostConfiguration:: { + v1::HostConfiguration:: { max_validators_per_core: Some(33), ..v1.clone() }, ), ( 3, - v1::HostConfiguration:: { + v1::HostConfiguration:: { parathread_retries: 11, ..v1.clone() }, @@ -337,8 +337,8 @@ mod tests { // The same motivation as for the migration code. See `migrate_to_v2`. #[rustfmt::skip] fn assert_correct_translation( - v1: v1::HostConfiguration, - v2: configuration::HostConfiguration + v1: v1::HostConfiguration, + v2: configuration::HostConfiguration ) { assert_eq!(v1.max_code_size , v2.max_code_size); assert_eq!(v1.max_head_data_size , v2.max_head_data_size); diff --git a/runtime/parachains/src/configuration/tests.rs b/runtime/parachains/src/configuration/tests.rs index 8750560e4a99..e3065dbff90c 100644 --- a/runtime/parachains/src/configuration/tests.rs +++ b/runtime/parachains/src/configuration/tests.rs @@ -520,7 +520,7 @@ fn verify_externally_accessible() { // This test verifies that the value can be accessed through the well known keys and the // host configuration decodes into the abridged version. - use primitives::v1::{well_known_keys, AbridgedHostConfiguration}; + use primitives::v2::{well_known_keys, AbridgedHostConfiguration}; new_test_ext(Default::default()).execute_with(|| { let ground_truth = HostConfiguration::default(); diff --git a/runtime/parachains/src/disputes.rs b/runtime/parachains/src/disputes.rs index a938046b888d..29fa811cc44c 100644 --- a/runtime/parachains/src/disputes.rs +++ b/runtime/parachains/src/disputes.rs @@ -21,7 +21,7 @@ use bitvec::{bitvec, order::Lsb0 as BitOrderLsb0}; use frame_support::{ensure, traits::Get, weights::Weight}; use frame_system::pallet_prelude::*; use parity_scale_codec::{Decode, Encode}; -use primitives::v1::{ +use primitives::v2::{ byzantine_threshold, supermajority_threshold, ApprovalVote, CandidateHash, CheckedDisputeStatementSet, CheckedMultiDisputeStatementSet, CompactStatement, ConsensusLog, DisputeState, DisputeStatement, DisputeStatementSet, ExplicitDisputeStatement, diff --git a/runtime/parachains/src/disputes/tests.rs b/runtime/parachains/src/disputes/tests.rs index d05cda5758c2..28d22f24fc4a 100644 --- a/runtime/parachains/src/disputes/tests.rs +++ b/runtime/parachains/src/disputes/tests.rs @@ -28,7 +28,7 @@ use frame_support::{ assert_err, assert_noop, assert_ok, traits::{OnFinalize, OnInitialize}, }; -use primitives::v1::BlockNumber; +use primitives::v2::BlockNumber; use sp_core::{crypto::CryptoType, Pair}; /// Filtering updates the spam slots, as such update them. diff --git a/runtime/parachains/src/dmp.rs b/runtime/parachains/src/dmp.rs index 4a11796af0ce..9e2210f83856 100644 --- a/runtime/parachains/src/dmp.rs +++ b/runtime/parachains/src/dmp.rs @@ -19,7 +19,7 @@ use crate::{ initializer, }; use frame_support::pallet_prelude::*; -use primitives::v1::{DownwardMessage, Hash, Id as ParaId, InboundDownwardMessage}; +use primitives::v2::{DownwardMessage, Hash, Id as ParaId, InboundDownwardMessage}; use sp_runtime::traits::{BlakeTwo256, Hash as HashT, SaturatedConversion}; use sp_std::{fmt, prelude::*}; use xcm::latest::SendError; diff --git a/runtime/parachains/src/dmp/tests.rs b/runtime/parachains/src/dmp/tests.rs index 46c497dde904..35bda2d973df 100644 --- a/runtime/parachains/src/dmp/tests.rs +++ b/runtime/parachains/src/dmp/tests.rs @@ -18,7 +18,7 @@ use super::*; use crate::mock::{new_test_ext, Configuration, Dmp, MockGenesisConfig, Paras, System}; use hex_literal::hex; use parity_scale_codec::Encode; -use primitives::v1::BlockNumber; +use primitives::v2::BlockNumber; pub(crate) fn run_to_block(to: BlockNumber, new_session: Option>) { while System::block_number() < to { @@ -184,7 +184,7 @@ fn queue_downward_message_critical() { #[test] fn verify_dmq_mqc_head_is_externally_accessible() { use hex_literal::hex; - use primitives::v1::well_known_keys; + use primitives::v2::well_known_keys; let a = ParaId::from(2020); diff --git a/runtime/parachains/src/hrmp.rs b/runtime/parachains/src/hrmp.rs index 025addbc9184..0f221dfa4b73 100644 --- a/runtime/parachains/src/hrmp.rs +++ b/runtime/parachains/src/hrmp.rs @@ -21,7 +21,7 @@ use crate::{ use frame_support::{pallet_prelude::*, traits::ReservableCurrency}; use frame_system::pallet_prelude::*; use parity_scale_codec::{Decode, Encode}; -use primitives::v1::{ +use primitives::v2::{ Balance, Hash, HrmpChannelId, Id as ParaId, InboundHrmpMessage, OutboundHrmpMessage, SessionIndex, }; diff --git a/runtime/parachains/src/hrmp/tests.rs b/runtime/parachains/src/hrmp/tests.rs index 35dd006a4481..ad7871e1f9a7 100644 --- a/runtime/parachains/src/hrmp/tests.rs +++ b/runtime/parachains/src/hrmp/tests.rs @@ -20,7 +20,7 @@ use crate::mock::{ System, Test, }; use frame_support::{assert_noop, assert_ok, traits::Currency as _}; -use primitives::v1::BlockNumber; +use primitives::v2::BlockNumber; use std::collections::BTreeMap; fn run_to_block(to: BlockNumber, new_session: Option>) { @@ -387,7 +387,7 @@ fn check_sent_messages() { #[test] fn verify_externally_accessible() { - use primitives::v1::{well_known_keys, AbridgedHrmpChannel}; + use primitives::v2::{well_known_keys, AbridgedHrmpChannel}; let para_a = 20.into(); let para_b = 21.into(); diff --git a/runtime/parachains/src/inclusion/mod.rs b/runtime/parachains/src/inclusion/mod.rs index ecf5b7c94af8..60903914e9db 100644 --- a/runtime/parachains/src/inclusion/mod.rs +++ b/runtime/parachains/src/inclusion/mod.rs @@ -27,7 +27,7 @@ use crate::{ use bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec}; use frame_support::pallet_prelude::*; use parity_scale_codec::{Decode, Encode}; -use primitives::v1::{ +use primitives::v2::{ AvailabilityBitfield, BackedCandidate, CandidateCommitments, CandidateDescriptor, CandidateHash, CandidateReceipt, CommittedCandidateReceipt, CoreIndex, GroupIndex, Hash, HeadData, Id as ParaId, SigningContext, UncheckedSignedAvailabilityBitfields, ValidatorId, @@ -571,7 +571,7 @@ impl Pallet { // check the signatures in the backing and that it is a majority. { - let maybe_amount_validated = primitives::v1::check_candidate_backing( + let maybe_amount_validated = primitives::v2::check_candidate_backing( &backed_candidate, &signing_context, group_vals.len(), @@ -689,7 +689,7 @@ impl Pallet { /// Run the acceptance criteria checks on the given candidate commitments. pub(crate) fn check_validation_outputs_for_runtime_api( para_id: ParaId, - validation_outputs: primitives::v1::CandidateCommitments, + validation_outputs: primitives::v2::CandidateCommitments, ) -> bool { // This function is meant to be called from the runtime APIs against the relay-parent, hence // `relay_parent_number` is equal to `now`. @@ -1035,11 +1035,11 @@ impl CandidateCheckContext { &self, para_id: ParaId, head_data: &HeadData, - new_validation_code: &Option, + new_validation_code: &Option, processed_downward_messages: u32, - upward_messages: &[primitives::v1::UpwardMessage], + upward_messages: &[primitives::v2::UpwardMessage], hrmp_watermark: T::BlockNumber, - horizontal_messages: &[primitives::v1::OutboundHrmpMessage], + horizontal_messages: &[primitives::v2::OutboundHrmpMessage], ) -> Result<(), AcceptanceCheckErr> { ensure!( head_data.0.len() <= self.config.max_head_data_size as _, diff --git a/runtime/parachains/src/inclusion/tests.rs b/runtime/parachains/src/inclusion/tests.rs index cd6b968ddcd1..8de44a93efd6 100644 --- a/runtime/parachains/src/inclusion/tests.rs +++ b/runtime/parachains/src/inclusion/tests.rs @@ -30,13 +30,11 @@ use assert_matches::assert_matches; use frame_support::assert_noop; use futures::executor::block_on; use keyring::Sr25519Keyring; -use primitives::{ - v0::PARACHAIN_KEY_TYPE_ID, - v1::{ - BlockNumber, CandidateCommitments, CandidateDescriptor, CollatorId, - CompactStatement as Statement, Hash, SignedAvailabilityBitfield, SignedStatement, - UncheckedSignedAvailabilityBitfield, ValidationCode, ValidatorId, ValidityAttestation, - }, +use primitives::v2::{ + BlockNumber, CandidateCommitments, CandidateDescriptor, CollatorId, + CompactStatement as Statement, Hash, SignedAvailabilityBitfield, SignedStatement, + UncheckedSignedAvailabilityBitfield, ValidationCode, ValidatorId, ValidityAttestation, + PARACHAIN_KEY_TYPE_ID, }; use sc_keystore::LocalKeystore; use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; @@ -93,7 +91,7 @@ pub(crate) fn collator_sign_candidate( ) { candidate.descriptor.collator = collator.public().into(); - let payload = primitives::v1::collator_signature_payload( + let payload = primitives::v2::collator_signature_payload( &candidate.descriptor.relay_parent, &candidate.descriptor.para_id, &candidate.descriptor.persisted_validation_data_hash, @@ -148,7 +146,7 @@ pub(crate) async fn back_candidate( let backed = BackedCandidate { candidate, validity_votes, validator_indices }; let successfully_backed = - primitives::v1::check_candidate_backing(&backed, signing_context, group.len(), |i| { + primitives::v2::check_candidate_backing(&backed, signing_context, group.len(), |i| { Some(validators[group[i].0 as usize].public().into()) }) .ok() diff --git a/runtime/parachains/src/initializer.rs b/runtime/parachains/src/initializer.rs index cbfdd84e58a5..027dd677bbba 100644 --- a/runtime/parachains/src/initializer.rs +++ b/runtime/parachains/src/initializer.rs @@ -30,7 +30,7 @@ use frame_support::{ }; use frame_system::limits::BlockWeights; use parity_scale_codec::{Decode, Encode}; -use primitives::v1::{BlockNumber, ConsensusLog, SessionIndex, ValidatorId}; +use primitives::v2::{BlockNumber, ConsensusLog, SessionIndex, ValidatorId}; use scale_info::TypeInfo; use sp_std::prelude::*; diff --git a/runtime/parachains/src/initializer/benchmarking.rs b/runtime/parachains/src/initializer/benchmarking.rs index 761097dbf624..7c6a633790c2 100644 --- a/runtime/parachains/src/initializer/benchmarking.rs +++ b/runtime/parachains/src/initializer/benchmarking.rs @@ -17,7 +17,7 @@ use super::*; use frame_benchmarking::benchmarks; use frame_system::RawOrigin; -use primitives::v1::ConsensusLog; +use primitives::v2::ConsensusLog; use sp_runtime::DigestItem; // Random large number for the digest diff --git a/runtime/parachains/src/initializer/tests.rs b/runtime/parachains/src/initializer/tests.rs index 6085e5f47168..7fdf8b6b4a57 100644 --- a/runtime/parachains/src/initializer/tests.rs +++ b/runtime/parachains/src/initializer/tests.rs @@ -18,7 +18,7 @@ use super::*; use crate::mock::{ new_test_ext, Configuration, Dmp, Initializer, MockGenesisConfig, Paras, SessionInfo, System, }; -use primitives::v1::{HeadData, Id as ParaId}; +use primitives::v2::{HeadData, Id as ParaId}; use test_helpers::dummy_validation_code; use frame_support::{ diff --git a/runtime/parachains/src/lib.rs b/runtime/parachains/src/lib.rs index 20945e7a13d3..2005861a6c4b 100644 --- a/runtime/parachains/src/lib.rs +++ b/runtime/parachains/src/lib.rs @@ -50,7 +50,7 @@ mod mock; pub use origin::{ensure_parachain, Origin}; pub use paras::ParaLifecycle; -use primitives::v1::Id as ParaId; +use primitives::v2::Id as ParaId; /// Schedule a para to be initialized at the start of the next session with the given genesis data. /// @@ -65,7 +65,7 @@ pub fn schedule_para_initialize( /// Schedule a para to be cleaned up at the start of the next session. /// /// See [`paras::Pallet::schedule_para_cleanup`] for more details. -pub fn schedule_para_cleanup(id: primitives::v1::Id) -> Result<(), ()> { +pub fn schedule_para_cleanup(id: primitives::v2::Id) -> Result<(), ()> { >::schedule_para_cleanup(id).map_err(|_| ()) } diff --git a/runtime/parachains/src/metrics.rs b/runtime/parachains/src/metrics.rs index 9f10249c2641..1368bdbfbbf4 100644 --- a/runtime/parachains/src/metrics.rs +++ b/runtime/parachains/src/metrics.rs @@ -17,7 +17,7 @@ //! Runtime declaration of the parachain metrics. use polkadot_runtime_metrics::{Counter, CounterVec}; -use primitives::v1::metric_definitions::{ +use primitives::v2::metric_definitions::{ PARACHAIN_CREATE_INHERENT_BITFIELDS_SIGNATURE_CHECKS, PARACHAIN_INHERENT_DATA_BITFIELDS_PROCESSED, PARACHAIN_INHERENT_DATA_CANDIDATES_PROCESSED, PARACHAIN_INHERENT_DATA_DISPUTE_SETS_INCLUDED, PARACHAIN_INHERENT_DATA_DISPUTE_SETS_PROCESSED, diff --git a/runtime/parachains/src/mock.rs b/runtime/parachains/src/mock.rs index 3c99a07f33ba..416903d1875a 100644 --- a/runtime/parachains/src/mock.rs +++ b/runtime/parachains/src/mock.rs @@ -30,7 +30,7 @@ use frame_support::{ }; use frame_support_test::TestRandomness; use parity_scale_codec::Decode; -use primitives::v1::{ +use primitives::v2::{ AuthorityDiscoveryId, Balance, BlockNumber, Header, Moment, SessionIndex, UpwardMessage, ValidatorIndex, }; diff --git a/runtime/parachains/src/origin.rs b/runtime/parachains/src/origin.rs index 83d4dcc25d99..4eedffe5862f 100644 --- a/runtime/parachains/src/origin.rs +++ b/runtime/parachains/src/origin.rs @@ -16,7 +16,7 @@ //! Declaration of the parachain specific origin and a pallet that hosts it. -use primitives::v1::Id as ParaId; +use primitives::v2::Id as ParaId; use sp_runtime::traits::BadOrigin; use sp_std::result; diff --git a/runtime/parachains/src/paras/benchmarking.rs b/runtime/parachains/src/paras/benchmarking.rs index bd9106422d90..e2c4954a2340 100644 --- a/runtime/parachains/src/paras/benchmarking.rs +++ b/runtime/parachains/src/paras/benchmarking.rs @@ -18,7 +18,7 @@ use super::*; use crate::{configuration::HostConfiguration, shared}; use frame_benchmarking::benchmarks; use frame_system::RawOrigin; -use primitives::v1::{HeadData, Id as ParaId, ValidationCode, MAX_CODE_SIZE, MAX_HEAD_DATA_SIZE}; +use primitives::v2::{HeadData, Id as ParaId, ValidationCode, MAX_CODE_SIZE, MAX_HEAD_DATA_SIZE}; use sp_runtime::traits::{One, Saturating}; // 2 ^ 10, because binary search time complexity is O(log(2, n)) and n = 1024 gives us a big and diff --git a/runtime/parachains/src/paras/mod.rs b/runtime/parachains/src/paras/mod.rs index fc35b80c7a63..06902649d35b 100644 --- a/runtime/parachains/src/paras/mod.rs +++ b/runtime/parachains/src/paras/mod.rs @@ -111,12 +111,9 @@ use bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec}; use frame_support::{pallet_prelude::*, traits::EstimateNextSessionRotation}; use frame_system::pallet_prelude::*; use parity_scale_codec::{Decode, Encode}; -use primitives::{ - v1::{ - ConsensusLog, HeadData, Id as ParaId, SessionIndex, UpgradeGoAhead, UpgradeRestriction, - ValidationCode, ValidationCodeHash, ValidatorSignature, - }, - v2::PvfCheckStatement, +use primitives::v2::{ + ConsensusLog, HeadData, Id as ParaId, PvfCheckStatement, SessionIndex, UpgradeGoAhead, + UpgradeRestriction, ValidationCode, ValidationCodeHash, ValidatorSignature, }; use scale_info::TypeInfo; use sp_core::RuntimeDebug; @@ -387,7 +384,7 @@ impl PvfCheckActiveVoteState { /// Returns `None` if the quorum is not reached, or the direction of the decision. fn quorum(&self, n_validators: usize) -> Option { - let q_threshold = primitives::v1::supermajority_threshold(n_validators); + let q_threshold = primitives::v2::supermajority_threshold(n_validators); // NOTE: counting the reject votes is deliberately placed first. This is to err on the safe. if self.votes_reject.count_ones() >= q_threshold { Some(PvfCheckOutcome::Rejected) diff --git a/runtime/parachains/src/paras/tests.rs b/runtime/parachains/src/paras/tests.rs index 7f4ac54711c1..f2fa90fcafb5 100644 --- a/runtime/parachains/src/paras/tests.rs +++ b/runtime/parachains/src/paras/tests.rs @@ -17,10 +17,7 @@ use super::*; use frame_support::{assert_err, assert_ok, assert_storage_noop}; use keyring::Sr25519Keyring; -use primitives::{ - v0::PARACHAIN_KEY_TYPE_ID, - v1::{BlockNumber, ValidatorId}, -}; +use primitives::v2::{BlockNumber, ValidatorId, PARACHAIN_KEY_TYPE_ID}; use sc_keystore::LocalKeystore; use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use std::sync::Arc; @@ -116,7 +113,7 @@ fn check_code_is_not_stored(validation_code: &ValidationCode) { /// An utility for checking that certain events were deposited. struct EventValidator { events: - Vec::Event, primitives::v1::Hash>>, + Vec::Event, primitives::v2::Hash>>, } impl EventValidator { @@ -1545,7 +1542,7 @@ fn add_trusted_validation_code_enacts_existing_pvf_vote() { #[test] fn verify_upgrade_go_ahead_signal_is_externally_accessible() { - use primitives::v1::well_known_keys; + use primitives::v2::well_known_keys; let a = ParaId::from(2020); @@ -1561,7 +1558,7 @@ fn verify_upgrade_go_ahead_signal_is_externally_accessible() { #[test] fn verify_upgrade_restriction_signal_is_externally_accessible() { - use primitives::v1::well_known_keys; + use primitives::v2::well_known_keys; let a = ParaId::from(2020); diff --git a/runtime/parachains/src/paras_inherent/mod.rs b/runtime/parachains/src/paras_inherent/mod.rs index bbc8b59803cd..2457c40aba06 100644 --- a/runtime/parachains/src/paras_inherent/mod.rs +++ b/runtime/parachains/src/paras_inherent/mod.rs @@ -39,7 +39,7 @@ use frame_support::{ }; use frame_system::pallet_prelude::*; use pallet_babe::{self, CurrentBlockRandomness}; -use primitives::v1::{ +use primitives::v2::{ BackedCandidate, CandidateHash, CandidateReceipt, CheckedDisputeStatementSet, CheckedMultiDisputeStatementSet, CoreIndex, DisputeStatementSet, InherentData as ParachainsInherentData, MultiDisputeStatementSet, ScrapedOnChainVotes, diff --git a/runtime/parachains/src/paras_inherent/tests.rs b/runtime/parachains/src/paras_inherent/tests.rs index eed7ebebbcfa..d1e02837e3c1 100644 --- a/runtime/parachains/src/paras_inherent/tests.rs +++ b/runtime/parachains/src/paras_inherent/tests.rs @@ -139,7 +139,7 @@ mod enter { #[test] fn test_session_is_tracked_in_on_chain_scraping() { use crate::disputes::run_to_block; - use primitives::v1::{ + use primitives::v2::{ DisputeStatement, DisputeStatementSet, ExplicitDisputeStatement, InvalidDisputeStatementKind, ValidDisputeStatementKind, }; @@ -861,8 +861,8 @@ mod enter { } } -fn default_header() -> primitives::v1::Header { - primitives::v1::Header { +fn default_header() -> primitives::v2::Header { + primitives::v2::Header { parent_hash: Default::default(), number: 0, state_root: Default::default(), @@ -878,7 +878,7 @@ mod sanitizers { back_candidate, collator_sign_candidate, BackingKind, TestCandidateBuilder, }; use bitvec::order::Lsb0; - use primitives::v1::{ + use primitives::v2::{ AvailabilityBitfield, GroupIndex, Hash, Id as ParaId, SignedAvailabilityBitfield, ValidatorIndex, }; @@ -887,7 +887,7 @@ mod sanitizers { use crate::mock::Test; use futures::executor::block_on; use keyring::Sr25519Keyring; - use primitives::v0::PARACHAIN_KEY_TYPE_ID; + use primitives::v2::PARACHAIN_KEY_TYPE_ID; use sc_keystore::LocalKeystore; use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use std::sync::Arc; diff --git a/runtime/parachains/src/reward_points.rs b/runtime/parachains/src/reward_points.rs index 3a68ff4710b3..6f5b52018e5d 100644 --- a/runtime/parachains/src/reward_points.rs +++ b/runtime/parachains/src/reward_points.rs @@ -23,7 +23,7 @@ use crate::shared; use pallet_staking::SessionInterface; -use primitives::v1::ValidatorIndex; +use primitives::v2::ValidatorIndex; /// The amount of era points given by backing a candidate that is included. pub const BACKING_POINTS: u32 = 20; @@ -74,7 +74,7 @@ mod tests { mock::{new_test_ext, MockGenesisConfig, ParasShared, Test}, }; use keyring::Sr25519Keyring; - use primitives::v1::ValidatorId; + use primitives::v2::ValidatorId; #[test] fn rewards_based_on_indirection() { diff --git a/runtime/parachains/src/runtime_api_impl/mod.rs b/runtime/parachains/src/runtime_api_impl/mod.rs index 35c26fe35def..edcf4d8ef937 100644 --- a/runtime/parachains/src/runtime_api_impl/mod.rs +++ b/runtime/parachains/src/runtime_api_impl/mod.rs @@ -17,7 +17,7 @@ //! Runtime API implementations for Parachains. //! //! These are exposed as different modules using different sets of primitives. -//! At the moment there is only a v1 module and it is not completely clear how migration +//! At the moment there is only a v2 module and it is not completely clear how migration //! to a v2 would be done. -pub mod v1; +pub mod v2; diff --git a/runtime/parachains/src/runtime_api_impl/v1.rs b/runtime/parachains/src/runtime_api_impl/v2.rs similarity index 95% rename from runtime/parachains/src/runtime_api_impl/v1.rs rename to runtime/parachains/src/runtime_api_impl/v2.rs index 994a720bc590..20ee41636d81 100644 --- a/runtime/parachains/src/runtime_api_impl/v1.rs +++ b/runtime/parachains/src/runtime_api_impl/v2.rs @@ -11,25 +11,22 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -//! A module exporting runtime API implementation functions for all runtime APIs using v1 +//! A module exporting runtime API implementation functions for all runtime APIs using v2 //! primitives. //! -//! Runtimes implementing the v1 runtime API are recommended to forward directly to these +//! Runtimes implementing the v2 runtime API are recommended to forward directly to these //! functions. use crate::{ configuration, dmp, hrmp, inclusion, initializer, paras, paras_inherent, scheduler, session_info, shared, }; -use primitives::{ - v1::{ - AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreIndex, CoreOccupied, - CoreState, GroupIndex, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, - InboundHrmpMessage, OccupiedCore, OccupiedCoreAssumption, PersistedValidationData, - ScheduledCore, ScrapedOnChainVotes, SessionIndex, ValidationCode, ValidationCodeHash, - ValidatorId, ValidatorIndex, ValidatorSignature, - }, - v2::{PvfCheckStatement, SessionInfo}, +use primitives::v2::{ + AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreIndex, CoreOccupied, + CoreState, GroupIndex, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, + InboundHrmpMessage, OccupiedCore, OccupiedCoreAssumption, PersistedValidationData, + PvfCheckStatement, ScheduledCore, ScrapedOnChainVotes, SessionIndex, SessionInfo, + ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature, }; use sp_runtime::traits::One; use sp_std::{collections::btree_map::BTreeMap, prelude::*}; @@ -90,7 +87,7 @@ pub fn availability_cores() -> Vec g, None => { log::warn!( - target: "runtime::polkadot-api::v1", + target: "runtime::polkadot-api::v2", "Could not determine the group responsible for core extracted \ from list of cores for some prior block in same session", ); @@ -259,7 +256,7 @@ pub fn assumed_validation_data( /// Implementation for the `check_validation_outputs` function of the runtime API. pub fn check_validation_outputs( para_id: ParaId, - outputs: primitives::v1::CandidateCommitments, + outputs: primitives::v2::CandidateCommitments, ) -> bool { >::check_validation_outputs_for_runtime_api(para_id, outputs) } diff --git a/runtime/parachains/src/scheduler.rs b/runtime/parachains/src/scheduler.rs index 2753fe4e111b..9bf467f09f83 100644 --- a/runtime/parachains/src/scheduler.rs +++ b/runtime/parachains/src/scheduler.rs @@ -36,7 +36,7 @@ //! over time. use frame_support::pallet_prelude::*; -use primitives::v1::{ +use primitives::v2::{ CollatorId, CoreIndex, CoreOccupied, GroupIndex, GroupRotationInfo, Id as ParaId, ParathreadClaim, ParathreadEntry, ScheduledCore, ValidatorIndex, }; diff --git a/runtime/parachains/src/scheduler/tests.rs b/runtime/parachains/src/scheduler/tests.rs index 234c1833d9f0..eb4200bf9ec9 100644 --- a/runtime/parachains/src/scheduler/tests.rs +++ b/runtime/parachains/src/scheduler/tests.rs @@ -18,7 +18,7 @@ use super::*; use frame_support::assert_ok; use keyring::Sr25519Keyring; -use primitives::v1::{BlockNumber, CollatorId, SessionIndex, ValidatorId}; +use primitives::v2::{BlockNumber, CollatorId, SessionIndex, ValidatorId}; use crate::{ configuration::HostConfiguration, diff --git a/runtime/parachains/src/session_info.rs b/runtime/parachains/src/session_info.rs index 904d46260b8d..5ef19912db94 100644 --- a/runtime/parachains/src/session_info.rs +++ b/runtime/parachains/src/session_info.rs @@ -24,10 +24,7 @@ use crate::{ util::{take_active_subset, take_active_subset_and_inactive}, }; use frame_support::{pallet_prelude::*, traits::OneSessionHandler}; -use primitives::{ - v1::{AssignmentId, AuthorityDiscoveryId, SessionIndex}, - v2::SessionInfo, -}; +use primitives::v2::{AssignmentId, AuthorityDiscoveryId, SessionIndex, SessionInfo}; use sp_std::vec::Vec; pub use pallet::*; diff --git a/runtime/parachains/src/session_info/migration.rs b/runtime/parachains/src/session_info/migration.rs index 07ef965dc97a..e2ed663204ca 100644 --- a/runtime/parachains/src/session_info/migration.rs +++ b/runtime/parachains/src/session_info/migration.rs @@ -35,7 +35,7 @@ pub fn migrate_to_latest() -> Weight { pub fn migrate_to_v1() -> Weight { let mut vs = 0; - as Store>::Sessions::translate_values(|old: primitives::v1::SessionInfo| { + as Store>::Sessions::translate_values(|old: primitives::v2::OldV1SessionInfo| { vs += 1; Some(primitives::v2::SessionInfo::from(old)) }); diff --git a/runtime/parachains/src/session_info/tests.rs b/runtime/parachains/src/session_info/tests.rs index e35007289958..4128463578e6 100644 --- a/runtime/parachains/src/session_info/tests.rs +++ b/runtime/parachains/src/session_info/tests.rs @@ -25,7 +25,7 @@ use crate::{ util::take_active_subset, }; use keyring::Sr25519Keyring; -use primitives::v1::{BlockNumber, ValidatorId, ValidatorIndex}; +use primitives::v2::{BlockNumber, ValidatorId, ValidatorIndex}; fn run_to_block( to: BlockNumber, diff --git a/runtime/parachains/src/shared.rs b/runtime/parachains/src/shared.rs index 7bd33c503c63..e309e128800a 100644 --- a/runtime/parachains/src/shared.rs +++ b/runtime/parachains/src/shared.rs @@ -20,7 +20,7 @@ //! dependent on any of the other pallets. use frame_support::pallet_prelude::*; -use primitives::v1::{SessionIndex, ValidatorId, ValidatorIndex}; +use primitives::v2::{SessionIndex, ValidatorId, ValidatorIndex}; use sp_std::vec::Vec; use rand::{seq::SliceRandom, SeedableRng}; diff --git a/runtime/parachains/src/ump.rs b/runtime/parachains/src/ump.rs index 3ccb51a3329c..71deb778005e 100644 --- a/runtime/parachains/src/ump.rs +++ b/runtime/parachains/src/ump.rs @@ -20,7 +20,7 @@ use crate::{ }; use frame_support::{pallet_prelude::*, traits::EnsureOrigin}; use frame_system::pallet_prelude::*; -use primitives::v1::{Id as ParaId, UpwardMessage}; +use primitives::v2::{Id as ParaId, UpwardMessage}; use sp_std::{ collections::btree_map::BTreeMap, convert::TryFrom, fmt, marker::PhantomData, mem, prelude::*, }; diff --git a/runtime/parachains/src/ump/tests.rs b/runtime/parachains/src/ump/tests.rs index 8911a52c5113..b4e758b4b88c 100644 --- a/runtime/parachains/src/ump/tests.rs +++ b/runtime/parachains/src/ump/tests.rs @@ -261,7 +261,7 @@ fn verify_relay_dispatch_queue_size_is_externally_accessible() { // keys and is decodable into a (u32, u32). use parity_scale_codec::Decode as _; - use primitives::v1::well_known_keys; + use primitives::v2::well_known_keys; let a = ParaId::from(228); let msg = vec![1, 2, 3]; diff --git a/runtime/parachains/src/util.rs b/runtime/parachains/src/util.rs index 2e0625f42202..e4c538ed2c66 100644 --- a/runtime/parachains/src/util.rs +++ b/runtime/parachains/src/util.rs @@ -17,7 +17,7 @@ //! Utilities that don't belong to any particular module but may draw //! on all modules. -use primitives::v1::{Id as ParaId, PersistedValidationData, ValidatorIndex}; +use primitives::v2::{Id as ParaId, PersistedValidationData, ValidatorIndex}; use sp_std::{collections::btree_set::BTreeSet, vec::Vec}; use crate::{configuration, hrmp, paras}; @@ -103,7 +103,7 @@ mod tests { use sp_std::vec::Vec; use crate::util::{split_active_subset, take_active_subset}; - use primitives::v1::ValidatorIndex; + use primitives::v2::ValidatorIndex; #[test] fn take_active_subset_is_compatible_with_split_active_subset() { diff --git a/runtime/polkadot/constants/src/lib.rs b/runtime/polkadot/constants/src/lib.rs index 37c26c62074f..0d22f8caeb0a 100644 --- a/runtime/polkadot/constants/src/lib.rs +++ b/runtime/polkadot/constants/src/lib.rs @@ -20,7 +20,7 @@ pub use self::currency::DOLLARS; /// Money matters. pub mod currency { - use primitives::v0::Balance; + use primitives::v2::Balance; /// The existential deposit. pub const EXISTENTIAL_DEPOSIT: Balance = 100 * CENTS; @@ -37,7 +37,7 @@ pub mod currency { /// Time and blocks. pub mod time { - use primitives::v0::{BlockNumber, Moment}; + use primitives::v2::{BlockNumber, Moment}; pub const MILLISECS_PER_BLOCK: Moment = 6000; pub const SLOT_DURATION: Moment = MILLISECS_PER_BLOCK; pub const EPOCH_DURATION_IN_SLOTS: BlockNumber = 4 * HOURS; @@ -57,7 +57,7 @@ pub mod fee { use frame_support::weights::{ WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, }; - use primitives::v0::Balance; + use primitives::v2::Balance; use runtime_common::ExtrinsicBaseWeight; use smallvec::smallvec; pub use sp_runtime::Perbill; diff --git a/runtime/polkadot/src/lib.rs b/runtime/polkadot/src/lib.rs index 0933801332ee..1e012b9a2911 100644 --- a/runtime/polkadot/src/lib.rs +++ b/runtime/polkadot/src/lib.rs @@ -32,7 +32,7 @@ use runtime_parachains::{ dmp as parachains_dmp, hrmp as parachains_hrmp, inclusion as parachains_inclusion, initializer as parachains_initializer, origin as parachains_origin, paras as parachains_paras, paras_inherent as parachains_paras_inherent, reward_points as parachains_reward_points, - runtime_api_impl::v1 as parachains_runtime_api_impl, scheduler as parachains_scheduler, + runtime_api_impl::v2 as parachains_runtime_api_impl, scheduler as parachains_scheduler, session_info as parachains_session_info, shared as parachains_shared, ump as parachains_ump, }; @@ -54,15 +54,11 @@ use pallet_mmr_primitives as mmr; use pallet_session::historical as session_historical; use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; -use primitives::{ - v1::{ - AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt, - CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, - InboundHrmpMessage, Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, - ScrapedOnChainVotes, Signature, ValidationCode, ValidationCodeHash, ValidatorId, - ValidatorIndex, - }, - v2::SessionInfo, +use primitives::v2::{ + AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt, + CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, + Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes, + SessionInfo, Signature, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, }; use sp_core::OpaqueMetadata; use sp_runtime::{ @@ -1332,7 +1328,7 @@ impl auctions::Config for Runtime { construct_runtime! { pub enum Runtime where Block = Block, - NodeBlock = primitives::v1::Block, + NodeBlock = primitives::v2::Block, UncheckedExtrinsic = UncheckedExtrinsic { // Basic stuff; balances is uncallable initially. @@ -1809,7 +1805,7 @@ sp_api::impl_runtime_apis! { fn check_validation_outputs( para_id: ParaId, - outputs: primitives::v1::CandidateCommitments, + outputs: primitives::v2::CandidateCommitments, ) -> bool { parachains_runtime_api_impl::check_validation_outputs::(para_id, outputs) } @@ -1862,7 +1858,7 @@ sp_api::impl_runtime_apis! { fn submit_pvf_check_statement( stmt: primitives::v2::PvfCheckStatement, - signature: primitives::v1::ValidatorSignature, + signature: primitives::v2::ValidatorSignature, ) { parachains_runtime_api_impl::submit_pvf_check_statement::(stmt, signature) } diff --git a/runtime/rococo/constants/src/lib.rs b/runtime/rococo/constants/src/lib.rs index bb0bfc4a9747..4f301b8c7726 100644 --- a/runtime/rococo/constants/src/lib.rs +++ b/runtime/rococo/constants/src/lib.rs @@ -18,7 +18,7 @@ /// Money matters. pub mod currency { - use primitives::v0::Balance; + use primitives::v2::Balance; pub const UNITS: Balance = 1_000_000_000_000; pub const DOLLARS: Balance = UNITS; @@ -32,7 +32,7 @@ pub mod currency { /// Time and blocks. pub mod time { - use primitives::v0::{BlockNumber, Moment}; + use primitives::v2::{BlockNumber, Moment}; use runtime_common::prod_or_fast; pub const MILLISECS_PER_BLOCK: Moment = 6000; @@ -56,7 +56,7 @@ pub mod fee { use frame_support::weights::{ WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, }; - use primitives::v0::Balance; + use primitives::v2::Balance; use runtime_common::ExtrinsicBaseWeight; use smallvec::smallvec; pub use sp_runtime::Perbill; diff --git a/runtime/rococo/src/bridge_messages.rs b/runtime/rococo/src/bridge_messages.rs index 32b6aad29979..17a15836db46 100644 --- a/runtime/rococo/src/bridge_messages.rs +++ b/runtime/rococo/src/bridge_messages.rs @@ -99,7 +99,7 @@ pub struct RococoLikeChain { impl ChainWithMessages for RococoLikeChain { type Hash = crate::Hash; type AccountId = crate::AccountId; - type Signer = primitives::v1::AccountPublic; + type Signer = primitives::v2::AccountPublic; type Signature = crate::Signature; type Weight = Weight; type Balance = crate::Balance; @@ -447,10 +447,10 @@ mod tests { u64::MAX, u64::MAX, )), - frame_system::CheckNonce::from(primitives::v1::Nonce::MAX), + frame_system::CheckNonce::from(primitives::v2::Nonce::MAX), frame_system::CheckWeight::new(), pallet_transaction_payment::ChargeTransactionPayment::from( - primitives::v1::Balance::MAX, + primitives::v2::Balance::MAX, ), ); let mut zeroes = TrailingZeroInput::zeroes(); diff --git a/runtime/rococo/src/lib.rs b/runtime/rococo/src/lib.rs index fe3548aec5dc..6adc03e5503b 100644 --- a/runtime/rococo/src/lib.rs +++ b/runtime/rococo/src/lib.rs @@ -34,20 +34,18 @@ use pallet_mmr_primitives as mmr; use pallet_session::historical as session_historical; use pallet_transaction_payment::{CurrencyAdapter, FeeDetails, RuntimeDispatchInfo}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; -use primitives::{ - v1::{ - AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt, - CoreState, GroupRotationInfo, Hash, Id, InboundDownwardMessage, InboundHrmpMessage, Moment, - Nonce, OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes, Signature, - ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature, - }, - v2::{PvfCheckStatement, SessionInfo as SessionInfoData}, +use primitives::v2::{ + AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt, + CoreState, GroupRotationInfo, Hash, Id, InboundDownwardMessage, InboundHrmpMessage, Moment, + Nonce, OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, + SessionInfo as SessionInfoData, Signature, ValidationCode, ValidationCodeHash, ValidatorId, + ValidatorIndex, ValidatorSignature, }; use runtime_common::{ assigned_slots, auctions, crowdloan, impls::ToAuthor, paras_registrar, paras_sudo_wrapper, slots, BlockHashCount, BlockLength, BlockWeights, RocksDbWeight, SlowAdjustingFeeUpdate, }; -use runtime_parachains::{self, runtime_api_impl::v1 as runtime_api_impl}; +use runtime_parachains::{self, runtime_api_impl::v2 as runtime_api_impl}; use scale_info::TypeInfo; use sp_core::{OpaqueMetadata, RuntimeDebug}; use sp_runtime::{ @@ -213,7 +211,7 @@ impl_opaque_keys! { construct_runtime! { pub enum Runtime where Block = Block, - NodeBlock = primitives::v1::Block, + NodeBlock = primitives::v2::Block, UncheckedExtrinsic = UncheckedExtrinsic { System: frame_system, @@ -1218,7 +1216,7 @@ sp_api::impl_runtime_apis! { fn check_validation_outputs( para_id: Id, - outputs: primitives::v1::CandidateCommitments, + outputs: primitives::v2::CandidateCommitments, ) -> bool { runtime_api_impl::check_validation_outputs::(para_id, outputs) } diff --git a/runtime/test-runtime/constants/src/lib.rs b/runtime/test-runtime/constants/src/lib.rs index 331e3ab47cb8..583dbe655114 100644 --- a/runtime/test-runtime/constants/src/lib.rs +++ b/runtime/test-runtime/constants/src/lib.rs @@ -18,7 +18,7 @@ /// Money matters. pub mod currency { - use primitives::v0::Balance; + use primitives::v2::Balance; pub const DOTS: Balance = 1_000_000_000_000; pub const DOLLARS: Balance = DOTS; @@ -28,7 +28,7 @@ pub mod currency { /// Time and blocks. pub mod time { - use primitives::v0::{BlockNumber, Moment}; + use primitives::v2::{BlockNumber, Moment}; // Testnet pub const MILLISECS_PER_BLOCK: Moment = 6000; pub const SLOT_DURATION: Moment = MILLISECS_PER_BLOCK; @@ -49,7 +49,7 @@ pub mod fee { use frame_support::weights::{ WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, }; - use primitives::v0::Balance; + use primitives::v2::Balance; use runtime_common::ExtrinsicBaseWeight; use smallvec::smallvec; pub use sp_runtime::Perbill; diff --git a/runtime/test-runtime/src/lib.rs b/runtime/test-runtime/src/lib.rs index aad95bbe0c06..4883f19afffc 100644 --- a/runtime/test-runtime/src/lib.rs +++ b/runtime/test-runtime/src/lib.rs @@ -28,7 +28,7 @@ use polkadot_runtime_parachains::{ configuration as parachains_configuration, disputes as parachains_disputes, dmp as parachains_dmp, hrmp as parachains_hrmp, inclusion as parachains_inclusion, initializer as parachains_initializer, origin as parachains_origin, paras as parachains_paras, - paras_inherent as parachains_paras_inherent, runtime_api_impl::v1 as runtime_impl, + paras_inherent as parachains_paras_inherent, runtime_api_impl::v2 as runtime_impl, scheduler as parachains_scheduler, session_info as parachains_session_info, shared as parachains_shared, ump as parachains_ump, }; @@ -44,15 +44,12 @@ use pallet_mmr_primitives as mmr; use pallet_session::historical as session_historical; use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo}; use polkadot_runtime_parachains::reward_points::RewardValidatorsWithEraPoints; -use primitives::{ - v1::{ - AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt, - CoreState, GroupRotationInfo, Hash as HashT, Id as ParaId, InboundDownwardMessage, - InboundHrmpMessage, Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, - ScrapedOnChainVotes, Signature, ValidationCode, ValidationCodeHash, ValidatorId, - ValidatorIndex, - }, - v2::SessionInfo as SessionInfoData, +use primitives::v2::{ + AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt, + CoreState, GroupRotationInfo, Hash as HashT, Id as ParaId, InboundDownwardMessage, + InboundHrmpMessage, Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, + ScrapedOnChainVotes, SessionInfo as SessionInfoData, Signature, ValidationCode, + ValidationCodeHash, ValidatorId, ValidatorIndex, }; use runtime_common::{ claims, paras_sudo_wrapper, BlockHashCount, BlockLength, BlockWeights, SlowAdjustingFeeUpdate, @@ -649,7 +646,7 @@ pub mod pallet_test_notifier { construct_runtime! { pub enum Runtime where Block = Block, - NodeBlock = primitives::v1::Block, + NodeBlock = primitives::v2::Block, UncheckedExtrinsic = UncheckedExtrinsic { // Basic stuff; balances is uncallable initially. @@ -833,7 +830,7 @@ sp_api::impl_runtime_apis! { fn check_validation_outputs( para_id: ParaId, - outputs: primitives::v1::CandidateCommitments, + outputs: primitives::v2::CandidateCommitments, ) -> bool { runtime_impl::check_validation_outputs::(para_id, outputs) } @@ -883,7 +880,7 @@ sp_api::impl_runtime_apis! { fn submit_pvf_check_statement( stmt: primitives::v2::PvfCheckStatement, - signature: primitives::v1::ValidatorSignature, + signature: primitives::v2::ValidatorSignature, ) { runtime_impl::submit_pvf_check_statement::(stmt, signature) } diff --git a/runtime/westend/constants/src/lib.rs b/runtime/westend/constants/src/lib.rs index 46ce6d9e4af3..2a43d38829c6 100644 --- a/runtime/westend/constants/src/lib.rs +++ b/runtime/westend/constants/src/lib.rs @@ -18,7 +18,7 @@ /// Money matters. pub mod currency { - use primitives::v0::Balance; + use primitives::v2::Balance; /// The existential deposit. pub const EXISTENTIAL_DEPOSIT: Balance = 1 * CENTS; @@ -35,7 +35,7 @@ pub mod currency { /// Time and blocks. pub mod time { - use primitives::v0::{BlockNumber, Moment}; + use primitives::v2::{BlockNumber, Moment}; use runtime_common::prod_or_fast; pub const MILLISECS_PER_BLOCK: Moment = 6000; @@ -56,7 +56,7 @@ pub mod fee { use frame_support::weights::{ WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, }; - use primitives::v1::Balance; + use primitives::v2::Balance; use runtime_common::ExtrinsicBaseWeight; use smallvec::smallvec; pub use sp_runtime::Perbill; diff --git a/runtime/westend/src/lib.rs b/runtime/westend/src/lib.rs index 0fdad6852d6f..086038c83f45 100644 --- a/runtime/westend/src/lib.rs +++ b/runtime/westend/src/lib.rs @@ -22,15 +22,11 @@ use pallet_transaction_payment::CurrencyAdapter; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; -use primitives::{ - v1::{ - AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt, - CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, - InboundHrmpMessage, Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, - ScrapedOnChainVotes, Signature, ValidationCode, ValidationCodeHash, ValidatorId, - ValidatorIndex, - }, - v2::SessionInfo, +use primitives::v2::{ + AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt, + CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, + Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes, + SessionInfo, Signature, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, }; use runtime_common::{ assigned_slots, auctions, crowdloan, impls::ToAuthor, paras_registrar, paras_sudo_wrapper, @@ -44,7 +40,7 @@ use runtime_parachains::{ inclusion as parachains_inclusion, initializer as parachains_initializer, origin as parachains_origin, paras as parachains_paras, paras_inherent as parachains_paras_inherent, reward_points as parachains_reward_points, - runtime_api_impl::v1 as parachains_runtime_api_impl, scheduler as parachains_scheduler, + runtime_api_impl::v2 as parachains_runtime_api_impl, scheduler as parachains_scheduler, session_info as parachains_session_info, shared as parachains_shared, ump as parachains_ump, }; @@ -970,7 +966,7 @@ impl auctions::Config for Runtime { construct_runtime! { pub enum Runtime where Block = Block, - NodeBlock = primitives::v1::Block, + NodeBlock = primitives::v2::Block, UncheckedExtrinsic = UncheckedExtrinsic { // Basic stuff; balances is uncallable initially. @@ -1243,7 +1239,7 @@ sp_api::impl_runtime_apis! { fn check_validation_outputs( para_id: ParaId, - outputs: primitives::v1::CandidateCommitments, + outputs: primitives::v2::CandidateCommitments, ) -> bool { parachains_runtime_api_impl::check_validation_outputs::(para_id, outputs) } @@ -1296,7 +1292,7 @@ sp_api::impl_runtime_apis! { fn submit_pvf_check_statement( stmt: primitives::v2::PvfCheckStatement, - signature: primitives::v1::ValidatorSignature, + signature: primitives::v2::ValidatorSignature, ) { parachains_runtime_api_impl::submit_pvf_check_statement::(stmt, signature) } diff --git a/statement-table/src/generic.rs b/statement-table/src/generic.rs index db40c88d75c1..d899c54d1d53 100644 --- a/statement-table/src/generic.rs +++ b/statement-table/src/generic.rs @@ -30,7 +30,7 @@ use std::{ hash::Hash, }; -use primitives::v1::{ValidatorSignature, ValidityAttestation as PrimitiveValidityAttestation}; +use primitives::v2::{ValidatorSignature, ValidityAttestation as PrimitiveValidityAttestation}; use parity_scale_codec::{Decode, Encode}; diff --git a/statement-table/src/lib.rs b/statement-table/src/lib.rs index 37aac24d4e71..a3fbbb1fdaaa 100644 --- a/statement-table/src/lib.rs +++ b/statement-table/src/lib.rs @@ -18,10 +18,10 @@ pub mod generic; pub use generic::{Context, Table}; -/// Concrete instantiations suitable for v1 primitives. -pub mod v1 { +/// Concrete instantiations suitable for v2 primitives. +pub mod v2 { use crate::generic; - use primitives::v1::{ + use primitives::v2::{ CandidateHash, CommittedCandidateReceipt, CompactStatement as PrimitiveStatement, Id, ValidatorIndex, ValidatorSignature, };