Associated type Hasher for QueryPreimage, StorePreimage and Bounded (#1720)

I hope it's enough to fix #1701 
the only solution I found to make it happen is to put an associated type
to the `Bounded` enum as well.
@liamaharon @kianenigma @bkchr 

Polkadot address: 12poSUQPtcF1HUPQGY3zZu2P8emuW9YnsPduA4XG3oCEfJVp

---------

Signed-off-by: muraca <mmuraca247@gmail.com>
Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
This commit is contained in:
Matteo Muraca
2023-09-27 14:46:14 +02:00
committed by GitHub
parent 7cbe0c76ef
commit 8b061a5c5d
20 changed files with 189 additions and 159 deletions
+1 -1
View File
@@ -107,7 +107,7 @@ mod voting;
pub use voting::{ClassCountOf, PollStatus, Polling, VoteTally};
mod preimages;
pub use preimages::{Bounded, BoundedInline, FetchResult, Hash, QueryPreimage, StorePreimage};
pub use preimages::{Bounded, BoundedInline, FetchResult, QueryPreimage, StorePreimage};
mod messages;
pub use messages::{
+60 -50
View File
@@ -15,16 +15,17 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//! Stuff for dealing with 32-byte hashed preimages.
//! Stuff for dealing with hashed preimages.
use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};
use scale_info::TypeInfo;
use sp_core::{RuntimeDebug, H256};
use sp_io::hashing::blake2_256;
use sp_runtime::{traits::ConstU32, DispatchError};
use sp_core::RuntimeDebug;
use sp_runtime::{
traits::{ConstU32, Hash},
DispatchError,
};
use sp_std::borrow::Cow;
pub type Hash = H256;
pub type BoundedInline = crate::BoundedVec<u8, ConstU32<128>>;
/// The maximum we expect a single legacy hash lookup to be.
@@ -32,29 +33,29 @@ const MAX_LEGACY_LEN: u32 = 1_000_000;
#[derive(Encode, Decode, MaxEncodedLen, Clone, Eq, PartialEq, TypeInfo, RuntimeDebug)]
#[codec(mel_bound())]
pub enum Bounded<T> {
/// A Blake2 256 hash with no preimage length. We
/// do not support creation of this except for transitioning from legacy state.
/// In the future we will make this a pure `Dummy` item storing only the final `dummy` field.
Legacy { hash: Hash, dummy: sp_std::marker::PhantomData<T> },
pub enum Bounded<T, H: Hash> {
/// A hash with no preimage length. We do not support creation of this except
/// for transitioning from legacy state. In the future we will make this a pure
/// `Dummy` item storing only the final `dummy` field.
Legacy { hash: H::Output, dummy: sp_std::marker::PhantomData<T> },
/// A an bounded `Call`. Its encoding must be at most 128 bytes.
Inline(BoundedInline),
/// A Blake2-256 hash of the call together with an upper limit for its size.
Lookup { hash: Hash, len: u32 },
/// A hash of the call together with an upper limit for its size.`
Lookup { hash: H::Output, len: u32 },
}
impl<T> Bounded<T> {
impl<T, H: Hash> Bounded<T, H> {
/// Casts the wrapped type into something that encodes alike.
///
/// # Examples
/// ```
/// use frame_support::traits::Bounded;
/// use frame_support::{traits::Bounded, sp_runtime::traits::BlakeTwo256};
///
/// // Transmute from `String` to `&str`.
/// let x: Bounded<String> = Bounded::Inline(Default::default());
/// let _: Bounded<&str> = x.transmute();
/// let x: Bounded<String, BlakeTwo256> = Bounded::Inline(Default::default());
/// let _: Bounded<&str, BlakeTwo256> = x.transmute();
/// ```
pub fn transmute<S: Encode>(self) -> Bounded<S>
pub fn transmute<S: Encode>(self) -> Bounded<S, H>
where
T: Encode + EncodeLike<S>,
{
@@ -69,18 +70,18 @@ impl<T> Bounded<T> {
/// Returns the hash of the preimage.
///
/// The hash is re-calculated every time if the preimage is inlined.
pub fn hash(&self) -> Hash {
pub fn hash(&self) -> H::Output {
use Bounded::*;
match self {
Lookup { hash, .. } | Legacy { hash, .. } => *hash,
Inline(x) => blake2_256(x.as_ref()).into(),
Inline(x) => <H as Hash>::hash(x.as_ref()),
}
}
/// Returns the hash to lookup the preimage.
///
/// If this is a `Bounded::Inline`, `None` is returned as no lookup is required.
pub fn lookup_hash(&self) -> Option<Hash> {
pub fn lookup_hash(&self) -> Option<H::Output> {
use Bounded::*;
match self {
Lookup { hash, .. } | Legacy { hash, .. } => Some(*hash),
@@ -115,13 +116,13 @@ impl<T> Bounded<T> {
}
/// Constructs a `Lookup` bounded item.
pub fn unrequested(hash: Hash, len: u32) -> Self {
pub fn unrequested(hash: H::Output, len: u32) -> Self {
Self::Lookup { hash, len }
}
/// Constructs a `Legacy` bounded item.
#[deprecated = "This API is only for transitioning to Scheduler v3 API"]
pub fn from_legacy_hash(hash: impl Into<Hash>) -> Self {
pub fn from_legacy_hash(hash: impl Into<H::Output>) -> Self {
Self::Legacy { hash: hash.into(), dummy: sp_std::marker::PhantomData }
}
}
@@ -130,24 +131,27 @@ pub type FetchResult = Result<Cow<'static, [u8]>, DispatchError>;
/// A interface for looking up preimages from their hash on chain.
pub trait QueryPreimage {
/// The hasher used in the runtime.
type H: Hash;
/// Returns whether a preimage exists for a given hash and if so its length.
fn len(hash: &Hash) -> Option<u32>;
fn len(hash: &<Self::H as sp_core::Hasher>::Out) -> Option<u32>;
/// Returns the preimage for a given hash. If given, `len` must be the size of the preimage.
fn fetch(hash: &Hash, len: Option<u32>) -> FetchResult;
fn fetch(hash: &<Self::H as sp_core::Hasher>::Out, len: Option<u32>) -> FetchResult;
/// Returns whether a preimage request exists for a given hash.
fn is_requested(hash: &Hash) -> bool;
fn is_requested(hash: &<Self::H as sp_core::Hasher>::Out) -> bool;
/// Request that someone report a preimage. Providers use this to optimise the economics for
/// preimage reporting.
fn request(hash: &Hash);
fn request(hash: &<Self::H as sp_core::Hasher>::Out);
/// Cancel a previous preimage request.
fn unrequest(hash: &Hash);
fn unrequest(hash: &<Self::H as sp_core::Hasher>::Out);
/// Request that the data required for decoding the given `bounded` value is made available.
fn hold<T>(bounded: &Bounded<T>) {
fn hold<T>(bounded: &Bounded<T, Self::H>) {
use Bounded::*;
match bounded {
Inline(..) => {},
@@ -157,7 +161,7 @@ pub trait QueryPreimage {
/// No longer request that the data required for decoding the given `bounded` value is made
/// available.
fn drop<T>(bounded: &Bounded<T>) {
fn drop<T>(bounded: &Bounded<T, Self::H>) {
use Bounded::*;
match bounded {
Inline(..) => {},
@@ -167,7 +171,7 @@ pub trait QueryPreimage {
/// Check to see if all data required for the given `bounded` value is available for its
/// decoding.
fn have<T>(bounded: &Bounded<T>) -> bool {
fn have<T>(bounded: &Bounded<T, Self::H>) -> bool {
use Bounded::*;
match bounded {
Inline(..) => true,
@@ -180,7 +184,7 @@ pub trait QueryPreimage {
/// It also directly requests the given `hash` using [`Self::request`].
///
/// This may not be `peek`-able or `realize`-able.
fn pick<T>(hash: Hash, len: u32) -> Bounded<T> {
fn pick<T>(hash: <Self::H as sp_core::Hasher>::Out, len: u32) -> Bounded<T, Self::H> {
Self::request(&hash);
Bounded::Lookup { hash, len }
}
@@ -190,7 +194,7 @@ pub trait QueryPreimage {
///
/// NOTE: This does not remove any data needed for realization. If you will no longer use the
/// `bounded`, call `realize` instead or call `drop` afterwards.
fn peek<T: Decode>(bounded: &Bounded<T>) -> Result<(T, Option<u32>), DispatchError> {
fn peek<T: Decode>(bounded: &Bounded<T, Self::H>) -> Result<(T, Option<u32>), DispatchError> {
use Bounded::*;
match bounded {
Inline(data) => T::decode(&mut &data[..]).ok().map(|x| (x, None)),
@@ -209,7 +213,9 @@ pub trait QueryPreimage {
/// Convert the given `bounded` value back into its original instance. If successful,
/// `drop` any data backing it. This will not break the realisability of independently
/// created instances of `Bounded` which happen to have identical data.
fn realize<T: Decode>(bounded: &Bounded<T>) -> Result<(T, Option<u32>), DispatchError> {
fn realize<T: Decode>(
bounded: &Bounded<T, Self::H>,
) -> Result<(T, Option<u32>), DispatchError> {
let r = Self::peek(bounded)?;
Self::drop(bounded);
Ok(r)
@@ -230,11 +236,11 @@ pub trait StorePreimage: QueryPreimage {
/// Request and attempt to store the bytes of a preimage on chain.
///
/// May return `DispatchError::Exhausted` if the preimage is just too big.
fn note(bytes: Cow<[u8]>) -> Result<Hash, DispatchError>;
fn note(bytes: Cow<[u8]>) -> Result<<Self::H as sp_core::Hasher>::Out, DispatchError>;
/// Attempt to clear a previously noted preimage. Exactly the same as `unrequest` but is
/// provided for symmetry.
fn unnote(hash: &Hash) {
fn unnote(hash: &<Self::H as sp_core::Hasher>::Out) {
Self::unrequest(hash)
}
@@ -244,7 +250,7 @@ pub trait StorePreimage: QueryPreimage {
///
/// NOTE: Once this API is used, you should use either `drop` or `realize`.
/// The value is also noted using [`Self::note`].
fn bound<T: Encode>(t: T) -> Result<Bounded<T>, DispatchError> {
fn bound<T: Encode>(t: T) -> Result<Bounded<T, Self::H>, DispatchError> {
let data = t.encode();
let len = data.len() as u32;
Ok(match BoundedInline::try_from(data) {
@@ -255,22 +261,24 @@ pub trait StorePreimage: QueryPreimage {
}
impl QueryPreimage for () {
fn len(_: &Hash) -> Option<u32> {
type H = sp_runtime::traits::BlakeTwo256;
fn len(_: &sp_core::H256) -> Option<u32> {
None
}
fn fetch(_: &Hash, _: Option<u32>) -> FetchResult {
fn fetch(_: &sp_core::H256, _: Option<u32>) -> FetchResult {
Err(DispatchError::Unavailable)
}
fn is_requested(_: &Hash) -> bool {
fn is_requested(_: &sp_core::H256) -> bool {
false
}
fn request(_: &Hash) {}
fn unrequest(_: &Hash) {}
fn request(_: &sp_core::H256) {}
fn unrequest(_: &sp_core::H256) {}
}
impl StorePreimage for () {
const MAX_LENGTH: usize = 0;
fn note(_: Cow<[u8]>) -> Result<Hash, DispatchError> {
fn note(_: Cow<[u8]>) -> Result<sp_core::H256, DispatchError> {
Err(DispatchError::Exhausted)
}
}
@@ -279,22 +287,22 @@ impl StorePreimage for () {
mod tests {
use super::*;
use crate::BoundedVec;
use sp_runtime::bounded_vec;
use sp_runtime::{bounded_vec, traits::BlakeTwo256};
#[test]
fn bounded_size_is_correct() {
assert_eq!(<Bounded<Vec<u8>> as MaxEncodedLen>::max_encoded_len(), 131);
assert_eq!(<Bounded<Vec<u8>, BlakeTwo256> as MaxEncodedLen>::max_encoded_len(), 131);
}
#[test]
fn bounded_basic_works() {
let data: BoundedVec<u8, _> = bounded_vec![b'a', b'b', b'c'];
let len = data.len() as u32;
let hash = blake2_256(&data).into();
let hash = BlakeTwo256::hash(&data).into();
// Inline works
{
let bound: Bounded<Vec<u8>> = Bounded::Inline(data.clone());
let bound: Bounded<Vec<u8>, BlakeTwo256> = Bounded::Inline(data.clone());
assert_eq!(bound.hash(), hash);
assert_eq!(bound.len(), Some(len));
assert!(!bound.lookup_needed());
@@ -302,7 +310,8 @@ mod tests {
}
// Legacy works
{
let bound: Bounded<Vec<u8>> = Bounded::Legacy { hash, dummy: Default::default() };
let bound: Bounded<Vec<u8>, BlakeTwo256> =
Bounded::Legacy { hash, dummy: Default::default() };
assert_eq!(bound.hash(), hash);
assert_eq!(bound.len(), None);
assert!(bound.lookup_needed());
@@ -310,7 +319,8 @@ mod tests {
}
// Lookup works
{
let bound: Bounded<Vec<u8>> = Bounded::Lookup { hash, len: data.len() as u32 };
let bound: Bounded<Vec<u8>, BlakeTwo256> =
Bounded::Lookup { hash, len: data.len() as u32 };
assert_eq!(bound.hash(), hash);
assert_eq!(bound.len(), Some(len));
assert!(bound.lookup_needed());
@@ -323,8 +333,8 @@ mod tests {
let data: BoundedVec<u8, _> = bounded_vec![b'a', b'b', b'c'];
// Transmute a `String` into a `&str`.
let x: Bounded<String> = Bounded::Inline(data.clone());
let y: Bounded<&str> = x.transmute();
let x: Bounded<String, BlakeTwo256> = Bounded::Inline(data.clone());
let y: Bounded<&str, BlakeTwo256> = x.transmute();
assert_eq!(y, Bounded::Inline(data));
}
}
@@ -387,6 +387,8 @@ pub mod v3 {
pub trait Anon<BlockNumber, Call, Origin> {
/// An address which can be used for removing a scheduled task.
type Address: Codec + MaxEncodedLen + Clone + Eq + EncodeLike + Debug + TypeInfo;
/// The hasher used in the runtime.
type Hasher: sp_runtime::traits::Hash;
/// Schedule a dispatch to happen at the beginning of some block in the future.
///
@@ -396,7 +398,7 @@ pub mod v3 {
maybe_periodic: Option<Period<BlockNumber>>,
priority: Priority,
origin: Origin,
call: Bounded<Call>,
call: Bounded<Call, Self::Hasher>,
) -> Result<Self::Address, DispatchError>;
/// Cancel a scheduled task. If periodic, then it will cancel all further instances of that,
@@ -434,6 +436,8 @@ pub mod v3 {
pub trait Named<BlockNumber, Call, Origin> {
/// An address which can be used for removing a scheduled task.
type Address: Codec + MaxEncodedLen + Clone + Eq + EncodeLike + sp_std::fmt::Debug;
/// The hasher used in the runtime.
type Hasher: sp_runtime::traits::Hash;
/// Schedule a dispatch to happen at the beginning of some block in the future.
///
@@ -446,7 +450,7 @@ pub mod v3 {
maybe_periodic: Option<Period<BlockNumber>>,
priority: Priority,
origin: Origin,
call: Bounded<Call>,
call: Bounded<Call, Self::Hasher>,
) -> Result<Self::Address, DispatchError>;
/// Cancel a scheduled, named task. If periodic, then it will cancel all further instances