referrerpolicy=no-referrer-when-downgrade

frame_support/traits/
preimages.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Stuff for dealing with hashed preimages.
19
20use alloc::borrow::Cow;
21use codec::{Decode, DecodeWithMemTracking, Encode, EncodeLike, MaxEncodedLen};
22use scale_info::TypeInfo;
23use sp_core::RuntimeDebug;
24use sp_runtime::{
25	traits::{ConstU32, Hash},
26	DispatchError,
27};
28
29pub type BoundedInline = crate::BoundedVec<u8, ConstU32<128>>;
30
31/// The maximum we expect a single legacy hash lookup to be.
32const MAX_LEGACY_LEN: u32 = 1_000_000;
33
34#[derive(
35	Encode,
36	Decode,
37	DecodeWithMemTracking,
38	MaxEncodedLen,
39	Clone,
40	Eq,
41	PartialEq,
42	TypeInfo,
43	RuntimeDebug,
44)]
45#[codec(mel_bound())]
46pub enum Bounded<T, H: Hash> {
47	/// A hash with no preimage length. We do not support creation of this except
48	/// for transitioning from legacy state. In the future we will make this a pure
49	/// `Dummy` item storing only the final `dummy` field.
50	Legacy { hash: H::Output, dummy: core::marker::PhantomData<T> },
51	/// A bounded `Call`. Its encoding must be at most 128 bytes.
52	Inline(BoundedInline),
53	/// A hash of the call together with an upper limit for its size.`
54	Lookup { hash: H::Output, len: u32 },
55}
56
57impl<T, H: Hash> Bounded<T, H> {
58	/// Casts the wrapped type into something that encodes alike.
59	///
60	/// # Examples
61	/// ```
62	/// use frame_support::{traits::Bounded, sp_runtime::traits::BlakeTwo256};
63	///
64	/// // Transmute from `String` to `&str`.
65	/// let x: Bounded<String, BlakeTwo256> = Bounded::Inline(Default::default());
66	/// let _: Bounded<&str, BlakeTwo256> = x.transmute();
67	/// ```
68	pub fn transmute<S: Encode>(self) -> Bounded<S, H>
69	where
70		T: Encode + EncodeLike<S>,
71	{
72		use Bounded::*;
73		match self {
74			Legacy { hash, .. } => Legacy { hash, dummy: core::marker::PhantomData },
75			Inline(x) => Inline(x),
76			Lookup { hash, len } => Lookup { hash, len },
77		}
78	}
79
80	/// Returns the hash of the preimage.
81	///
82	/// The hash is re-calculated every time if the preimage is inlined.
83	pub fn hash(&self) -> H::Output {
84		use Bounded::*;
85		match self {
86			Lookup { hash, .. } | Legacy { hash, .. } => *hash,
87			Inline(x) => <H as Hash>::hash(x.as_ref()),
88		}
89	}
90
91	/// Returns the hash to lookup the preimage.
92	///
93	/// If this is a `Bounded::Inline`, `None` is returned as no lookup is required.
94	pub fn lookup_hash(&self) -> Option<H::Output> {
95		use Bounded::*;
96		match self {
97			Lookup { hash, .. } | Legacy { hash, .. } => Some(*hash),
98			Inline(_) => None,
99		}
100	}
101
102	/// Returns the length of the preimage or `None` if the length is unknown.
103	pub fn len(&self) -> Option<u32> {
104		match self {
105			Self::Legacy { .. } => None,
106			Self::Inline(i) => Some(i.len() as u32),
107			Self::Lookup { len, .. } => Some(*len),
108		}
109	}
110
111	/// Returns whether the image will require a lookup to be peeked.
112	pub fn lookup_needed(&self) -> bool {
113		match self {
114			Self::Inline(..) => false,
115			Self::Legacy { .. } | Self::Lookup { .. } => true,
116		}
117	}
118
119	/// The maximum length of the lookup that is needed to peek `Self`.
120	pub fn lookup_len(&self) -> Option<u32> {
121		match self {
122			Self::Inline(..) => None,
123			Self::Legacy { .. } => Some(MAX_LEGACY_LEN),
124			Self::Lookup { len, .. } => Some(*len),
125		}
126	}
127
128	/// Constructs a `Lookup` bounded item.
129	pub fn unrequested(hash: H::Output, len: u32) -> Self {
130		Self::Lookup { hash, len }
131	}
132
133	/// Constructs a `Legacy` bounded item.
134	#[deprecated = "This API is only for transitioning to Scheduler v3 API"]
135	pub fn from_legacy_hash(hash: impl Into<H::Output>) -> Self {
136		Self::Legacy { hash: hash.into(), dummy: core::marker::PhantomData }
137	}
138}
139
140pub type FetchResult = Result<Cow<'static, [u8]>, DispatchError>;
141
142/// A interface for looking up preimages from their hash on chain.
143pub trait QueryPreimage {
144	/// The hasher used in the runtime.
145	type H: Hash;
146
147	/// Returns whether a preimage exists for a given hash and if so its length.
148	fn len(hash: &<Self::H as sp_core::Hasher>::Out) -> Option<u32>;
149
150	/// Returns the preimage for a given hash. If given, `len` must be the size of the preimage.
151	fn fetch(hash: &<Self::H as sp_core::Hasher>::Out, len: Option<u32>) -> FetchResult;
152
153	/// Returns whether a preimage request exists for a given hash.
154	fn is_requested(hash: &<Self::H as sp_core::Hasher>::Out) -> bool;
155
156	/// Request that someone report a preimage. Providers use this to optimise the economics for
157	/// preimage reporting.
158	fn request(hash: &<Self::H as sp_core::Hasher>::Out);
159
160	/// Cancel a previous preimage request.
161	fn unrequest(hash: &<Self::H as sp_core::Hasher>::Out);
162
163	/// Request that the data required for decoding the given `bounded` value is made available.
164	fn hold<T>(bounded: &Bounded<T, Self::H>) {
165		use Bounded::*;
166		match bounded {
167			Inline(..) => {},
168			Legacy { hash, .. } | Lookup { hash, .. } => Self::request(hash),
169		}
170	}
171
172	/// No longer request that the data required for decoding the given `bounded` value is made
173	/// available.
174	fn drop<T>(bounded: &Bounded<T, Self::H>) {
175		use Bounded::*;
176		match bounded {
177			Inline(..) => {},
178			Legacy { hash, .. } | Lookup { hash, .. } => Self::unrequest(hash),
179		}
180	}
181
182	/// Check to see if all data required for the given `bounded` value is available for its
183	/// decoding.
184	fn have<T>(bounded: &Bounded<T, Self::H>) -> bool {
185		use Bounded::*;
186		match bounded {
187			Inline(..) => true,
188			Legacy { hash, .. } | Lookup { hash, .. } => Self::len(hash).is_some(),
189		}
190	}
191
192	/// Create a `Bounded` instance based on the `hash` and `len` of the encoded value.
193	///
194	/// It also directly requests the given `hash` using [`Self::request`].
195	///
196	/// This may not be `peek`-able or `realize`-able.
197	fn pick<T>(hash: <Self::H as sp_core::Hasher>::Out, len: u32) -> Bounded<T, Self::H> {
198		Self::request(&hash);
199		Bounded::Lookup { hash, len }
200	}
201
202	/// Convert the given `bounded` instance back into its original instance, also returning the
203	/// exact size of its encoded form if it needed to be looked-up from a stored preimage).
204	///
205	/// NOTE: This does not remove any data needed for realization. If you will no longer use the
206	/// `bounded`, call `realize` instead or call `drop` afterwards.
207	fn peek<T: Decode>(bounded: &Bounded<T, Self::H>) -> Result<(T, Option<u32>), DispatchError> {
208		use Bounded::*;
209		match bounded {
210			Inline(data) => T::decode(&mut &data[..]).ok().map(|x| (x, None)),
211			Lookup { hash, len } => {
212				let data = Self::fetch(hash, Some(*len))?;
213				T::decode(&mut &data[..]).ok().map(|x| (x, Some(data.len() as u32)))
214			},
215			Legacy { hash, .. } => {
216				let data = Self::fetch(hash, None)?;
217				T::decode(&mut &data[..]).ok().map(|x| (x, Some(data.len() as u32)))
218			},
219		}
220		.ok_or(DispatchError::Corruption)
221	}
222
223	/// Convert the given `bounded` value back into its original instance. If successful,
224	/// `drop` any data backing it. This will not break the realisability of independently
225	/// created instances of `Bounded` which happen to have identical data.
226	fn realize<T: Decode>(
227		bounded: &Bounded<T, Self::H>,
228	) -> Result<(T, Option<u32>), DispatchError> {
229		let r = Self::peek(bounded)?;
230		Self::drop(bounded);
231		Ok(r)
232	}
233}
234
235/// A interface for managing preimages to hashes on chain.
236///
237/// Note that this API does not assume any underlying user is calling, and thus
238/// does not handle any preimage ownership or fees. Other system level logic that
239/// uses this API should implement that on their own side.
240pub trait StorePreimage: QueryPreimage {
241	/// The maximum length of preimage we can store.
242	///
243	/// This is the maximum length of the *encoded* value that can be passed to `bound`.
244	const MAX_LENGTH: usize;
245
246	/// Request and attempt to store the bytes of a preimage on chain.
247	///
248	/// May return `DispatchError::Exhausted` if the preimage is just too big.
249	fn note(bytes: Cow<[u8]>) -> Result<<Self::H as sp_core::Hasher>::Out, DispatchError>;
250
251	/// Attempt to clear a previously noted preimage. Exactly the same as `unrequest` but is
252	/// provided for symmetry.
253	fn unnote(hash: &<Self::H as sp_core::Hasher>::Out) {
254		Self::unrequest(hash)
255	}
256
257	/// Convert an otherwise unbounded or large value into a type ready for placing in storage.
258	///
259	/// The result is a type whose `MaxEncodedLen` is 131 bytes.
260	///
261	/// NOTE: Once this API is used, you should use either `drop` or `realize`.
262	/// The value is also noted using [`Self::note`].
263	fn bound<T: Encode>(t: T) -> Result<Bounded<T, Self::H>, DispatchError> {
264		let data = t.encode();
265		let len = data.len() as u32;
266		Ok(match BoundedInline::try_from(data) {
267			Ok(bounded) => Bounded::Inline(bounded),
268			Err(unbounded) => Bounded::Lookup { hash: Self::note(unbounded.into())?, len },
269		})
270	}
271}
272
273impl QueryPreimage for () {
274	type H = sp_runtime::traits::BlakeTwo256;
275
276	fn len(_: &sp_core::H256) -> Option<u32> {
277		None
278	}
279	fn fetch(_: &sp_core::H256, _: Option<u32>) -> FetchResult {
280		Err(DispatchError::Unavailable)
281	}
282	fn is_requested(_: &sp_core::H256) -> bool {
283		false
284	}
285	fn request(_: &sp_core::H256) {}
286	fn unrequest(_: &sp_core::H256) {}
287}
288
289impl StorePreimage for () {
290	const MAX_LENGTH: usize = 0;
291	fn note(_: Cow<[u8]>) -> Result<sp_core::H256, DispatchError> {
292		Err(DispatchError::Exhausted)
293	}
294}
295
296#[cfg(test)]
297mod tests {
298	use super::*;
299	use crate::BoundedVec;
300	use sp_runtime::{bounded_vec, traits::BlakeTwo256};
301
302	#[test]
303	fn bounded_size_is_correct() {
304		assert_eq!(<Bounded<Vec<u8>, BlakeTwo256> as MaxEncodedLen>::max_encoded_len(), 131);
305	}
306
307	#[test]
308	fn bounded_basic_works() {
309		let data: BoundedVec<u8, _> = bounded_vec![b'a', b'b', b'c'];
310		let len = data.len() as u32;
311		let hash = BlakeTwo256::hash(&data).into();
312
313		// Inline works
314		{
315			let bound: Bounded<Vec<u8>, BlakeTwo256> = Bounded::Inline(data.clone());
316			assert_eq!(bound.hash(), hash);
317			assert_eq!(bound.len(), Some(len));
318			assert!(!bound.lookup_needed());
319			assert_eq!(bound.lookup_len(), None);
320		}
321		// Legacy works
322		{
323			let bound: Bounded<Vec<u8>, BlakeTwo256> =
324				Bounded::Legacy { hash, dummy: Default::default() };
325			assert_eq!(bound.hash(), hash);
326			assert_eq!(bound.len(), None);
327			assert!(bound.lookup_needed());
328			assert_eq!(bound.lookup_len(), Some(1_000_000));
329		}
330		// Lookup works
331		{
332			let bound: Bounded<Vec<u8>, BlakeTwo256> =
333				Bounded::Lookup { hash, len: data.len() as u32 };
334			assert_eq!(bound.hash(), hash);
335			assert_eq!(bound.len(), Some(len));
336			assert!(bound.lookup_needed());
337			assert_eq!(bound.lookup_len(), Some(len));
338		}
339	}
340
341	#[test]
342	fn bounded_transmuting_works() {
343		let data: BoundedVec<u8, _> = bounded_vec![b'a', b'b', b'c'];
344
345		// Transmute a `String` into a `&str`.
346		let x: Bounded<String, BlakeTwo256> = Bounded::Inline(data.clone());
347		let y: Bounded<&str, BlakeTwo256> = x.transmute();
348		assert_eq!(y, Bounded::Inline(data));
349	}
350}