Unverified Commit 390e58de authored by André Silva's avatar André Silva Committed by GitHub
Browse files

create newtype for ValidationCodeHash (#3212)

* create newtype for ValidationCodeHash

* pvf: fix tests compilation

* primitives: fix test compilation
parent c8b3f113
Pipeline #141946 passed with stages
in 33 minutes and 36 seconds
......@@ -18,7 +18,7 @@ use always_assert::always;
use async_std::{
path::{Path, PathBuf},
};
use polkadot_core_primitives::Hash;
use polkadot_parachain::primitives::ValidationCodeHash;
use std::{
collections::HashMap,
time::{Duration, SystemTime},
......@@ -56,14 +56,14 @@ impl Artifact {
/// multiple engine implementations the artifact ID should include the engine type as well.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ArtifactId {
code_hash: Hash,
code_hash: ValidationCodeHash,
}
impl ArtifactId {
const PREFIX: &'static str = "wasmtime_";
/// Creates a new artifact ID with the given hash.
pub fn new(code_hash: Hash) -> Self {
pub fn new(code_hash: ValidationCodeHash) -> Self {
Self { code_hash }
}
......@@ -71,9 +71,10 @@ impl ArtifactId {
#[cfg(test)]
pub fn from_file_name(file_name: &str) -> Option<Self> {
use std::str::FromStr as _;
use polkadot_core_primitives::Hash;
let file_name = file_name.strip_prefix(Self::PREFIX)?;
let code_hash = Hash::from_str(file_name).ok()?;
let code_hash = Hash::from_str(file_name).ok()?.into();
Some(Self { code_hash })
}
......@@ -212,7 +213,7 @@ mod tests {
#[test]
fn path() {
let path = Path::new("/test");
let hash = H256::from_str("1234567890123456789012345678901234567890123456789012345678901234").unwrap();
let hash = H256::from_str("1234567890123456789012345678901234567890123456789012345678901234").unwrap().into();
assert_eq!(
ArtifactId::new(hash).path(path).to_str(),
......
......@@ -15,7 +15,7 @@
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use crate::artifacts::ArtifactId;
use polkadot_core_primitives::Hash;
use polkadot_parachain::primitives::ValidationCodeHash;
use sp_core::blake2_256;
use std::{fmt, sync::Arc};
......@@ -25,7 +25,7 @@ use std::{fmt, sync::Arc};
#[derive(Clone)]
pub struct Pvf {
pub(crate) code: Arc<Vec<u8>>,
pub(crate) code_hash: Hash,
pub(crate) code_hash: ValidationCodeHash,
}
impl fmt::Debug for Pvf {
......
......@@ -144,7 +144,7 @@ sp_api::mock_impl_runtime_apis! {
fn validation_code_by_hash(
&self,
hash: Hash,
hash: ValidationCodeHash,
) -> Option<ValidationCode> {
self.validation_code_by_hash.get(&hash).map(|c| c.clone())
}
......
......@@ -53,24 +53,66 @@ impl HeadData {
/// Parachain validation code.
#[derive(Default, PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, derive_more::From)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash, MallocSizeOf))]
pub struct ValidationCode(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
pub struct ValidationCode(#[cfg_attr(feature = "std", serde(with = "bytes"))] pub Vec<u8>);
impl ValidationCode {
/// Get the blake2-256 hash of the validation code bytes.
pub fn hash(&self) -> Hash {
sp_runtime::traits::BlakeTwo256::hash(&self.0[..])
pub fn hash(&self) -> ValidationCodeHash {
ValidationCodeHash(sp_runtime::traits::BlakeTwo256::hash(&self.0[..]))
}
}
/// Unit type wrapper around [`Hash`] that represents a validation code hash.
///
/// This type is produced by [`ValidationCode::hash`].
///
/// This type makes it easy to enforce that a hash is a validation code hash on the type level.
#[derive(Clone, Copy, Encode, Decode, Default, Hash, Eq, PartialEq, PartialOrd, Ord)]
#[cfg_attr(feature = "std", derive(MallocSizeOf))]
pub struct ValidationCodeHash(Hash);
impl sp_std::fmt::Display for ValidationCodeHash {
fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result {
self.0.fmt(f)
}
}
impl sp_std::fmt::Debug for ValidationCodeHash {
fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result {
write!(f, "{:?}", self.0)
}
}
impl AsRef<[u8]> for ValidationCodeHash {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl From<Hash> for ValidationCodeHash {
fn from(hash: Hash) -> ValidationCodeHash {
ValidationCodeHash(hash)
}
}
/// A hash of the parachain validation code.
pub type ValidationCodeHash = Hash;
impl From<[u8; 32]> for ValidationCodeHash {
fn from(hash: [u8; 32]) -> ValidationCodeHash {
ValidationCodeHash(hash.into())
}
}
impl sp_std::fmt::LowerHex for ValidationCodeHash {
fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result {
sp_std::fmt::LowerHex::fmt(&self.0, f)
}
}
/// Parachain block data.
///
/// Contains everything required to validate para-block, may contain block and witness data.
#[derive(PartialEq, Eq, Clone, Encode, Decode, derive_more::From)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug, MallocSizeOf))]
pub struct BlockData(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
pub struct BlockData(#[cfg_attr(feature = "std", serde(with = "bytes"))] pub Vec<u8>);
/// Unique identifier of a parachain.
#[derive(
......
......@@ -228,7 +228,7 @@ pub fn collator_signature_payload<H: AsRef<[u8]>>(
para_id: &Id,
persisted_validation_data_hash: &Hash,
pov_hash: &Hash,
validation_code_hash: &Hash,
validation_code_hash: &ValidationCodeHash,
) -> [u8; 132] {
// 32-byte hash length is protected in a test below.
let mut payload = [0u8; 132];
......@@ -247,10 +247,10 @@ fn check_collator_signature<H: AsRef<[u8]>>(
para_id: &Id,
persisted_validation_data_hash: &Hash,
pov_hash: &Hash,
validation_code_hash: &Hash,
validation_code_hash: &ValidationCodeHash,
collator: &CollatorId,
signature: &CollatorSignature,
) -> Result<(),()> {
) -> Result<(), ()> {
let payload = collator_signature_payload(
relay_parent,
para_id,
......@@ -290,7 +290,7 @@ pub struct CandidateDescriptor<H = Hash> {
/// 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: Hash,
pub validation_code_hash: ValidationCodeHash,
}
impl<H: AsRef<[u8]>> CandidateDescriptor<H> {
......@@ -931,7 +931,7 @@ sp_api::decl_runtime_apis! {
/// Get the validation code from its hash.
#[skip_initialize_block]
fn validation_code_by_hash(hash: Hash) -> Option<ValidationCode>;
fn validation_code_by_hash(hash: ValidationCodeHash) -> Option<ValidationCode>;
}
}
......@@ -1022,10 +1022,10 @@ pub const POLKADOT_ENGINE_ID: runtime_primitives::ConsensusEngineId = *b"POL1";
pub enum ConsensusLog {
/// A parachain or parathread upgraded its code.
#[codec(index = 1)]
ParaUpgradeCode(Id, Hash),
ParaUpgradeCode(Id, ValidationCodeHash),
/// A parachain or parathread scheduled a code upgrade.
#[codec(index = 2)]
ParaScheduleUpgradeCode(Id, Hash, BlockNumber),
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)]
......@@ -1187,7 +1187,7 @@ mod tests {
&5u32.into(),
&Hash::repeat_byte(2),
&Hash::repeat_byte(3),
&Hash::repeat_byte(4),
&Hash::repeat_byte(4).into(),
);
}
}
......@@ -9,5 +9,5 @@ fn validation_code(at: Block, ParaId, OccupiedCoreAssumption) -> Option<Validati
Fetch the validation code (past, present or future) by its hash.
```rust
fn validation_code_by_hash(at: Block, Hash) -> Option<ValidationCode>;
fn validation_code_by_hash(at: Block, ValidationCodeHash) -> Option<ValidationCode>;
```
......@@ -117,9 +117,9 @@ ParaLifecycle: map ParaId => Option<ParaLifecycle>,
/// The head-data of every registered para.
Heads: map ParaId => Option<HeadData>;
/// The validation code hash of every live para.
CurrentCodeHash: map ParaId => Option<Hash>;
CurrentCodeHash: map ParaId => Option<ValidationCodeHash>;
/// Actual past code hash, indicated by the para id as well as the block number at which it became outdated.
PastCodeHash: map (ParaId, BlockNumber) => Option<Hash>;
PastCodeHash: map (ParaId, BlockNumber) => Option<ValidationCodeHash>;
/// Past code of parachains. The parachains themselves may not be registered anymore,
/// but we also keep their code on-chain for the same amount of time as outdated code
/// to keep it available for secondary checkers.
......@@ -136,15 +136,15 @@ PastCodePruning: Vec<(ParaId, BlockNumber)>;
/// in the context of a relay chain block with a number >= `expected_at`.
FutureCodeUpgrades: map ParaId => Option<BlockNumber>;
/// The actual future code of a para.
FutureCodeHash: map ParaId => Option<Hash>;
FutureCodeHash: map ParaId => Option<ValidationCodeHash>;
/// The actions to perform during the start of a specific session index.
ActionsQueue: map SessionIndex => Vec<ParaId>;
/// Upcoming paras instantiation arguments.
UpcomingParasGenesis: map ParaId => Option<ParaGenesisArgs>;
/// The number of references on the validation code in `CodeByHash` storage.
CodeByHashRefs: map Hash => u32;
CodeByHashRefs: map ValidationCodeHash => u32;
/// Validation code stored by its hash.
CodeByHash: map Hash => Option<ValidationCode>
CodeByHash: map ValidationCodeHash => Option<ValidationCode>
```
## Session Change
......
......@@ -87,6 +87,8 @@ struct CandidateDescriptor {
signature: CollatorSignature,
/// Hash of the para header that is being generated by this candidate.
para_head: Hash,
/// The blake2-256 hash of the validation code bytes.
validation_code_hash: ValidationCodeHash,
}
```
......
......@@ -28,8 +28,8 @@ use parity_scale_codec::{Encode, Decode};
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash, Id as ParaId, Moment, Nonce, OccupiedCoreAssumption,
PersistedValidationData, Signature, ValidationCode, ValidatorId, ValidatorIndex,
InboundDownwardMessage, InboundHrmpMessage, SessionInfo,
PersistedValidationData, Signature, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex, InboundDownwardMessage, InboundHrmpMessage, SessionInfo,
};
use runtime_common::{
claims, paras_registrar, xcm_sender, slots, auctions, crowdloan,
......@@ -1654,7 +1654,7 @@ sp_api::impl_runtime_apis! {
parachains_runtime_api_impl::inbound_hrmp_channels_contents::<Runtime>(recipient)
}
fn validation_code_by_hash(hash: Hash) -> Option<ValidationCode> {
fn validation_code_by_hash(hash: ValidationCodeHash) -> Option<ValidationCode> {
parachains_runtime_api_impl::validation_code_by_hash::<Runtime>(hash)
}
}
......
......@@ -28,7 +28,7 @@ use sp_std::result;
#[cfg(feature = "std")]
use sp_std::marker::PhantomData;
use primitives::v1::{
Id as ParaId, ValidationCode, HeadData, SessionIndex, Hash, ConsensusLog,
Id as ParaId, ValidationCode, ValidationCodeHash, HeadData, SessionIndex, ConsensusLog,
};
use sp_runtime::{traits::One, DispatchResult, SaturatedConversion};
use frame_system::ensure_root;
......@@ -290,12 +290,12 @@ decl_storage! {
/// The validation code hash of every live para.
///
/// Corresponding code can be retrieved with [`CodeByHash`].
CurrentCodeHash: map hasher(twox_64_concat) ParaId => Option<Hash>;
CurrentCodeHash: map hasher(twox_64_concat) ParaId => Option<ValidationCodeHash>;
/// Actual past code hash, indicated by the para id as well as the block number at which it
/// became outdated.
///
/// Corresponding code can be retrieved with [`CodeByHash`].
PastCodeHash: map hasher(twox_64_concat) (ParaId, T::BlockNumber) => Option<Hash>;
PastCodeHash: map hasher(twox_64_concat) (ParaId, T::BlockNumber) => Option<ValidationCodeHash>;
/// Past code of parachains. The parachains themselves may not be registered anymore,
/// but we also keep their code on-chain for the same amount of time as outdated code
/// to keep it available for secondary checkers.
......@@ -315,18 +315,18 @@ decl_storage! {
/// The actual future code hash of a para.
///
/// Corresponding code can be retrieved with [`CodeByHash`].
FutureCodeHash: map hasher(twox_64_concat) ParaId => Option<Hash>;
FutureCodeHash: map hasher(twox_64_concat) ParaId => Option<ValidationCodeHash>;
/// The actions to perform during the start of a specific session index.
ActionsQueue get(fn actions_queue): map hasher(twox_64_concat) SessionIndex => Vec<ParaId>;
/// Upcoming paras instantiation arguments.
UpcomingParasGenesis: map hasher(twox_64_concat) ParaId => Option<ParaGenesisArgs>;
/// The number of reference on the validation code in [`CodeByHash`] storage.
CodeByHashRefs: map hasher(identity) Hash => u32;
CodeByHashRefs: map hasher(identity) ValidationCodeHash => u32;
/// Validation code stored by its hash.
///
/// This storage is consistent with [`FutureCodeHash`], [`CurrentCodeHash`] and
/// [`PastCodeHash`].
CodeByHash get(fn code_by_hash): map hasher(identity) Hash => Option<ValidationCode>;
CodeByHash get(fn code_by_hash): map hasher(identity) ValidationCodeHash => Option<ValidationCode>;
}
add_extra_genesis {
config(paras): Vec<(ParaId, ParaGenesisArgs)>;
......@@ -577,9 +577,8 @@ impl<T: Config> Module<T> {
id: ParaId,
at: T::BlockNumber,
now: T::BlockNumber,
old_code_hash: Hash,
old_code_hash: ValidationCodeHash,
) -> Weight {
<Self as Store>::PastCodeMeta::mutate(&id, |past_meta| {
past_meta.note_replacement(at, now);
});
......@@ -836,7 +835,7 @@ impl<T: Config> Module<T> {
id: ParaId,
at: T::BlockNumber,
assume_intermediate: Option<T::BlockNumber>,
) -> Option<Hash> {
) -> Option<ValidationCodeHash> {
if assume_intermediate.as_ref().map_or(false, |i| &at <= i) {
return None;
}
......@@ -916,7 +915,7 @@ impl<T: Config> Module<T> {
/// Store the validation code if not already stored, and increase the number of reference.
///
/// Returns the number of storage reads and number of storage writes.
fn increase_code_ref(code_hash: &Hash, code: &ValidationCode) -> (u64, u64) {
fn increase_code_ref(code_hash: &ValidationCodeHash, code: &ValidationCode) -> (u64, u64) {
let reads = 1;
let mut writes = 1;
<Self as Store>::CodeByHashRefs::mutate(code_hash, |refs| {
......@@ -931,7 +930,7 @@ impl<T: Config> Module<T> {
/// Decrease the number of reference ofthe validation code and remove it from storage if zero
/// is reached.
fn decrease_code_ref(code_hash: &Hash) {
fn decrease_code_ref(code_hash: &ValidationCodeHash) {
let refs = <Self as Store>::CodeByHashRefs::get(code_hash);
if refs <= 1 {
<Self as Store>::CodeByHash::remove(code_hash);
......
......@@ -21,11 +21,11 @@ use sp_std::prelude::*;
use sp_std::collections::btree_map::BTreeMap;
use sp_runtime::traits::One;
use primitives::v1::{
ValidatorId, ValidatorIndex, GroupRotationInfo, CoreState,
Id as ParaId, OccupiedCoreAssumption, SessionIndex, ValidationCode,
CommittedCandidateReceipt, ScheduledCore, OccupiedCore, CoreOccupied, CoreIndex,
GroupIndex, CandidateEvent, PersistedValidationData, SessionInfo,
InboundDownwardMessage, InboundHrmpMessage, AuthorityDiscoveryId, Hash
AuthorityDiscoveryId, CandidateEvent, CommittedCandidateReceipt, CoreIndex, CoreOccupied,
CoreState, GroupIndex, GroupRotationInfo, Id as ParaId, InboundDownwardMessage,
InboundHrmpMessage, OccupiedCore, OccupiedCoreAssumption, PersistedValidationData,
ScheduledCore, SessionIndex, SessionInfo, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex,
};
use crate::{initializer, inclusion, scheduler, configuration, paras, session_info, dmp, hrmp, shared};
......@@ -325,7 +325,7 @@ pub fn inbound_hrmp_channels_contents<T: hrmp::Config>(
/// Implementation for the `validation_code_by_hash` function of the runtime API.
pub fn validation_code_by_hash<T: paras::Config>(
hash: Hash,
hash: ValidationCodeHash,
) -> Option<ValidationCode> {
<paras::Module<T>>::code_by_hash(hash)
}
......@@ -36,8 +36,8 @@ use parity_scale_codec::{Encode, Decode};
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash, Id, Moment, Nonce, OccupiedCoreAssumption,
PersistedValidationData, Signature, ValidationCode, ValidatorId, ValidatorIndex,
InboundDownwardMessage, InboundHrmpMessage, SessionInfo,
PersistedValidationData, Signature, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex, InboundDownwardMessage, InboundHrmpMessage, SessionInfo,
};
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys, ApplyExtrinsicResult,
......@@ -1207,7 +1207,7 @@ sp_api::impl_runtime_apis! {
BTreeMap::new()
}
fn validation_code_by_hash(_hash: Hash) -> Option<ValidationCode> {
fn validation_code_by_hash(_hash: ValidationCodeHash) -> Option<ValidationCode> {
None
}
}
......
......@@ -26,7 +26,7 @@ use sp_std::collections::btree_map::BTreeMap;
use parity_scale_codec::{Encode, Decode};
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, Hash, Nonce, Signature, Moment,
GroupRotationInfo, CoreState, Id, ValidationCode, CandidateEvent,
GroupRotationInfo, CoreState, Id, ValidationCode, ValidationCodeHash, CandidateEvent,
ValidatorId, ValidatorIndex, CommittedCandidateReceipt, OccupiedCoreAssumption,
PersistedValidationData, InboundDownwardMessage, InboundHrmpMessage,
SessionInfo as SessionInfoData,
......@@ -1136,7 +1136,7 @@ sp_api::impl_runtime_apis! {
runtime_api_impl::inbound_hrmp_channels_contents::<Runtime>(recipient)
}
fn validation_code_by_hash(hash: Hash) -> Option<ValidationCode> {
fn validation_code_by_hash(hash: ValidationCodeHash) -> Option<ValidationCode> {
runtime_api_impl::validation_code_by_hash::<Runtime>(hash)
}
}
......
......@@ -41,7 +41,7 @@ use polkadot_runtime_parachains::runtime_api_impl::v1 as runtime_impl;
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash as HashT, Id as ParaId, Moment, Nonce, OccupiedCoreAssumption,
PersistedValidationData, Signature, ValidationCode, ValidatorId, ValidatorIndex,
PersistedValidationData, Signature, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
InboundDownwardMessage, InboundHrmpMessage, SessionInfo as SessionInfoData,
};
use runtime_common::{
......@@ -695,7 +695,7 @@ sp_api::impl_runtime_apis! {
runtime_impl::inbound_hrmp_channels_contents::<Runtime>(recipient)
}
fn validation_code_by_hash(hash: Hash) -> Option<ValidationCode> {
fn validation_code_by_hash(hash: ValidationCodeHash) -> Option<ValidationCode> {
runtime_impl::validation_code_by_hash::<Runtime>(hash)
}
}
......
......@@ -27,8 +27,8 @@ use parity_scale_codec::{Encode, Decode};
use primitives::v1::{
AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
CoreState, GroupRotationInfo, Hash, Id as ParaId, Moment, Nonce, OccupiedCoreAssumption,
PersistedValidationData, Signature, ValidationCode, ValidatorId, ValidatorIndex,
InboundDownwardMessage, InboundHrmpMessage, SessionInfo,
PersistedValidationData, Signature, ValidationCode, ValidationCodeHash, ValidatorId,
ValidatorIndex, InboundDownwardMessage, InboundHrmpMessage, SessionInfo,
};
use runtime_common::{
paras_sudo_wrapper, paras_registrar, xcm_sender, slots, crowdloan, auctions,
......@@ -1252,7 +1252,7 @@ sp_api::impl_runtime_apis! {
parachains_runtime_api_impl::inbound_hrmp_channels_contents::<Runtime>(recipient)
}
fn validation_code_by_hash(hash: Hash) -> Option<ValidationCode> {
fn validation_code_by_hash(hash: ValidationCodeHash) -> Option<ValidationCode> {
parachains_runtime_api_impl::validation_code_by_hash::<Runtime>(hash)
}
}
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment