mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-09 20:11:09 +00:00
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:
@@ -25,7 +25,6 @@ use frame_support::{
|
||||
traits::{Currency, EnsureOrigin, Get, OnInitialize, UnfilteredDispatchable},
|
||||
};
|
||||
use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin};
|
||||
use sp_core::H256;
|
||||
use sp_runtime::{traits::Bounded, BoundedVec};
|
||||
|
||||
use crate::Pallet as Democracy;
|
||||
@@ -46,7 +45,7 @@ fn make_proposal<T: Config>(n: u32) -> BoundedCallOf<T> {
|
||||
<T as Config>::Preimages::bound(call).unwrap()
|
||||
}
|
||||
|
||||
fn add_proposal<T: Config>(n: u32) -> Result<H256, &'static str> {
|
||||
fn add_proposal<T: Config>(n: u32) -> Result<T::Hash, &'static str> {
|
||||
let other = funded_account::<T>("proposer", n);
|
||||
let value = T::MinimumDeposit::get();
|
||||
let proposal = make_proposal::<T>(n);
|
||||
@@ -55,7 +54,7 @@ fn add_proposal<T: Config>(n: u32) -> Result<H256, &'static str> {
|
||||
}
|
||||
|
||||
// add a referendum with a metadata.
|
||||
fn add_referendum<T: Config>(n: u32) -> (ReferendumIndex, H256, PreimageHash) {
|
||||
fn add_referendum<T: Config>(n: u32) -> (ReferendumIndex, T::Hash, T::Hash) {
|
||||
let vote_threshold = VoteThreshold::SimpleMajority;
|
||||
let proposal = make_proposal::<T>(n);
|
||||
let hash = proposal.hash();
|
||||
@@ -85,7 +84,7 @@ fn assert_has_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {
|
||||
}
|
||||
|
||||
// note a new preimage.
|
||||
fn note_preimage<T: Config>() -> PreimageHash {
|
||||
fn note_preimage<T: Config>() -> T::Hash {
|
||||
use core::sync::atomic::{AtomicU8, Ordering};
|
||||
use sp_std::borrow::Cow;
|
||||
// note a new preimage on every function invoke.
|
||||
|
||||
@@ -159,9 +159,8 @@ use frame_support::{
|
||||
traits::{
|
||||
defensive_prelude::*,
|
||||
schedule::{v3::Named as ScheduleNamed, DispatchTime},
|
||||
Bounded, Currency, EnsureOrigin, Get, Hash as PreimageHash, LockIdentifier,
|
||||
LockableCurrency, OnUnbalanced, QueryPreimage, ReservableCurrency, StorePreimage,
|
||||
WithdrawReasons,
|
||||
Bounded, Currency, EnsureOrigin, Get, LockIdentifier, LockableCurrency, OnUnbalanced,
|
||||
QueryPreimage, ReservableCurrency, StorePreimage, WithdrawReasons,
|
||||
},
|
||||
weights::Weight,
|
||||
};
|
||||
@@ -203,7 +202,7 @@ type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<
|
||||
<T as frame_system::Config>::AccountId,
|
||||
>>::NegativeImbalance;
|
||||
pub type CallOf<T> = <T as frame_system::Config>::RuntimeCall;
|
||||
pub type BoundedCallOf<T> = Bounded<CallOf<T>>;
|
||||
pub type BoundedCallOf<T> = Bounded<CallOf<T>, <T as frame_system::Config>::Hashing>;
|
||||
type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
|
||||
|
||||
#[frame_support::pallet]
|
||||
@@ -211,7 +210,6 @@ pub mod pallet {
|
||||
use super::{DispatchResult, *};
|
||||
use frame_support::pallet_prelude::*;
|
||||
use frame_system::pallet_prelude::*;
|
||||
use sp_core::H256;
|
||||
|
||||
/// The current storage version.
|
||||
const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
|
||||
@@ -226,10 +224,15 @@ pub mod pallet {
|
||||
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
|
||||
|
||||
/// The Scheduler.
|
||||
type Scheduler: ScheduleNamed<BlockNumberFor<Self>, CallOf<Self>, Self::PalletsOrigin>;
|
||||
type Scheduler: ScheduleNamed<
|
||||
BlockNumberFor<Self>,
|
||||
CallOf<Self>,
|
||||
Self::PalletsOrigin,
|
||||
Hasher = Self::Hashing,
|
||||
>;
|
||||
|
||||
/// The Preimage provider.
|
||||
type Preimages: QueryPreimage + StorePreimage;
|
||||
type Preimages: QueryPreimage<H = Self::Hashing> + StorePreimage;
|
||||
|
||||
/// Currency type for this pallet.
|
||||
type Currency: ReservableCurrency<Self::AccountId>
|
||||
@@ -421,22 +424,22 @@ pub mod pallet {
|
||||
pub type Blacklist<T: Config> = StorageMap<
|
||||
_,
|
||||
Identity,
|
||||
H256,
|
||||
T::Hash,
|
||||
(BlockNumberFor<T>, BoundedVec<T::AccountId, T::MaxBlacklisted>),
|
||||
>;
|
||||
|
||||
/// Record of all proposals that have been subject to emergency cancellation.
|
||||
#[pallet::storage]
|
||||
pub type Cancellations<T: Config> = StorageMap<_, Identity, H256, bool, ValueQuery>;
|
||||
pub type Cancellations<T: Config> = StorageMap<_, Identity, T::Hash, bool, ValueQuery>;
|
||||
|
||||
/// General information concerning any proposal or referendum.
|
||||
/// The `PreimageHash` refers to the preimage of the `Preimages` provider which can be a JSON
|
||||
/// The `Hash` refers to the preimage of the `Preimages` provider which can be a JSON
|
||||
/// dump or IPFS hash of a JSON file.
|
||||
///
|
||||
/// Consider a garbage collection for a metadata of finished referendums to `unrequest` (remove)
|
||||
/// large preimages.
|
||||
#[pallet::storage]
|
||||
pub type MetadataOf<T: Config> = StorageMap<_, Blake2_128Concat, MetadataOwner, PreimageHash>;
|
||||
pub type MetadataOf<T: Config> = StorageMap<_, Blake2_128Concat, MetadataOwner, T::Hash>;
|
||||
|
||||
#[pallet::genesis_config]
|
||||
#[derive(frame_support::DefaultNoBound)]
|
||||
@@ -476,9 +479,9 @@ pub mod pallet {
|
||||
/// An account has cancelled a previous delegation operation.
|
||||
Undelegated { account: T::AccountId },
|
||||
/// An external proposal has been vetoed.
|
||||
Vetoed { who: T::AccountId, proposal_hash: H256, until: BlockNumberFor<T> },
|
||||
Vetoed { who: T::AccountId, proposal_hash: T::Hash, until: BlockNumberFor<T> },
|
||||
/// A proposal_hash has been blacklisted permanently.
|
||||
Blacklisted { proposal_hash: H256 },
|
||||
Blacklisted { proposal_hash: T::Hash },
|
||||
/// An account has voted in a referendum
|
||||
Voted { voter: T::AccountId, ref_index: ReferendumIndex, vote: AccountVote<BalanceOf<T>> },
|
||||
/// An account has secconded a proposal
|
||||
@@ -490,14 +493,14 @@ pub mod pallet {
|
||||
/// Metadata owner.
|
||||
owner: MetadataOwner,
|
||||
/// Preimage hash.
|
||||
hash: PreimageHash,
|
||||
hash: T::Hash,
|
||||
},
|
||||
/// Metadata for a proposal or a referendum has been cleared.
|
||||
MetadataCleared {
|
||||
/// Metadata owner.
|
||||
owner: MetadataOwner,
|
||||
/// Preimage hash.
|
||||
hash: PreimageHash,
|
||||
hash: T::Hash,
|
||||
},
|
||||
/// Metadata has been transferred to new owner.
|
||||
MetadataTransferred {
|
||||
@@ -506,7 +509,7 @@ pub mod pallet {
|
||||
/// New metadata owner.
|
||||
owner: MetadataOwner,
|
||||
/// Preimage hash.
|
||||
hash: PreimageHash,
|
||||
hash: T::Hash,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -775,7 +778,7 @@ pub mod pallet {
|
||||
#[pallet::weight(T::WeightInfo::fast_track())]
|
||||
pub fn fast_track(
|
||||
origin: OriginFor<T>,
|
||||
proposal_hash: H256,
|
||||
proposal_hash: T::Hash,
|
||||
voting_period: BlockNumberFor<T>,
|
||||
delay: BlockNumberFor<T>,
|
||||
) -> DispatchResult {
|
||||
@@ -827,7 +830,7 @@ pub mod pallet {
|
||||
/// Weight: `O(V + log(V))` where V is number of `existing vetoers`
|
||||
#[pallet::call_index(8)]
|
||||
#[pallet::weight(T::WeightInfo::veto_external())]
|
||||
pub fn veto_external(origin: OriginFor<T>, proposal_hash: H256) -> DispatchResult {
|
||||
pub fn veto_external(origin: OriginFor<T>, proposal_hash: T::Hash) -> DispatchResult {
|
||||
let who = T::VetoOrigin::ensure_origin(origin)?;
|
||||
|
||||
if let Some((ext_proposal, _)) = NextExternal::<T>::get() {
|
||||
@@ -1042,7 +1045,7 @@ pub mod pallet {
|
||||
#[pallet::weight((T::WeightInfo::blacklist(), DispatchClass::Operational))]
|
||||
pub fn blacklist(
|
||||
origin: OriginFor<T>,
|
||||
proposal_hash: H256,
|
||||
proposal_hash: T::Hash,
|
||||
maybe_ref_index: Option<ReferendumIndex>,
|
||||
) -> DispatchResult {
|
||||
T::BlacklistOrigin::ensure_origin(origin)?;
|
||||
@@ -1139,7 +1142,7 @@ pub mod pallet {
|
||||
pub fn set_metadata(
|
||||
origin: OriginFor<T>,
|
||||
owner: MetadataOwner,
|
||||
maybe_hash: Option<PreimageHash>,
|
||||
maybe_hash: Option<T::Hash>,
|
||||
) -> DispatchResult {
|
||||
match owner {
|
||||
MetadataOwner::External => {
|
||||
@@ -1173,15 +1176,16 @@ pub mod pallet {
|
||||
}
|
||||
|
||||
pub trait EncodeInto: Encode {
|
||||
fn encode_into<T: AsMut<[u8]> + Default>(&self) -> T {
|
||||
fn encode_into<T: AsMut<[u8]> + Default, H: sp_core::Hasher>(&self) -> T {
|
||||
let mut t = T::default();
|
||||
self.using_encoded(|data| {
|
||||
if data.len() <= t.as_mut().len() {
|
||||
t.as_mut()[0..data.len()].copy_from_slice(data);
|
||||
} else {
|
||||
// encoded self is too big to fit into a T. hash it and use the first bytes of that
|
||||
// instead.
|
||||
let hash = sp_io::hashing::blake2_256(data);
|
||||
// encoded self is too big to fit into a T.
|
||||
// hash it and use the first bytes of that instead.
|
||||
let hash = H::hash(&data);
|
||||
let hash = hash.as_ref();
|
||||
let l = t.as_mut().len().min(hash.len());
|
||||
t.as_mut()[0..l].copy_from_slice(&hash[0..l]);
|
||||
}
|
||||
@@ -1610,7 +1614,7 @@ impl<T: Config> Pallet<T> {
|
||||
// Earliest it can be scheduled for is next block.
|
||||
let when = now.saturating_add(status.delay.max(One::one()));
|
||||
if T::Scheduler::schedule_named(
|
||||
(DEMOCRACY_ID, index).encode_into(),
|
||||
(DEMOCRACY_ID, index).encode_into::<_, T::Hashing>(),
|
||||
DispatchTime::At(when),
|
||||
None,
|
||||
63,
|
||||
|
||||
@@ -277,7 +277,7 @@ fn tally(r: ReferendumIndex) -> Tally<u64> {
|
||||
}
|
||||
|
||||
/// note a new preimage without registering.
|
||||
fn note_preimage(who: u64) -> PreimageHash {
|
||||
fn note_preimage(who: u64) -> <Test as frame_system::Config>::Hash {
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
// note a new preimage on every function invoke.
|
||||
static COUNTER: AtomicU8 = AtomicU8::new(0);
|
||||
|
||||
@@ -22,9 +22,8 @@ use super::*;
|
||||
#[test]
|
||||
fn set_external_metadata_works() {
|
||||
new_test_ext().execute_with(|| {
|
||||
use frame_support::traits::Hash as PreimageHash;
|
||||
// invalid preimage hash.
|
||||
let invalid_hash: PreimageHash = [1u8; 32].into();
|
||||
let invalid_hash: <Test as frame_system::Config>::Hash = [1u8; 32].into();
|
||||
// metadata owner is an external proposal.
|
||||
let owner = MetadataOwner::External;
|
||||
// fails to set metadata if an external proposal does not exist.
|
||||
@@ -83,9 +82,8 @@ fn clear_metadata_works() {
|
||||
#[test]
|
||||
fn set_proposal_metadata_works() {
|
||||
new_test_ext().execute_with(|| {
|
||||
use frame_support::traits::Hash as PreimageHash;
|
||||
// invalid preimage hash.
|
||||
let invalid_hash: PreimageHash = [1u8; 32].into();
|
||||
let invalid_hash: <Test as frame_system::Config>::Hash = [1u8; 32].into();
|
||||
// create an external proposal.
|
||||
assert_ok!(propose_set_balance(1, 2, 5));
|
||||
// metadata owner is a public proposal.
|
||||
|
||||
@@ -49,8 +49,8 @@ use frame_support::{
|
||||
ensure,
|
||||
pallet_prelude::Get,
|
||||
traits::{
|
||||
Consideration, Currency, Defensive, FetchResult, Footprint, Hash as PreimageHash,
|
||||
PreimageProvider, PreimageRecipient, QueryPreimage, ReservableCurrency, StorePreimage,
|
||||
Consideration, Currency, Defensive, FetchResult, Footprint, PreimageProvider,
|
||||
PreimageRecipient, QueryPreimage, ReservableCurrency, StorePreimage,
|
||||
},
|
||||
BoundedSlice, BoundedVec,
|
||||
};
|
||||
@@ -531,7 +531,9 @@ impl<T: Config> PreimageRecipient<T::Hash> for Pallet<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config<Hash = PreimageHash>> QueryPreimage for Pallet<T> {
|
||||
impl<T: Config> QueryPreimage for Pallet<T> {
|
||||
type H = T::Hashing;
|
||||
|
||||
fn len(hash: &T::Hash) -> Option<u32> {
|
||||
Pallet::<T>::len(hash)
|
||||
}
|
||||
@@ -555,7 +557,7 @@ impl<T: Config<Hash = PreimageHash>> QueryPreimage for Pallet<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config<Hash = PreimageHash>> StorePreimage for Pallet<T> {
|
||||
impl<T: Config> StorePreimage for Pallet<T> {
|
||||
const MAX_LENGTH: usize = MAX_SIZE as usize;
|
||||
|
||||
fn note(bytes: Cow<[u8]>) -> Result<T::Hash, DispatchError> {
|
||||
|
||||
@@ -24,25 +24,32 @@ use crate::mock::*;
|
||||
|
||||
use frame_support::{
|
||||
assert_err, assert_noop, assert_ok, assert_storage_noop,
|
||||
traits::{fungible::InspectHold, Bounded, BoundedInline, Hash as PreimageHash},
|
||||
traits::{fungible::InspectHold, Bounded, BoundedInline},
|
||||
StorageNoopGuard,
|
||||
};
|
||||
use sp_core::{blake2_256, H256};
|
||||
use sp_runtime::{bounded_vec, TokenError};
|
||||
|
||||
/// Returns one `Inline`, `Lookup` and `Legacy` item each with different data and hash.
|
||||
pub fn make_bounded_values() -> (Bounded<Vec<u8>>, Bounded<Vec<u8>>, Bounded<Vec<u8>>) {
|
||||
pub fn make_bounded_values() -> (
|
||||
Bounded<Vec<u8>, <Test as frame_system::Config>::Hashing>,
|
||||
Bounded<Vec<u8>, <Test as frame_system::Config>::Hashing>,
|
||||
Bounded<Vec<u8>, <Test as frame_system::Config>::Hashing>,
|
||||
) {
|
||||
let data: BoundedInline = bounded_vec![1];
|
||||
let inline = Bounded::<Vec<u8>>::Inline(data);
|
||||
let inline = Bounded::<Vec<u8>, <Test as frame_system::Config>::Hashing>::Inline(data);
|
||||
|
||||
let data = vec![1, 2];
|
||||
let hash: H256 = blake2_256(&data[..]).into();
|
||||
let hash = <Test as frame_system::Config>::Hashing::hash(&data[..]).into();
|
||||
let len = data.len() as u32;
|
||||
let lookup = Bounded::<Vec<u8>>::unrequested(hash, len);
|
||||
let lookup =
|
||||
Bounded::<Vec<u8>, <Test as frame_system::Config>::Hashing>::unrequested(hash, len);
|
||||
|
||||
let data = vec![1, 2, 3];
|
||||
let hash: H256 = blake2_256(&data[..]).into();
|
||||
let legacy = Bounded::<Vec<u8>>::Legacy { hash, dummy: Default::default() };
|
||||
let hash = <Test as frame_system::Config>::Hashing::hash(&data[..]).into();
|
||||
let legacy = Bounded::<Vec<u8>, <Test as frame_system::Config>::Hashing>::Legacy {
|
||||
hash,
|
||||
dummy: Default::default(),
|
||||
};
|
||||
|
||||
(inline, lookup, legacy)
|
||||
}
|
||||
@@ -303,7 +310,7 @@ fn query_and_store_preimage_workflow() {
|
||||
let bound = Preimage::bound(data.clone()).unwrap();
|
||||
let (len, hash) = (bound.len().unwrap(), bound.hash());
|
||||
|
||||
assert_eq!(hash, blake2_256(&encoded).into());
|
||||
assert_eq!(hash, <Test as frame_system::Config>::Hashing::hash(&encoded).into());
|
||||
assert_eq!(bound.len(), Some(len));
|
||||
assert!(bound.lookup_needed(), "Should not be Inlined");
|
||||
assert_eq!(bound.lookup_len(), Some(len));
|
||||
@@ -364,7 +371,7 @@ fn query_preimage_request_works() {
|
||||
new_test_ext().execute_with(|| {
|
||||
let _guard = StorageNoopGuard::default();
|
||||
let data: Vec<u8> = vec![1; 10];
|
||||
let hash: PreimageHash = blake2_256(&data[..]).into();
|
||||
let hash = <Test as frame_system::Config>::Hashing::hash(&data[..]).into();
|
||||
|
||||
// Request the preimage.
|
||||
<Preimage as QueryPreimage>::request(&hash);
|
||||
@@ -454,7 +461,7 @@ fn store_preimage_basic_works() {
|
||||
|
||||
// Cleanup.
|
||||
<Preimage as StorePreimage>::unnote(&bound.hash());
|
||||
let data_hash = blake2_256(&data);
|
||||
let data_hash = <Test as frame_system::Config>::Hashing::hash(&data);
|
||||
<Preimage as StorePreimage>::unnote(&data_hash.into());
|
||||
|
||||
// No storage changes remain. Checked by `StorageNoopGuard`.
|
||||
|
||||
@@ -25,7 +25,7 @@ use frame_benchmarking::v1::{
|
||||
};
|
||||
use frame_support::{
|
||||
assert_ok,
|
||||
traits::{Bounded, Currency, EnsureOrigin, EnsureOriginWithArg, UnfilteredDispatchable},
|
||||
traits::{Currency, EnsureOrigin, EnsureOriginWithArg, UnfilteredDispatchable},
|
||||
};
|
||||
use frame_system::RawOrigin;
|
||||
use sp_runtime::traits::Bounded as ArithBounded;
|
||||
@@ -42,7 +42,7 @@ fn funded_account<T: Config<I>, I: 'static>(name: &'static str, index: u32) -> T
|
||||
caller
|
||||
}
|
||||
|
||||
fn dummy_call<T: Config<I>, I: 'static>() -> Bounded<<T as Config<I>>::RuntimeCall> {
|
||||
fn dummy_call<T: Config<I>, I: 'static>() -> BoundedCallOf<T, I> {
|
||||
let inner = frame_system::Call::remark { remark: vec![] };
|
||||
let call = <T as Config<I>>::RuntimeCall::from(inner);
|
||||
T::Preimages::bound(call).unwrap()
|
||||
|
||||
@@ -73,8 +73,8 @@ use frame_support::{
|
||||
v3::{Anon as ScheduleAnon, Named as ScheduleNamed},
|
||||
DispatchTime,
|
||||
},
|
||||
Currency, Hash as PreimageHash, LockIdentifier, OnUnbalanced, OriginTrait, PollStatus,
|
||||
Polling, QueryPreimage, ReservableCurrency, StorePreimage, VoteTally,
|
||||
Currency, LockIdentifier, OnUnbalanced, OriginTrait, PollStatus, Polling, QueryPreimage,
|
||||
ReservableCurrency, StorePreimage, VoteTally,
|
||||
},
|
||||
BoundedVec,
|
||||
};
|
||||
@@ -163,8 +163,17 @@ pub mod pallet {
|
||||
/// Weight information for extrinsics in this pallet.
|
||||
type WeightInfo: WeightInfo;
|
||||
/// The Scheduler.
|
||||
type Scheduler: ScheduleAnon<BlockNumberFor<Self>, CallOf<Self, I>, PalletsOriginOf<Self>>
|
||||
+ ScheduleNamed<BlockNumberFor<Self>, CallOf<Self, I>, PalletsOriginOf<Self>>;
|
||||
type Scheduler: ScheduleAnon<
|
||||
BlockNumberFor<Self>,
|
||||
CallOf<Self, I>,
|
||||
PalletsOriginOf<Self>,
|
||||
Hasher = Self::Hashing,
|
||||
> + ScheduleNamed<
|
||||
BlockNumberFor<Self>,
|
||||
CallOf<Self, I>,
|
||||
PalletsOriginOf<Self>,
|
||||
Hasher = Self::Hashing,
|
||||
>;
|
||||
/// Currency type for this pallet.
|
||||
type Currency: ReservableCurrency<Self::AccountId>;
|
||||
// Origins and unbalances.
|
||||
@@ -226,7 +235,7 @@ pub mod pallet {
|
||||
>;
|
||||
|
||||
/// The preimage provider.
|
||||
type Preimages: QueryPreimage + StorePreimage;
|
||||
type Preimages: QueryPreimage<H = Self::Hashing> + StorePreimage;
|
||||
}
|
||||
|
||||
/// The next free referendum index, aka the number of referenda started so far.
|
||||
@@ -257,14 +266,14 @@ pub mod pallet {
|
||||
StorageMap<_, Twox64Concat, TrackIdOf<T, I>, u32, ValueQuery>;
|
||||
|
||||
/// The metadata is a general information concerning the referendum.
|
||||
/// The `PreimageHash` refers to the preimage of the `Preimages` provider which can be a JSON
|
||||
/// The `Hash` refers to the preimage of the `Preimages` provider which can be a JSON
|
||||
/// dump or IPFS hash of a JSON file.
|
||||
///
|
||||
/// Consider a garbage collection for a metadata of finished referendums to `unrequest` (remove)
|
||||
/// large preimages.
|
||||
#[pallet::storage]
|
||||
pub type MetadataOf<T: Config<I>, I: 'static = ()> =
|
||||
StorageMap<_, Blake2_128Concat, ReferendumIndex, PreimageHash>;
|
||||
StorageMap<_, Blake2_128Concat, ReferendumIndex, T::Hash>;
|
||||
|
||||
#[pallet::event]
|
||||
#[pallet::generate_deposit(pub(super) fn deposit_event)]
|
||||
@@ -376,14 +385,14 @@ pub mod pallet {
|
||||
/// Index of the referendum.
|
||||
index: ReferendumIndex,
|
||||
/// Preimage hash.
|
||||
hash: PreimageHash,
|
||||
hash: T::Hash,
|
||||
},
|
||||
/// Metadata for a referendum has been cleared.
|
||||
MetadataCleared {
|
||||
/// Index of the referendum.
|
||||
index: ReferendumIndex,
|
||||
/// Preimage hash.
|
||||
hash: PreimageHash,
|
||||
hash: T::Hash,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -691,7 +700,7 @@ pub mod pallet {
|
||||
pub fn set_metadata(
|
||||
origin: OriginFor<T>,
|
||||
index: ReferendumIndex,
|
||||
maybe_hash: Option<PreimageHash>,
|
||||
maybe_hash: Option<T::Hash>,
|
||||
) -> DispatchResult {
|
||||
let who = ensure_signed(origin)?;
|
||||
if let Some(hash) = maybe_hash {
|
||||
|
||||
@@ -473,7 +473,7 @@ impl RefState {
|
||||
}
|
||||
|
||||
/// note a new preimage without registering.
|
||||
pub fn note_preimage(who: u64) -> PreimageHash {
|
||||
pub fn note_preimage(who: u64) -> <Test as frame_system::Config>::Hash {
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
// note a new preimage on every function invoke.
|
||||
static COUNTER: AtomicU8 = AtomicU8::new(0);
|
||||
|
||||
@@ -599,9 +599,8 @@ fn curve_handles_all_inputs() {
|
||||
#[test]
|
||||
fn set_metadata_works() {
|
||||
ExtBuilder::default().build_and_execute(|| {
|
||||
use frame_support::traits::Hash as PreimageHash;
|
||||
// invalid preimage hash.
|
||||
let invalid_hash: PreimageHash = [1u8; 32].into();
|
||||
let invalid_hash: <Test as frame_system::Config>::Hash = [1u8; 32].into();
|
||||
// fails to set metadata for a finished referendum.
|
||||
assert_ok!(Referenda::submit(
|
||||
RuntimeOrigin::signed(1),
|
||||
|
||||
@@ -34,7 +34,8 @@ pub type NegativeImbalanceOf<T, I> = <<T as Config<I>>::Currency as Currency<
|
||||
<T as frame_system::Config>::AccountId,
|
||||
>>::NegativeImbalance;
|
||||
pub type CallOf<T, I> = <T as Config<I>>::RuntimeCall;
|
||||
pub type BoundedCallOf<T, I> = Bounded<<T as Config<I>>::RuntimeCall>;
|
||||
pub type BoundedCallOf<T, I> =
|
||||
Bounded<<T as Config<I>>::RuntimeCall, <T as frame_system::Config>::Hashing>;
|
||||
pub type VotesOf<T, I> = <T as Config<I>>::Votes;
|
||||
pub type TallyOf<T, I> = <T as Config<I>>::Tally;
|
||||
pub type PalletsOriginOf<T> =
|
||||
|
||||
@@ -82,13 +82,13 @@ fn make_task<T: Config>(
|
||||
Scheduled { maybe_id, priority, call, maybe_periodic, origin, _phantom: PhantomData }
|
||||
}
|
||||
|
||||
fn bounded<T: Config>(len: u32) -> Option<Bounded<<T as Config>::RuntimeCall>> {
|
||||
fn bounded<T: Config>(len: u32) -> Option<BoundedCallOf<T>> {
|
||||
let call =
|
||||
<<T as Config>::RuntimeCall>::from(SystemCall::remark { remark: vec![0; len as usize] });
|
||||
T::Preimages::bound(call).ok()
|
||||
}
|
||||
|
||||
fn make_call<T: Config>(maybe_lookup_len: Option<u32>) -> Bounded<<T as Config>::RuntimeCall> {
|
||||
fn make_call<T: Config>(maybe_lookup_len: Option<u32>) -> BoundedCallOf<T> {
|
||||
let bound = BoundedInline::bound() as u32;
|
||||
let mut len = match maybe_lookup_len {
|
||||
Some(len) => len.min(T::Preimages::MAX_LENGTH as u32 - 2).max(bound) - 3,
|
||||
|
||||
@@ -91,8 +91,8 @@ use frame_support::{
|
||||
ensure,
|
||||
traits::{
|
||||
schedule::{self, DispatchTime, MaybeHashed},
|
||||
Bounded, CallerTrait, EnsureOrigin, Get, Hash as PreimageHash, IsType, OriginTrait,
|
||||
PalletInfoAccess, PrivilegeCmp, QueryPreimage, StorageVersion, StorePreimage,
|
||||
Bounded, CallerTrait, EnsureOrigin, Get, IsType, OriginTrait, PalletInfoAccess,
|
||||
PrivilegeCmp, QueryPreimage, StorageVersion, StorePreimage,
|
||||
},
|
||||
weights::{Weight, WeightMeter},
|
||||
};
|
||||
@@ -119,6 +119,9 @@ pub type TaskAddress<BlockNumber> = (BlockNumber, u32);
|
||||
pub type CallOrHashOf<T> =
|
||||
MaybeHashed<<T as Config>::RuntimeCall, <T as frame_system::Config>::Hash>;
|
||||
|
||||
pub type BoundedCallOf<T> =
|
||||
Bounded<<T as Config>::RuntimeCall, <T as frame_system::Config>::Hashing>;
|
||||
|
||||
#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
|
||||
#[derive(Clone, RuntimeDebug, Encode, Decode)]
|
||||
struct ScheduledV1<Call, BlockNumber> {
|
||||
@@ -165,7 +168,7 @@ pub type ScheduledV3Of<T> = ScheduledV3<
|
||||
|
||||
pub type ScheduledOf<T> = Scheduled<
|
||||
TaskName,
|
||||
Bounded<<T as Config>::RuntimeCall>,
|
||||
BoundedCallOf<T>,
|
||||
BlockNumberFor<T>,
|
||||
<T as Config>::PalletsOrigin,
|
||||
<T as frame_system::Config>::AccountId,
|
||||
@@ -254,7 +257,7 @@ pub mod pallet {
|
||||
type WeightInfo: WeightInfo;
|
||||
|
||||
/// The preimage provider with which we look up call hashes to get the call.
|
||||
type Preimages: QueryPreimage + StorePreimage;
|
||||
type Preimages: QueryPreimage<H = Self::Hashing> + StorePreimage;
|
||||
}
|
||||
|
||||
#[pallet::storage]
|
||||
@@ -440,7 +443,7 @@ pub mod pallet {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config<Hash = PreimageHash>> Pallet<T> {
|
||||
impl<T: Config> Pallet<T> {
|
||||
/// Migrate storage format from V1 to V4.
|
||||
///
|
||||
/// Returns the weight consumed by this migration.
|
||||
@@ -627,7 +630,7 @@ impl<T: Config<Hash = PreimageHash>> Pallet<T> {
|
||||
>(&bounded)
|
||||
{
|
||||
log::error!(
|
||||
"Dropping undecodable call {}: {:?}",
|
||||
"Dropping undecodable call {:?}: {:?}",
|
||||
&h,
|
||||
&err
|
||||
);
|
||||
@@ -695,7 +698,7 @@ impl<T: Config> Pallet<T> {
|
||||
Option<
|
||||
Scheduled<
|
||||
TaskName,
|
||||
Bounded<<T as Config>::RuntimeCall>,
|
||||
BoundedCallOf<T>,
|
||||
BlockNumberFor<T>,
|
||||
OldOrigin,
|
||||
T::AccountId,
|
||||
@@ -797,7 +800,7 @@ impl<T: Config> Pallet<T> {
|
||||
maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
|
||||
priority: schedule::Priority,
|
||||
origin: T::PalletsOrigin,
|
||||
call: Bounded<<T as Config>::RuntimeCall>,
|
||||
call: BoundedCallOf<T>,
|
||||
) -> Result<TaskAddress<BlockNumberFor<T>>, DispatchError> {
|
||||
let when = Self::resolve_time(when)?;
|
||||
|
||||
@@ -886,7 +889,7 @@ impl<T: Config> Pallet<T> {
|
||||
maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
|
||||
priority: schedule::Priority,
|
||||
origin: T::PalletsOrigin,
|
||||
call: Bounded<<T as Config>::RuntimeCall>,
|
||||
call: BoundedCallOf<T>,
|
||||
) -> Result<TaskAddress<BlockNumberFor<T>>, DispatchError> {
|
||||
// ensure id it is unique
|
||||
if Lookup::<T>::contains_key(&id) {
|
||||
@@ -1191,8 +1194,8 @@ impl<T: Config> Pallet<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config<Hash = PreimageHash>>
|
||||
schedule::v2::Anon<BlockNumberFor<T>, <T as Config>::RuntimeCall, T::PalletsOrigin> for Pallet<T>
|
||||
impl<T: Config> schedule::v2::Anon<BlockNumberFor<T>, <T as Config>::RuntimeCall, T::PalletsOrigin>
|
||||
for Pallet<T>
|
||||
{
|
||||
type Address = TaskAddress<BlockNumberFor<T>>;
|
||||
type Hash = T::Hash;
|
||||
@@ -1225,8 +1228,8 @@ impl<T: Config<Hash = PreimageHash>>
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config<Hash = PreimageHash>>
|
||||
schedule::v2::Named<BlockNumberFor<T>, <T as Config>::RuntimeCall, T::PalletsOrigin> for Pallet<T>
|
||||
impl<T: Config> schedule::v2::Named<BlockNumberFor<T>, <T as Config>::RuntimeCall, T::PalletsOrigin>
|
||||
for Pallet<T>
|
||||
{
|
||||
type Address = TaskAddress<BlockNumberFor<T>>;
|
||||
type Hash = T::Hash;
|
||||
@@ -1270,13 +1273,14 @@ impl<T: Config> schedule::v3::Anon<BlockNumberFor<T>, <T as Config>::RuntimeCall
|
||||
for Pallet<T>
|
||||
{
|
||||
type Address = TaskAddress<BlockNumberFor<T>>;
|
||||
type Hasher = T::Hashing;
|
||||
|
||||
fn schedule(
|
||||
when: DispatchTime<BlockNumberFor<T>>,
|
||||
maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
|
||||
priority: schedule::Priority,
|
||||
origin: T::PalletsOrigin,
|
||||
call: Bounded<<T as Config>::RuntimeCall>,
|
||||
call: BoundedCallOf<T>,
|
||||
) -> Result<Self::Address, DispatchError> {
|
||||
Self::do_schedule(when, maybe_periodic, priority, origin, call)
|
||||
}
|
||||
@@ -1308,6 +1312,7 @@ impl<T: Config> schedule::v3::Named<BlockNumberFor<T>, <T as Config>::RuntimeCal
|
||||
for Pallet<T>
|
||||
{
|
||||
type Address = TaskAddress<BlockNumberFor<T>>;
|
||||
type Hasher = T::Hashing;
|
||||
|
||||
fn schedule_named(
|
||||
id: TaskName,
|
||||
@@ -1315,7 +1320,7 @@ impl<T: Config> schedule::v3::Named<BlockNumberFor<T>, <T as Config>::RuntimeCal
|
||||
maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
|
||||
priority: schedule::Priority,
|
||||
origin: T::PalletsOrigin,
|
||||
call: Bounded<<T as Config>::RuntimeCall>,
|
||||
call: BoundedCallOf<T>,
|
||||
) -> Result<Self::Address, DispatchError> {
|
||||
Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call)
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ pub mod v3 {
|
||||
/// Migrate the scheduler pallet from V3 to V4.
|
||||
pub struct MigrateToV4<T>(sp_std::marker::PhantomData<T>);
|
||||
|
||||
impl<T: Config<Hash = PreimageHash>> OnRuntimeUpgrade for MigrateToV4<T> {
|
||||
impl<T: Config> OnRuntimeUpgrade for MigrateToV4<T> {
|
||||
#[cfg(feature = "try-runtime")]
|
||||
fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> {
|
||||
ensure!(StorageVersion::get::<Pallet<T>>() == 3, "Can only upgrade from version 3");
|
||||
|
||||
@@ -1019,7 +1019,7 @@ fn test_migrate_origin() {
|
||||
new_test_ext().execute_with(|| {
|
||||
for i in 0..3u64 {
|
||||
let k = i.twox_64_concat();
|
||||
let old: Vec<Option<Scheduled<[u8; 32], Bounded<RuntimeCall>, u64, u32, u64>>> = vec![
|
||||
let old: Vec<Option<Scheduled<[u8; 32], BoundedCallOf<Test>, u64, u32, u64>>> = vec![
|
||||
Some(Scheduled {
|
||||
maybe_id: None,
|
||||
priority: i as u8 + 10,
|
||||
|
||||
@@ -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::{
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -79,7 +79,7 @@ benchmarks! {
|
||||
let call_weight = call.get_dispatch_info().weight;
|
||||
let encoded_call = call.encode();
|
||||
let call_encoded_len = encoded_call.len() as u32;
|
||||
let call_hash = call.blake2_256().into();
|
||||
let call_hash = T::Hashing::hash_of(&call);
|
||||
|
||||
Pallet::<T>::whitelist_call(origin.clone(), call_hash)
|
||||
.expect("whitelisting call must be successful");
|
||||
@@ -106,7 +106,7 @@ benchmarks! {
|
||||
let remark = sp_std::vec![1u8; n as usize];
|
||||
|
||||
let call: <T as Config>::RuntimeCall = frame_system::Call::remark { remark }.into();
|
||||
let call_hash = call.blake2_256().into();
|
||||
let call_hash = T::Hashing::hash_of(&call);
|
||||
|
||||
Pallet::<T>::whitelist_call(origin.clone(), call_hash)
|
||||
.expect("whitelisting call must be successful");
|
||||
|
||||
@@ -44,12 +44,11 @@ use codec::{DecodeLimit, Encode, FullCodec};
|
||||
use frame_support::{
|
||||
dispatch::{GetDispatchInfo, PostDispatchInfo},
|
||||
ensure,
|
||||
traits::{Hash as PreimageHash, QueryPreimage, StorePreimage},
|
||||
traits::{QueryPreimage, StorePreimage},
|
||||
weights::Weight,
|
||||
Hashable,
|
||||
};
|
||||
use scale_info::TypeInfo;
|
||||
use sp_runtime::traits::Dispatchable;
|
||||
use sp_runtime::traits::{Dispatchable, Hash};
|
||||
use sp_std::prelude::*;
|
||||
|
||||
pub use pallet::*;
|
||||
@@ -81,7 +80,7 @@ pub mod pallet {
|
||||
type DispatchWhitelistedOrigin: EnsureOrigin<Self::RuntimeOrigin>;
|
||||
|
||||
/// The handler of pre-images.
|
||||
type Preimages: QueryPreimage + StorePreimage;
|
||||
type Preimages: QueryPreimage<H = Self::Hashing> + StorePreimage;
|
||||
|
||||
/// The weight information for this pallet.
|
||||
type WeightInfo: WeightInfo;
|
||||
@@ -93,9 +92,9 @@ pub mod pallet {
|
||||
#[pallet::event]
|
||||
#[pallet::generate_deposit(pub(super) fn deposit_event)]
|
||||
pub enum Event<T: Config> {
|
||||
CallWhitelisted { call_hash: PreimageHash },
|
||||
WhitelistedCallRemoved { call_hash: PreimageHash },
|
||||
WhitelistedCallDispatched { call_hash: PreimageHash, result: DispatchResultWithPostInfo },
|
||||
CallWhitelisted { call_hash: T::Hash },
|
||||
WhitelistedCallRemoved { call_hash: T::Hash },
|
||||
WhitelistedCallDispatched { call_hash: T::Hash, result: DispatchResultWithPostInfo },
|
||||
}
|
||||
|
||||
#[pallet::error]
|
||||
@@ -113,14 +112,13 @@ pub mod pallet {
|
||||
}
|
||||
|
||||
#[pallet::storage]
|
||||
pub type WhitelistedCall<T: Config> =
|
||||
StorageMap<_, Twox64Concat, PreimageHash, (), OptionQuery>;
|
||||
pub type WhitelistedCall<T: Config> = StorageMap<_, Twox64Concat, T::Hash, (), OptionQuery>;
|
||||
|
||||
#[pallet::call]
|
||||
impl<T: Config> Pallet<T> {
|
||||
#[pallet::call_index(0)]
|
||||
#[pallet::weight(T::WeightInfo::whitelist_call())]
|
||||
pub fn whitelist_call(origin: OriginFor<T>, call_hash: PreimageHash) -> DispatchResult {
|
||||
pub fn whitelist_call(origin: OriginFor<T>, call_hash: T::Hash) -> DispatchResult {
|
||||
T::WhitelistOrigin::ensure_origin(origin)?;
|
||||
|
||||
ensure!(
|
||||
@@ -138,10 +136,7 @@ pub mod pallet {
|
||||
|
||||
#[pallet::call_index(1)]
|
||||
#[pallet::weight(T::WeightInfo::remove_whitelisted_call())]
|
||||
pub fn remove_whitelisted_call(
|
||||
origin: OriginFor<T>,
|
||||
call_hash: PreimageHash,
|
||||
) -> DispatchResult {
|
||||
pub fn remove_whitelisted_call(origin: OriginFor<T>, call_hash: T::Hash) -> DispatchResult {
|
||||
T::WhitelistOrigin::ensure_origin(origin)?;
|
||||
|
||||
WhitelistedCall::<T>::take(call_hash).ok_or(Error::<T>::CallIsNotWhitelisted)?;
|
||||
@@ -160,7 +155,7 @@ pub mod pallet {
|
||||
)]
|
||||
pub fn dispatch_whitelisted_call(
|
||||
origin: OriginFor<T>,
|
||||
call_hash: PreimageHash,
|
||||
call_hash: T::Hash,
|
||||
call_encoded_len: u32,
|
||||
call_weight_witness: Weight,
|
||||
) -> DispatchResultWithPostInfo {
|
||||
@@ -206,7 +201,7 @@ pub mod pallet {
|
||||
) -> DispatchResultWithPostInfo {
|
||||
T::DispatchWhitelistedOrigin::ensure_origin(origin)?;
|
||||
|
||||
let call_hash = call.blake2_256().into();
|
||||
let call_hash = T::Hashing::hash_of(&call).into();
|
||||
|
||||
ensure!(
|
||||
WhitelistedCall::<T>::contains_key(call_hash),
|
||||
@@ -227,10 +222,7 @@ impl<T: Config> Pallet<T> {
|
||||
/// Clean whitelisting/preimage and dispatch call.
|
||||
///
|
||||
/// Return the call actual weight of the dispatched call if there is some.
|
||||
fn clean_and_dispatch(
|
||||
call_hash: PreimageHash,
|
||||
call: <T as Config>::RuntimeCall,
|
||||
) -> Option<Weight> {
|
||||
fn clean_and_dispatch(call_hash: T::Hash, call: <T as Config>::RuntimeCall) -> Option<Weight> {
|
||||
WhitelistedCall::<T>::remove(call_hash);
|
||||
|
||||
T::Preimages::unrequest(&call_hash);
|
||||
|
||||
Reference in New Issue
Block a user