sp_io/
lib.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//! # Substrate Primitives: IO
19//!
20//! This crate contains interfaces for the runtime to communicate with the outside world, ergo `io`.
21//! In other context, such interfaces are referred to as "**host functions**".
22//!
23//! Each set of host functions are defined with an instance of the
24//! [`sp_runtime_interface::runtime_interface`] macro.
25//!
26//! Most notably, this crate contains host functions for:
27//!
28//! - [`hashing`]
29//! - [`crypto`]
30//! - [`trie`]
31//! - [`offchain`]
32//! - [`storage`]
33//! - [`allocator`]
34//! - [`logging`]
35//!
36//! All of the default host functions provided by this crate, and by default contained in all
37//! substrate-based clients are amalgamated in [`SubstrateHostFunctions`].
38//!
39//! ## Externalities
40//!
41//! Host functions go hand in hand with the concept of externalities. Externalities are an
42//! environment in which host functions are provided, and thus can be accessed. Some host functions
43//! are only accessible in an externality environment that provides it.
44//!
45//! A typical error for substrate developers is the following:
46//!
47//! ```should_panic
48//! use sp_io::storage::get;
49//! # fn main() {
50//! let data = get(b"hello world");
51//! # }
52//! ```
53//!
54//! This code will panic with the following error:
55//!
56//! ```no_compile
57//! thread 'main' panicked at '`get_version_1` called outside of an Externalities-provided environment.'
58//! ```
59//!
60//! Such error messages should always be interpreted as "code accessing host functions accessed
61//! outside of externalities".
62//!
63//! An externality is any type that implements [`sp_externalities::Externalities`]. A simple example
64//! of which is [`TestExternalities`], which is commonly used in tests and is exported from this
65//! crate.
66//!
67//! ```
68//! use sp_io::{storage::get, TestExternalities};
69//! # fn main() {
70//! TestExternalities::default().execute_with(|| {
71//! 	let data = get(b"hello world");
72//! });
73//! # }
74//! ```
75
76#![warn(missing_docs)]
77#![cfg_attr(not(feature = "std"), no_std)]
78#![cfg_attr(enable_alloc_error_handler, feature(alloc_error_handler))]
79
80extern crate alloc;
81
82use alloc::vec::Vec;
83
84#[cfg(feature = "std")]
85use tracing;
86
87#[cfg(feature = "std")]
88use sp_core::{
89	crypto::Pair,
90	hexdisplay::HexDisplay,
91	offchain::{OffchainDbExt, OffchainWorkerExt, TransactionPoolExt},
92	storage::ChildInfo,
93};
94#[cfg(feature = "std")]
95use sp_keystore::KeystoreExt;
96
97use sp_core::{
98	crypto::KeyTypeId,
99	ecdsa, ed25519,
100	offchain::{
101		HttpError, HttpRequestId, HttpRequestStatus, OpaqueNetworkState, StorageKind, Timestamp,
102	},
103	sr25519,
104	storage::StateVersion,
105	LogLevel, LogLevelFilter, OpaquePeerId, H256,
106};
107
108#[cfg(feature = "bls-experimental")]
109use sp_core::{bls381, ecdsa_bls381};
110
111#[cfg(feature = "std")]
112use sp_trie::{LayoutV0, LayoutV1, TrieConfiguration};
113
114use sp_runtime_interface::{
115	pass_by::{PassBy, PassByCodec},
116	runtime_interface, Pointer,
117};
118
119use codec::{Decode, Encode};
120
121#[cfg(feature = "std")]
122use secp256k1::{
123	ecdsa::{RecoverableSignature, RecoveryId},
124	Message, SECP256K1,
125};
126
127#[cfg(feature = "std")]
128use sp_externalities::{Externalities, ExternalitiesExt};
129
130pub use sp_externalities::MultiRemovalResults;
131
132#[cfg(all(not(feature = "disable_allocator"), substrate_runtime, target_family = "wasm"))]
133mod global_alloc_wasm;
134
135#[cfg(all(
136	not(feature = "disable_allocator"),
137	substrate_runtime,
138	any(target_arch = "riscv32", target_arch = "riscv64")
139))]
140mod global_alloc_riscv;
141
142#[cfg(feature = "std")]
143const LOG_TARGET: &str = "runtime::io";
144
145/// Error verifying ECDSA signature
146#[derive(Encode, Decode)]
147pub enum EcdsaVerifyError {
148	/// Incorrect value of R or S
149	BadRS,
150	/// Incorrect value of V
151	BadV,
152	/// Invalid signature
153	BadSignature,
154}
155
156/// The outcome of calling `storage_kill`. Returned value is the number of storage items
157/// removed from the backend from making the `storage_kill` call.
158#[derive(PassByCodec, Encode, Decode)]
159pub enum KillStorageResult {
160	/// All keys to remove were removed, return number of iterations performed during the
161	/// operation.
162	AllRemoved(u32),
163	/// Not all key to remove were removed, return number of iterations performed during the
164	/// operation.
165	SomeRemaining(u32),
166}
167
168impl From<MultiRemovalResults> for KillStorageResult {
169	fn from(r: MultiRemovalResults) -> Self {
170		// We use `loops` here rather than `backend` because that's the same as the original
171		// functionality pre-#11490. This won't matter once we switch to the new host function
172		// since we won't be using the `KillStorageResult` type in the runtime any more.
173		match r.maybe_cursor {
174			None => Self::AllRemoved(r.loops),
175			Some(..) => Self::SomeRemaining(r.loops),
176		}
177	}
178}
179
180/// Interface for accessing the storage from within the runtime.
181#[runtime_interface]
182pub trait Storage {
183	/// Returns the data for `key` in the storage or `None` if the key can not be found.
184	fn get(&mut self, key: &[u8]) -> Option<bytes::Bytes> {
185		self.storage(key).map(bytes::Bytes::from)
186	}
187
188	/// Get `key` from storage, placing the value into `value_out` and return the number of
189	/// bytes that the entry in storage has beyond the offset or `None` if the storage entry
190	/// doesn't exist at all.
191	/// If `value_out` length is smaller than the returned length, only `value_out` length bytes
192	/// are copied into `value_out`.
193	fn read(&mut self, key: &[u8], value_out: &mut [u8], value_offset: u32) -> Option<u32> {
194		self.storage(key).map(|value| {
195			let value_offset = value_offset as usize;
196			let data = &value[value_offset.min(value.len())..];
197			let written = std::cmp::min(data.len(), value_out.len());
198			value_out[..written].copy_from_slice(&data[..written]);
199			data.len() as u32
200		})
201	}
202
203	/// Set `key` to `value` in the storage.
204	fn set(&mut self, key: &[u8], value: &[u8]) {
205		self.set_storage(key.to_vec(), value.to_vec());
206	}
207
208	/// Clear the storage of the given `key` and its value.
209	fn clear(&mut self, key: &[u8]) {
210		self.clear_storage(key)
211	}
212
213	/// Check whether the given `key` exists in storage.
214	fn exists(&mut self, key: &[u8]) -> bool {
215		self.exists_storage(key)
216	}
217
218	/// Clear the storage of each key-value pair where the key starts with the given `prefix`.
219	fn clear_prefix(&mut self, prefix: &[u8]) {
220		let _ = Externalities::clear_prefix(*self, prefix, None, None);
221	}
222
223	/// Clear the storage of each key-value pair where the key starts with the given `prefix`.
224	///
225	/// # Limit
226	///
227	/// Deletes all keys from the overlay and up to `limit` keys from the backend if
228	/// it is set to `Some`. No limit is applied when `limit` is set to `None`.
229	///
230	/// The limit can be used to partially delete a prefix storage in case it is too large
231	/// to delete in one go (block).
232	///
233	/// Returns [`KillStorageResult`] to inform about the result.
234	///
235	/// # Note
236	///
237	/// Please note that keys that are residing in the overlay for that prefix when
238	/// issuing this call are all deleted without counting towards the `limit`. Only keys
239	/// written during the current block are part of the overlay. Deleting with a `limit`
240	/// mostly makes sense with an empty overlay for that prefix.
241	///
242	/// Calling this function multiple times per block for the same `prefix` does
243	/// not make much sense because it is not cumulative when called inside the same block.
244	/// The deletion would always start from `prefix` resulting in the same keys being deleted
245	/// every time this function is called with the exact same arguments per block. This happens
246	/// because the keys in the overlay are not taken into account when deleting keys in the
247	/// backend.
248	#[version(2)]
249	fn clear_prefix(&mut self, prefix: &[u8], limit: Option<u32>) -> KillStorageResult {
250		Externalities::clear_prefix(*self, prefix, limit, None).into()
251	}
252
253	/// Partially clear the storage of each key-value pair where the key starts with the given
254	/// prefix.
255	///
256	/// # Limit
257	///
258	/// A *limit* should always be provided through `maybe_limit`. This is one fewer than the
259	/// maximum number of backend iterations which may be done by this operation and as such
260	/// represents the maximum number of backend deletions which may happen. A *limit* of zero
261	/// implies that no keys will be deleted, though there may be a single iteration done.
262	///
263	/// The limit can be used to partially delete a prefix storage in case it is too large or costly
264	/// to delete in a single operation.
265	///
266	/// # Cursor
267	///
268	/// A *cursor* may be passed in to this operation with `maybe_cursor`. `None` should only be
269	/// passed once (in the initial call) for any given `maybe_prefix` value. Subsequent calls
270	/// operating on the same prefix should always pass `Some`, and this should be equal to the
271	/// previous call result's `maybe_cursor` field.
272	///
273	/// Returns [`MultiRemovalResults`](sp_io::MultiRemovalResults) to inform about the result. Once
274	/// the resultant `maybe_cursor` field is `None`, then no further items remain to be deleted.
275	///
276	/// NOTE: After the initial call for any given prefix, it is important that no keys further
277	/// keys under the same prefix are inserted. If so, then they may or may not be deleted by
278	/// subsequent calls.
279	///
280	/// # Note
281	///
282	/// Please note that keys which are residing in the overlay for that prefix when
283	/// issuing this call are deleted without counting towards the `limit`.
284	#[version(3, register_only)]
285	fn clear_prefix(
286		&mut self,
287		maybe_prefix: &[u8],
288		maybe_limit: Option<u32>,
289		maybe_cursor: Option<Vec<u8>>, //< TODO Make work or just Option<Vec<u8>>?
290	) -> MultiRemovalResults {
291		Externalities::clear_prefix(
292			*self,
293			maybe_prefix,
294			maybe_limit,
295			maybe_cursor.as_ref().map(|x| &x[..]),
296		)
297		.into()
298	}
299
300	/// Append the encoded `value` to the storage item at `key`.
301	///
302	/// The storage item needs to implement [`EncodeAppend`](codec::EncodeAppend).
303	///
304	/// # Warning
305	///
306	/// If the storage item does not support [`EncodeAppend`](codec::EncodeAppend) or
307	/// something else fails at appending, the storage item will be set to `[value]`.
308	fn append(&mut self, key: &[u8], value: Vec<u8>) {
309		self.storage_append(key.to_vec(), value);
310	}
311
312	/// "Commit" all existing operations and compute the resulting storage root.
313	///
314	/// The hashing algorithm is defined by the `Block`.
315	///
316	/// Returns a `Vec<u8>` that holds the SCALE encoded hash.
317	fn root(&mut self) -> Vec<u8> {
318		self.storage_root(StateVersion::V0)
319	}
320
321	/// "Commit" all existing operations and compute the resulting storage root.
322	///
323	/// The hashing algorithm is defined by the `Block`.
324	///
325	/// Returns a `Vec<u8>` that holds the SCALE encoded hash.
326	#[version(2)]
327	fn root(&mut self, version: StateVersion) -> Vec<u8> {
328		self.storage_root(version)
329	}
330
331	/// Always returns `None`. This function exists for compatibility reasons.
332	fn changes_root(&mut self, _parent_hash: &[u8]) -> Option<Vec<u8>> {
333		None
334	}
335
336	/// Get the next key in storage after the given one in lexicographic order.
337	fn next_key(&mut self, key: &[u8]) -> Option<Vec<u8>> {
338		self.next_storage_key(key)
339	}
340
341	/// Start a new nested transaction.
342	///
343	/// This allows to either commit or roll back all changes that are made after this call.
344	/// For every transaction there must be a matching call to either `rollback_transaction`
345	/// or `commit_transaction`. This is also effective for all values manipulated using the
346	/// `DefaultChildStorage` API.
347	///
348	/// # Warning
349	///
350	/// This is a low level API that is potentially dangerous as it can easily result
351	/// in unbalanced transactions. For example, FRAME users should use high level storage
352	/// abstractions.
353	fn start_transaction(&mut self) {
354		self.storage_start_transaction();
355	}
356
357	/// Rollback the last transaction started by `start_transaction`.
358	///
359	/// Any changes made during that transaction are discarded.
360	///
361	/// # Panics
362	///
363	/// Will panic if there is no open transaction.
364	fn rollback_transaction(&mut self) {
365		self.storage_rollback_transaction()
366			.expect("No open transaction that can be rolled back.");
367	}
368
369	/// Commit the last transaction started by `start_transaction`.
370	///
371	/// Any changes made during that transaction are committed.
372	///
373	/// # Panics
374	///
375	/// Will panic if there is no open transaction.
376	fn commit_transaction(&mut self) {
377		self.storage_commit_transaction()
378			.expect("No open transaction that can be committed.");
379	}
380}
381
382/// Interface for accessing the child storage for default child trie,
383/// from within the runtime.
384#[runtime_interface]
385pub trait DefaultChildStorage {
386	/// Get a default child storage value for a given key.
387	///
388	/// Parameter `storage_key` is the unprefixed location of the root of the child trie in the
389	/// parent trie. Result is `None` if the value for `key` in the child storage can not be found.
390	fn get(&mut self, storage_key: &[u8], key: &[u8]) -> Option<Vec<u8>> {
391		let child_info = ChildInfo::new_default(storage_key);
392		self.child_storage(&child_info, key).map(|s| s.to_vec())
393	}
394
395	/// Allocation efficient variant of `get`.
396	///
397	/// Get `key` from child storage, placing the value into `value_out` and return the number
398	/// of bytes that the entry in storage has beyond the offset or `None` if the storage entry
399	/// doesn't exist at all.
400	/// If `value_out` length is smaller than the returned length, only `value_out` length bytes
401	/// are copied into `value_out`.
402	fn read(
403		&mut self,
404		storage_key: &[u8],
405		key: &[u8],
406		value_out: &mut [u8],
407		value_offset: u32,
408	) -> Option<u32> {
409		let child_info = ChildInfo::new_default(storage_key);
410		self.child_storage(&child_info, key).map(|value| {
411			let value_offset = value_offset as usize;
412			let data = &value[value_offset.min(value.len())..];
413			let written = std::cmp::min(data.len(), value_out.len());
414			value_out[..written].copy_from_slice(&data[..written]);
415			data.len() as u32
416		})
417	}
418
419	/// Set a child storage value.
420	///
421	/// Set `key` to `value` in the child storage denoted by `storage_key`.
422	fn set(&mut self, storage_key: &[u8], key: &[u8], value: &[u8]) {
423		let child_info = ChildInfo::new_default(storage_key);
424		self.set_child_storage(&child_info, key.to_vec(), value.to_vec());
425	}
426
427	/// Clear a child storage key.
428	///
429	/// For the default child storage at `storage_key`, clear value at `key`.
430	fn clear(&mut self, storage_key: &[u8], key: &[u8]) {
431		let child_info = ChildInfo::new_default(storage_key);
432		self.clear_child_storage(&child_info, key);
433	}
434
435	/// Clear an entire child storage.
436	///
437	/// If it exists, the child storage for `storage_key`
438	/// is removed.
439	fn storage_kill(&mut self, storage_key: &[u8]) {
440		let child_info = ChildInfo::new_default(storage_key);
441		let _ = self.kill_child_storage(&child_info, None, None);
442	}
443
444	/// Clear a child storage key.
445	///
446	/// See `Storage` module `clear_prefix` documentation for `limit` usage.
447	#[version(2)]
448	fn storage_kill(&mut self, storage_key: &[u8], limit: Option<u32>) -> bool {
449		let child_info = ChildInfo::new_default(storage_key);
450		let r = self.kill_child_storage(&child_info, limit, None);
451		r.maybe_cursor.is_none()
452	}
453
454	/// Clear a child storage key.
455	///
456	/// See `Storage` module `clear_prefix` documentation for `limit` usage.
457	#[version(3)]
458	fn storage_kill(&mut self, storage_key: &[u8], limit: Option<u32>) -> KillStorageResult {
459		let child_info = ChildInfo::new_default(storage_key);
460		self.kill_child_storage(&child_info, limit, None).into()
461	}
462
463	/// Clear a child storage key.
464	///
465	/// See `Storage` module `clear_prefix` documentation for `limit` usage.
466	#[version(4, register_only)]
467	fn storage_kill(
468		&mut self,
469		storage_key: &[u8],
470		maybe_limit: Option<u32>,
471		maybe_cursor: Option<Vec<u8>>,
472	) -> MultiRemovalResults {
473		let child_info = ChildInfo::new_default(storage_key);
474		self.kill_child_storage(&child_info, maybe_limit, maybe_cursor.as_ref().map(|x| &x[..]))
475			.into()
476	}
477
478	/// Check a child storage key.
479	///
480	/// Check whether the given `key` exists in default child defined at `storage_key`.
481	fn exists(&mut self, storage_key: &[u8], key: &[u8]) -> bool {
482		let child_info = ChildInfo::new_default(storage_key);
483		self.exists_child_storage(&child_info, key)
484	}
485
486	/// Clear child default key by prefix.
487	///
488	/// Clear the child storage of each key-value pair where the key starts with the given `prefix`.
489	fn clear_prefix(&mut self, storage_key: &[u8], prefix: &[u8]) {
490		let child_info = ChildInfo::new_default(storage_key);
491		let _ = self.clear_child_prefix(&child_info, prefix, None, None);
492	}
493
494	/// Clear the child storage of each key-value pair where the key starts with the given `prefix`.
495	///
496	/// See `Storage` module `clear_prefix` documentation for `limit` usage.
497	#[version(2)]
498	fn clear_prefix(
499		&mut self,
500		storage_key: &[u8],
501		prefix: &[u8],
502		limit: Option<u32>,
503	) -> KillStorageResult {
504		let child_info = ChildInfo::new_default(storage_key);
505		self.clear_child_prefix(&child_info, prefix, limit, None).into()
506	}
507
508	/// Clear the child storage of each key-value pair where the key starts with the given `prefix`.
509	///
510	/// See `Storage` module `clear_prefix` documentation for `limit` usage.
511	#[version(3, register_only)]
512	fn clear_prefix(
513		&mut self,
514		storage_key: &[u8],
515		prefix: &[u8],
516		maybe_limit: Option<u32>,
517		maybe_cursor: Option<Vec<u8>>,
518	) -> MultiRemovalResults {
519		let child_info = ChildInfo::new_default(storage_key);
520		self.clear_child_prefix(
521			&child_info,
522			prefix,
523			maybe_limit,
524			maybe_cursor.as_ref().map(|x| &x[..]),
525		)
526		.into()
527	}
528
529	/// Default child root calculation.
530	///
531	/// "Commit" all existing operations and compute the resulting child storage root.
532	/// The hashing algorithm is defined by the `Block`.
533	///
534	/// Returns a `Vec<u8>` that holds the SCALE encoded hash.
535	fn root(&mut self, storage_key: &[u8]) -> Vec<u8> {
536		let child_info = ChildInfo::new_default(storage_key);
537		self.child_storage_root(&child_info, StateVersion::V0)
538	}
539
540	/// Default child root calculation.
541	///
542	/// "Commit" all existing operations and compute the resulting child storage root.
543	/// The hashing algorithm is defined by the `Block`.
544	///
545	/// Returns a `Vec<u8>` that holds the SCALE encoded hash.
546	#[version(2)]
547	fn root(&mut self, storage_key: &[u8], version: StateVersion) -> Vec<u8> {
548		let child_info = ChildInfo::new_default(storage_key);
549		self.child_storage_root(&child_info, version)
550	}
551
552	/// Child storage key iteration.
553	///
554	/// Get the next key in storage after the given one in lexicographic order in child storage.
555	fn next_key(&mut self, storage_key: &[u8], key: &[u8]) -> Option<Vec<u8>> {
556		let child_info = ChildInfo::new_default(storage_key);
557		self.next_child_storage_key(&child_info, key)
558	}
559}
560
561/// Interface that provides trie related functionality.
562#[runtime_interface]
563pub trait Trie {
564	/// A trie root formed from the iterated items.
565	fn blake2_256_root(input: Vec<(Vec<u8>, Vec<u8>)>) -> H256 {
566		LayoutV0::<sp_core::Blake2Hasher>::trie_root(input)
567	}
568
569	/// A trie root formed from the iterated items.
570	#[version(2)]
571	fn blake2_256_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> H256 {
572		match version {
573			StateVersion::V0 => LayoutV0::<sp_core::Blake2Hasher>::trie_root(input),
574			StateVersion::V1 => LayoutV1::<sp_core::Blake2Hasher>::trie_root(input),
575		}
576	}
577
578	/// A trie root formed from the enumerated items.
579	fn blake2_256_ordered_root(input: Vec<Vec<u8>>) -> H256 {
580		LayoutV0::<sp_core::Blake2Hasher>::ordered_trie_root(input)
581	}
582
583	/// A trie root formed from the enumerated items.
584	#[version(2)]
585	fn blake2_256_ordered_root(input: Vec<Vec<u8>>, version: StateVersion) -> H256 {
586		match version {
587			StateVersion::V0 => LayoutV0::<sp_core::Blake2Hasher>::ordered_trie_root(input),
588			StateVersion::V1 => LayoutV1::<sp_core::Blake2Hasher>::ordered_trie_root(input),
589		}
590	}
591
592	/// A trie root formed from the iterated items.
593	fn keccak_256_root(input: Vec<(Vec<u8>, Vec<u8>)>) -> H256 {
594		LayoutV0::<sp_core::KeccakHasher>::trie_root(input)
595	}
596
597	/// A trie root formed from the iterated items.
598	#[version(2)]
599	fn keccak_256_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> H256 {
600		match version {
601			StateVersion::V0 => LayoutV0::<sp_core::KeccakHasher>::trie_root(input),
602			StateVersion::V1 => LayoutV1::<sp_core::KeccakHasher>::trie_root(input),
603		}
604	}
605
606	/// A trie root formed from the enumerated items.
607	fn keccak_256_ordered_root(input: Vec<Vec<u8>>) -> H256 {
608		LayoutV0::<sp_core::KeccakHasher>::ordered_trie_root(input)
609	}
610
611	/// A trie root formed from the enumerated items.
612	#[version(2)]
613	fn keccak_256_ordered_root(input: Vec<Vec<u8>>, version: StateVersion) -> H256 {
614		match version {
615			StateVersion::V0 => LayoutV0::<sp_core::KeccakHasher>::ordered_trie_root(input),
616			StateVersion::V1 => LayoutV1::<sp_core::KeccakHasher>::ordered_trie_root(input),
617		}
618	}
619
620	/// Verify trie proof
621	fn blake2_256_verify_proof(root: H256, proof: &[Vec<u8>], key: &[u8], value: &[u8]) -> bool {
622		sp_trie::verify_trie_proof::<LayoutV0<sp_core::Blake2Hasher>, _, _, _>(
623			&root,
624			proof,
625			&[(key, Some(value))],
626		)
627		.is_ok()
628	}
629
630	/// Verify trie proof
631	#[version(2)]
632	fn blake2_256_verify_proof(
633		root: H256,
634		proof: &[Vec<u8>],
635		key: &[u8],
636		value: &[u8],
637		version: StateVersion,
638	) -> bool {
639		match version {
640			StateVersion::V0 => sp_trie::verify_trie_proof::<
641				LayoutV0<sp_core::Blake2Hasher>,
642				_,
643				_,
644				_,
645			>(&root, proof, &[(key, Some(value))])
646			.is_ok(),
647			StateVersion::V1 => sp_trie::verify_trie_proof::<
648				LayoutV1<sp_core::Blake2Hasher>,
649				_,
650				_,
651				_,
652			>(&root, proof, &[(key, Some(value))])
653			.is_ok(),
654		}
655	}
656
657	/// Verify trie proof
658	fn keccak_256_verify_proof(root: H256, proof: &[Vec<u8>], key: &[u8], value: &[u8]) -> bool {
659		sp_trie::verify_trie_proof::<LayoutV0<sp_core::KeccakHasher>, _, _, _>(
660			&root,
661			proof,
662			&[(key, Some(value))],
663		)
664		.is_ok()
665	}
666
667	/// Verify trie proof
668	#[version(2)]
669	fn keccak_256_verify_proof(
670		root: H256,
671		proof: &[Vec<u8>],
672		key: &[u8],
673		value: &[u8],
674		version: StateVersion,
675	) -> bool {
676		match version {
677			StateVersion::V0 => sp_trie::verify_trie_proof::<
678				LayoutV0<sp_core::KeccakHasher>,
679				_,
680				_,
681				_,
682			>(&root, proof, &[(key, Some(value))])
683			.is_ok(),
684			StateVersion::V1 => sp_trie::verify_trie_proof::<
685				LayoutV1<sp_core::KeccakHasher>,
686				_,
687				_,
688				_,
689			>(&root, proof, &[(key, Some(value))])
690			.is_ok(),
691		}
692	}
693}
694
695/// Interface that provides miscellaneous functions for communicating between the runtime and the
696/// node.
697#[runtime_interface]
698pub trait Misc {
699	// NOTE: We use the target 'runtime' for messages produced by general printing functions,
700	// instead of LOG_TARGET.
701
702	/// Print a number.
703	fn print_num(val: u64) {
704		log::debug!(target: "runtime", "{}", val);
705	}
706
707	/// Print any valid `utf8` buffer.
708	fn print_utf8(utf8: &[u8]) {
709		if let Ok(data) = std::str::from_utf8(utf8) {
710			log::debug!(target: "runtime", "{}", data)
711		}
712	}
713
714	/// Print any `u8` slice as hex.
715	fn print_hex(data: &[u8]) {
716		log::debug!(target: "runtime", "{}", HexDisplay::from(&data));
717	}
718
719	/// Extract the runtime version of the given wasm blob by calling `Core_version`.
720	///
721	/// Returns `None` if calling the function failed for any reason or `Some(Vec<u8>)` where
722	/// the `Vec<u8>` holds the SCALE encoded runtime version.
723	///
724	/// # Performance
725	///
726	/// This function may be very expensive to call depending on the wasm binary. It may be
727	/// relatively cheap if the wasm binary contains version information. In that case,
728	/// uncompression of the wasm blob is the dominating factor.
729	///
730	/// If the wasm binary does not have the version information attached, then a legacy mechanism
731	/// may be involved. This means that a runtime call will be performed to query the version.
732	///
733	/// Calling into the runtime may be incredible expensive and should be approached with care.
734	fn runtime_version(&mut self, wasm: &[u8]) -> Option<Vec<u8>> {
735		use sp_core::traits::ReadRuntimeVersionExt;
736
737		let mut ext = sp_state_machine::BasicExternalities::default();
738
739		match self
740			.extension::<ReadRuntimeVersionExt>()
741			.expect("No `ReadRuntimeVersionExt` associated for the current context!")
742			.read_runtime_version(wasm, &mut ext)
743		{
744			Ok(v) => Some(v),
745			Err(err) => {
746				log::debug!(
747					target: LOG_TARGET,
748					"cannot read version from the given runtime: {}",
749					err,
750				);
751				None
752			},
753		}
754	}
755}
756
757#[cfg(feature = "std")]
758sp_externalities::decl_extension! {
759	/// Extension to signal to [`crypt::ed25519_verify`] to use the dalek crate.
760	///
761	/// The switch from `ed25519-dalek` to `ed25519-zebra` was a breaking change.
762	/// `ed25519-zebra` is more permissive when it comes to the verification of signatures.
763	/// This means that some chains may fail to sync from genesis when using `ed25519-zebra`.
764	/// So, this extension can be registered to the runtime execution environment to signal
765	/// that `ed25519-dalek` should be used for verification. The extension can be registered
766	/// in the following way:
767	///
768	/// ```nocompile
769	/// client.execution_extensions().set_extensions_factory(
770	/// 	// Let the `UseDalekExt` extension being registered for each runtime invocation
771	/// 	// until the execution happens in the context of block `1000`.
772	/// 	sc_client_api::execution_extensions::ExtensionBeforeBlock::<Block, UseDalekExt>::new(1000)
773	/// );
774	/// ```
775	pub struct UseDalekExt;
776}
777
778#[cfg(feature = "std")]
779impl Default for UseDalekExt {
780	fn default() -> Self {
781		Self
782	}
783}
784
785/// Interfaces for working with crypto related types from within the runtime.
786#[runtime_interface]
787pub trait Crypto {
788	/// Returns all `ed25519` public keys for the given key id from the keystore.
789	fn ed25519_public_keys(&mut self, id: KeyTypeId) -> Vec<ed25519::Public> {
790		self.extension::<KeystoreExt>()
791			.expect("No `keystore` associated for the current context!")
792			.ed25519_public_keys(id)
793	}
794
795	/// Generate an `ed22519` key for the given key type using an optional `seed` and
796	/// store it in the keystore.
797	///
798	/// The `seed` needs to be a valid utf8.
799	///
800	/// Returns the public key.
801	fn ed25519_generate(&mut self, id: KeyTypeId, seed: Option<Vec<u8>>) -> ed25519::Public {
802		let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!"));
803		self.extension::<KeystoreExt>()
804			.expect("No `keystore` associated for the current context!")
805			.ed25519_generate_new(id, seed)
806			.expect("`ed25519_generate` failed")
807	}
808
809	/// Sign the given `msg` with the `ed25519` key that corresponds to the given public key and
810	/// key type in the keystore.
811	///
812	/// Returns the signature.
813	fn ed25519_sign(
814		&mut self,
815		id: KeyTypeId,
816		pub_key: &ed25519::Public,
817		msg: &[u8],
818	) -> Option<ed25519::Signature> {
819		self.extension::<KeystoreExt>()
820			.expect("No `keystore` associated for the current context!")
821			.ed25519_sign(id, pub_key, msg)
822			.ok()
823			.flatten()
824	}
825
826	/// Verify `ed25519` signature.
827	///
828	/// Returns `true` when the verification was successful.
829	fn ed25519_verify(sig: &ed25519::Signature, msg: &[u8], pub_key: &ed25519::Public) -> bool {
830		// We don't want to force everyone needing to call the function in an externalities context.
831		// So, we assume that we should not use dalek when we are not in externalities context.
832		// Otherwise, we check if the extension is present.
833		if sp_externalities::with_externalities(|mut e| e.extension::<UseDalekExt>().is_some())
834			.unwrap_or_default()
835		{
836			use ed25519_dalek::Verifier;
837
838			let Ok(public_key) = ed25519_dalek::VerifyingKey::from_bytes(&pub_key.0) else {
839				return false
840			};
841
842			let sig = ed25519_dalek::Signature::from_bytes(&sig.0);
843
844			public_key.verify(msg, &sig).is_ok()
845		} else {
846			ed25519::Pair::verify(sig, msg, pub_key)
847		}
848	}
849
850	/// Register a `ed25519` signature for batch verification.
851	///
852	/// Batch verification must be enabled by calling [`start_batch_verify`].
853	/// If batch verification is not enabled, the signature will be verified immediately.
854	/// To get the result of the batch verification, [`finish_batch_verify`]
855	/// needs to be called.
856	///
857	/// Returns `true` when the verification is either successful or batched.
858	///
859	/// NOTE: Is tagged with `register_only` to keep the functions around for backwards
860	/// compatibility with old runtimes, but it should not be used anymore by new runtimes.
861	/// The implementation emulates the old behavior, but isn't doing any batch verification
862	/// anymore.
863	#[version(1, register_only)]
864	fn ed25519_batch_verify(
865		&mut self,
866		sig: &ed25519::Signature,
867		msg: &[u8],
868		pub_key: &ed25519::Public,
869	) -> bool {
870		let res = ed25519_verify(sig, msg, pub_key);
871
872		if let Some(ext) = self.extension::<VerificationExtDeprecated>() {
873			ext.0 &= res;
874		}
875
876		res
877	}
878
879	/// Verify `sr25519` signature.
880	///
881	/// Returns `true` when the verification was successful.
882	#[version(2)]
883	fn sr25519_verify(sig: &sr25519::Signature, msg: &[u8], pub_key: &sr25519::Public) -> bool {
884		sr25519::Pair::verify(sig, msg, pub_key)
885	}
886
887	/// Register a `sr25519` signature for batch verification.
888	///
889	/// Batch verification must be enabled by calling [`start_batch_verify`].
890	/// If batch verification is not enabled, the signature will be verified immediately.
891	/// To get the result of the batch verification, [`finish_batch_verify`]
892	/// needs to be called.
893	///
894	/// Returns `true` when the verification is either successful or batched.
895	///
896	/// NOTE: Is tagged with `register_only` to keep the functions around for backwards
897	/// compatibility with old runtimes, but it should not be used anymore by new runtimes.
898	/// The implementation emulates the old behavior, but isn't doing any batch verification
899	/// anymore.
900	#[version(1, register_only)]
901	fn sr25519_batch_verify(
902		&mut self,
903		sig: &sr25519::Signature,
904		msg: &[u8],
905		pub_key: &sr25519::Public,
906	) -> bool {
907		let res = sr25519_verify(sig, msg, pub_key);
908
909		if let Some(ext) = self.extension::<VerificationExtDeprecated>() {
910			ext.0 &= res;
911		}
912
913		res
914	}
915
916	/// Start verification extension.
917	///
918	/// NOTE: Is tagged with `register_only` to keep the functions around for backwards
919	/// compatibility with old runtimes, but it should not be used anymore by new runtimes.
920	/// The implementation emulates the old behavior, but isn't doing any batch verification
921	/// anymore.
922	#[version(1, register_only)]
923	fn start_batch_verify(&mut self) {
924		self.register_extension(VerificationExtDeprecated(true))
925			.expect("Failed to register required extension: `VerificationExt`");
926	}
927
928	/// Finish batch-verification of signatures.
929	///
930	/// Verify or wait for verification to finish for all signatures which were previously
931	/// deferred by `sr25519_verify`/`ed25519_verify`.
932	///
933	/// Will panic if no `VerificationExt` is registered (`start_batch_verify` was not called).
934	///
935	/// NOTE: Is tagged with `register_only` to keep the functions around for backwards
936	/// compatibility with old runtimes, but it should not be used anymore by new runtimes.
937	/// The implementation emulates the old behavior, but isn't doing any batch verification
938	/// anymore.
939	#[version(1, register_only)]
940	fn finish_batch_verify(&mut self) -> bool {
941		let result = self
942			.extension::<VerificationExtDeprecated>()
943			.expect("`finish_batch_verify` should only be called after `start_batch_verify`")
944			.0;
945
946		self.deregister_extension::<VerificationExtDeprecated>()
947			.expect("No verification extension in current context!");
948
949		result
950	}
951
952	/// Returns all `sr25519` public keys for the given key id from the keystore.
953	fn sr25519_public_keys(&mut self, id: KeyTypeId) -> Vec<sr25519::Public> {
954		self.extension::<KeystoreExt>()
955			.expect("No `keystore` associated for the current context!")
956			.sr25519_public_keys(id)
957	}
958
959	/// Generate an `sr22519` key for the given key type using an optional seed and
960	/// store it in the keystore.
961	///
962	/// The `seed` needs to be a valid utf8.
963	///
964	/// Returns the public key.
965	fn sr25519_generate(&mut self, id: KeyTypeId, seed: Option<Vec<u8>>) -> sr25519::Public {
966		let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!"));
967		self.extension::<KeystoreExt>()
968			.expect("No `keystore` associated for the current context!")
969			.sr25519_generate_new(id, seed)
970			.expect("`sr25519_generate` failed")
971	}
972
973	/// Sign the given `msg` with the `sr25519` key that corresponds to the given public key and
974	/// key type in the keystore.
975	///
976	/// Returns the signature.
977	fn sr25519_sign(
978		&mut self,
979		id: KeyTypeId,
980		pub_key: &sr25519::Public,
981		msg: &[u8],
982	) -> Option<sr25519::Signature> {
983		self.extension::<KeystoreExt>()
984			.expect("No `keystore` associated for the current context!")
985			.sr25519_sign(id, pub_key, msg)
986			.ok()
987			.flatten()
988	}
989
990	/// Verify an `sr25519` signature.
991	///
992	/// Returns `true` when the verification in successful regardless of
993	/// signature version.
994	fn sr25519_verify(sig: &sr25519::Signature, msg: &[u8], pubkey: &sr25519::Public) -> bool {
995		sr25519::Pair::verify_deprecated(sig, msg, pubkey)
996	}
997
998	/// Returns all `ecdsa` public keys for the given key id from the keystore.
999	fn ecdsa_public_keys(&mut self, id: KeyTypeId) -> Vec<ecdsa::Public> {
1000		self.extension::<KeystoreExt>()
1001			.expect("No `keystore` associated for the current context!")
1002			.ecdsa_public_keys(id)
1003	}
1004
1005	/// Generate an `ecdsa` key for the given key type using an optional `seed` and
1006	/// store it in the keystore.
1007	///
1008	/// The `seed` needs to be a valid utf8.
1009	///
1010	/// Returns the public key.
1011	fn ecdsa_generate(&mut self, id: KeyTypeId, seed: Option<Vec<u8>>) -> ecdsa::Public {
1012		let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!"));
1013		self.extension::<KeystoreExt>()
1014			.expect("No `keystore` associated for the current context!")
1015			.ecdsa_generate_new(id, seed)
1016			.expect("`ecdsa_generate` failed")
1017	}
1018
1019	/// Sign the given `msg` with the `ecdsa` key that corresponds to the given public key and
1020	/// key type in the keystore.
1021	///
1022	/// Returns the signature.
1023	fn ecdsa_sign(
1024		&mut self,
1025		id: KeyTypeId,
1026		pub_key: &ecdsa::Public,
1027		msg: &[u8],
1028	) -> Option<ecdsa::Signature> {
1029		self.extension::<KeystoreExt>()
1030			.expect("No `keystore` associated for the current context!")
1031			.ecdsa_sign(id, pub_key, msg)
1032			.ok()
1033			.flatten()
1034	}
1035
1036	/// Sign the given a pre-hashed `msg` with the `ecdsa` key that corresponds to the given public
1037	/// key and key type in the keystore.
1038	///
1039	/// Returns the signature.
1040	fn ecdsa_sign_prehashed(
1041		&mut self,
1042		id: KeyTypeId,
1043		pub_key: &ecdsa::Public,
1044		msg: &[u8; 32],
1045	) -> Option<ecdsa::Signature> {
1046		self.extension::<KeystoreExt>()
1047			.expect("No `keystore` associated for the current context!")
1048			.ecdsa_sign_prehashed(id, pub_key, msg)
1049			.ok()
1050			.flatten()
1051	}
1052
1053	/// Verify `ecdsa` signature.
1054	///
1055	/// Returns `true` when the verification was successful.
1056	/// This version is able to handle, non-standard, overflowing signatures.
1057	fn ecdsa_verify(sig: &ecdsa::Signature, msg: &[u8], pub_key: &ecdsa::Public) -> bool {
1058		#[allow(deprecated)]
1059		ecdsa::Pair::verify_deprecated(sig, msg, pub_key)
1060	}
1061
1062	/// Verify `ecdsa` signature.
1063	///
1064	/// Returns `true` when the verification was successful.
1065	#[version(2)]
1066	fn ecdsa_verify(sig: &ecdsa::Signature, msg: &[u8], pub_key: &ecdsa::Public) -> bool {
1067		ecdsa::Pair::verify(sig, msg, pub_key)
1068	}
1069
1070	/// Verify `ecdsa` signature with pre-hashed `msg`.
1071	///
1072	/// Returns `true` when the verification was successful.
1073	fn ecdsa_verify_prehashed(
1074		sig: &ecdsa::Signature,
1075		msg: &[u8; 32],
1076		pub_key: &ecdsa::Public,
1077	) -> bool {
1078		ecdsa::Pair::verify_prehashed(sig, msg, pub_key)
1079	}
1080
1081	/// Register a `ecdsa` signature for batch verification.
1082	///
1083	/// Batch verification must be enabled by calling [`start_batch_verify`].
1084	/// If batch verification is not enabled, the signature will be verified immediately.
1085	/// To get the result of the batch verification, [`finish_batch_verify`]
1086	/// needs to be called.
1087	///
1088	/// Returns `true` when the verification is either successful or batched.
1089	///
1090	/// NOTE: Is tagged with `register_only` to keep the functions around for backwards
1091	/// compatibility with old runtimes, but it should not be used anymore by new runtimes.
1092	/// The implementation emulates the old behavior, but isn't doing any batch verification
1093	/// anymore.
1094	#[version(1, register_only)]
1095	fn ecdsa_batch_verify(
1096		&mut self,
1097		sig: &ecdsa::Signature,
1098		msg: &[u8],
1099		pub_key: &ecdsa::Public,
1100	) -> bool {
1101		let res = ecdsa_verify(sig, msg, pub_key);
1102
1103		if let Some(ext) = self.extension::<VerificationExtDeprecated>() {
1104			ext.0 &= res;
1105		}
1106
1107		res
1108	}
1109
1110	/// Verify and recover a SECP256k1 ECDSA signature.
1111	///
1112	/// - `sig` is passed in RSV format. V should be either `0/1` or `27/28`.
1113	/// - `msg` is the blake2-256 hash of the message.
1114	///
1115	/// Returns `Err` if the signature is bad, otherwise the 64-byte pubkey
1116	/// (doesn't include the 0x04 prefix).
1117	/// This version is able to handle, non-standard, overflowing signatures.
1118	fn secp256k1_ecdsa_recover(
1119		sig: &[u8; 65],
1120		msg: &[u8; 32],
1121	) -> Result<[u8; 64], EcdsaVerifyError> {
1122		let rid = libsecp256k1::RecoveryId::parse(
1123			if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as u8,
1124		)
1125		.map_err(|_| EcdsaVerifyError::BadV)?;
1126		let sig = libsecp256k1::Signature::parse_overflowing_slice(&sig[..64])
1127			.map_err(|_| EcdsaVerifyError::BadRS)?;
1128		let msg = libsecp256k1::Message::parse(msg);
1129		let pubkey =
1130			libsecp256k1::recover(&msg, &sig, &rid).map_err(|_| EcdsaVerifyError::BadSignature)?;
1131		let mut res = [0u8; 64];
1132		res.copy_from_slice(&pubkey.serialize()[1..65]);
1133		Ok(res)
1134	}
1135
1136	/// Verify and recover a SECP256k1 ECDSA signature.
1137	///
1138	/// - `sig` is passed in RSV format. V should be either `0/1` or `27/28`.
1139	/// - `msg` is the blake2-256 hash of the message.
1140	///
1141	/// Returns `Err` if the signature is bad, otherwise the 64-byte pubkey
1142	/// (doesn't include the 0x04 prefix).
1143	#[version(2)]
1144	fn secp256k1_ecdsa_recover(
1145		sig: &[u8; 65],
1146		msg: &[u8; 32],
1147	) -> Result<[u8; 64], EcdsaVerifyError> {
1148		let rid = RecoveryId::from_i32(if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as i32)
1149			.map_err(|_| EcdsaVerifyError::BadV)?;
1150		let sig = RecoverableSignature::from_compact(&sig[..64], rid)
1151			.map_err(|_| EcdsaVerifyError::BadRS)?;
1152		let msg = Message::from_digest_slice(msg).expect("Message is 32 bytes; qed");
1153		let pubkey = SECP256K1
1154			.recover_ecdsa(&msg, &sig)
1155			.map_err(|_| EcdsaVerifyError::BadSignature)?;
1156		let mut res = [0u8; 64];
1157		res.copy_from_slice(&pubkey.serialize_uncompressed()[1..]);
1158		Ok(res)
1159	}
1160
1161	/// Verify and recover a SECP256k1 ECDSA signature.
1162	///
1163	/// - `sig` is passed in RSV format. V should be either `0/1` or `27/28`.
1164	/// - `msg` is the blake2-256 hash of the message.
1165	///
1166	/// Returns `Err` if the signature is bad, otherwise the 33-byte compressed pubkey.
1167	fn secp256k1_ecdsa_recover_compressed(
1168		sig: &[u8; 65],
1169		msg: &[u8; 32],
1170	) -> Result<[u8; 33], EcdsaVerifyError> {
1171		let rid = libsecp256k1::RecoveryId::parse(
1172			if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as u8,
1173		)
1174		.map_err(|_| EcdsaVerifyError::BadV)?;
1175		let sig = libsecp256k1::Signature::parse_overflowing_slice(&sig[0..64])
1176			.map_err(|_| EcdsaVerifyError::BadRS)?;
1177		let msg = libsecp256k1::Message::parse(msg);
1178		let pubkey =
1179			libsecp256k1::recover(&msg, &sig, &rid).map_err(|_| EcdsaVerifyError::BadSignature)?;
1180		Ok(pubkey.serialize_compressed())
1181	}
1182
1183	/// Verify and recover a SECP256k1 ECDSA signature.
1184	///
1185	/// - `sig` is passed in RSV format. V should be either `0/1` or `27/28`.
1186	/// - `msg` is the blake2-256 hash of the message.
1187	///
1188	/// Returns `Err` if the signature is bad, otherwise the 33-byte compressed pubkey.
1189	#[version(2)]
1190	fn secp256k1_ecdsa_recover_compressed(
1191		sig: &[u8; 65],
1192		msg: &[u8; 32],
1193	) -> Result<[u8; 33], EcdsaVerifyError> {
1194		let rid = RecoveryId::from_i32(if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as i32)
1195			.map_err(|_| EcdsaVerifyError::BadV)?;
1196		let sig = RecoverableSignature::from_compact(&sig[..64], rid)
1197			.map_err(|_| EcdsaVerifyError::BadRS)?;
1198		let msg = Message::from_digest_slice(msg).expect("Message is 32 bytes; qed");
1199		let pubkey = SECP256K1
1200			.recover_ecdsa(&msg, &sig)
1201			.map_err(|_| EcdsaVerifyError::BadSignature)?;
1202		Ok(pubkey.serialize())
1203	}
1204
1205	/// Generate an `bls12-381` key for the given key type using an optional `seed` and
1206	/// store it in the keystore.
1207	///
1208	/// The `seed` needs to be a valid utf8.
1209	///
1210	/// Returns the public key.
1211	#[cfg(feature = "bls-experimental")]
1212	fn bls381_generate(&mut self, id: KeyTypeId, seed: Option<Vec<u8>>) -> bls381::Public {
1213		let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!"));
1214		self.extension::<KeystoreExt>()
1215			.expect("No `keystore` associated for the current context!")
1216			.bls381_generate_new(id, seed)
1217			.expect("`bls381_generate` failed")
1218	}
1219
1220	/// Generate an `(ecdsa,bls12-381)` key for the given key type using an optional `seed` and
1221	/// store it in the keystore.
1222	///
1223	/// The `seed` needs to be a valid utf8.
1224	///
1225	/// Returns the public key.
1226	#[cfg(feature = "bls-experimental")]
1227	fn ecdsa_bls381_generate(
1228		&mut self,
1229		id: KeyTypeId,
1230		seed: Option<Vec<u8>>,
1231	) -> ecdsa_bls381::Public {
1232		let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!"));
1233		self.extension::<KeystoreExt>()
1234			.expect("No `keystore` associated for the current context!")
1235			.ecdsa_bls381_generate_new(id, seed)
1236			.expect("`ecdsa_bls381_generate` failed")
1237	}
1238}
1239
1240/// Interface that provides functions for hashing with different algorithms.
1241#[runtime_interface]
1242pub trait Hashing {
1243	/// Conduct a 256-bit Keccak hash.
1244	fn keccak_256(data: &[u8]) -> [u8; 32] {
1245		sp_crypto_hashing::keccak_256(data)
1246	}
1247
1248	/// Conduct a 512-bit Keccak hash.
1249	fn keccak_512(data: &[u8]) -> [u8; 64] {
1250		sp_crypto_hashing::keccak_512(data)
1251	}
1252
1253	/// Conduct a 256-bit Sha2 hash.
1254	fn sha2_256(data: &[u8]) -> [u8; 32] {
1255		sp_crypto_hashing::sha2_256(data)
1256	}
1257
1258	/// Conduct a 128-bit Blake2 hash.
1259	fn blake2_128(data: &[u8]) -> [u8; 16] {
1260		sp_crypto_hashing::blake2_128(data)
1261	}
1262
1263	/// Conduct a 256-bit Blake2 hash.
1264	fn blake2_256(data: &[u8]) -> [u8; 32] {
1265		sp_crypto_hashing::blake2_256(data)
1266	}
1267
1268	/// Conduct four XX hashes to give a 256-bit result.
1269	fn twox_256(data: &[u8]) -> [u8; 32] {
1270		sp_crypto_hashing::twox_256(data)
1271	}
1272
1273	/// Conduct two XX hashes to give a 128-bit result.
1274	fn twox_128(data: &[u8]) -> [u8; 16] {
1275		sp_crypto_hashing::twox_128(data)
1276	}
1277
1278	/// Conduct two XX hashes to give a 64-bit result.
1279	fn twox_64(data: &[u8]) -> [u8; 8] {
1280		sp_crypto_hashing::twox_64(data)
1281	}
1282}
1283
1284/// Interface that provides transaction indexing API.
1285#[runtime_interface]
1286pub trait TransactionIndex {
1287	/// Add transaction index. Returns indexed content hash.
1288	fn index(&mut self, extrinsic: u32, size: u32, context_hash: [u8; 32]) {
1289		self.storage_index_transaction(extrinsic, &context_hash, size);
1290	}
1291
1292	/// Conduct a 512-bit Keccak hash.
1293	fn renew(&mut self, extrinsic: u32, context_hash: [u8; 32]) {
1294		self.storage_renew_transaction_index(extrinsic, &context_hash);
1295	}
1296}
1297
1298/// Interface that provides functions to access the Offchain DB.
1299#[runtime_interface]
1300pub trait OffchainIndex {
1301	/// Write a key value pair to the Offchain DB database in a buffered fashion.
1302	fn set(&mut self, key: &[u8], value: &[u8]) {
1303		self.set_offchain_storage(key, Some(value));
1304	}
1305
1306	/// Remove a key and its associated value from the Offchain DB.
1307	fn clear(&mut self, key: &[u8]) {
1308		self.set_offchain_storage(key, None);
1309	}
1310}
1311
1312#[cfg(feature = "std")]
1313sp_externalities::decl_extension! {
1314	/// Deprecated verification context.
1315	///
1316	/// Stores the combined result of all verifications that are done in the same context.
1317	struct VerificationExtDeprecated(bool);
1318}
1319
1320/// Interface that provides functions to access the offchain functionality.
1321///
1322/// These functions are being made available to the runtime and are called by the runtime.
1323#[runtime_interface]
1324pub trait Offchain {
1325	/// Returns if the local node is a potential validator.
1326	///
1327	/// Even if this function returns `true`, it does not mean that any keys are configured
1328	/// and that the validator is registered in the chain.
1329	fn is_validator(&mut self) -> bool {
1330		self.extension::<OffchainWorkerExt>()
1331			.expect("is_validator can be called only in the offchain worker context")
1332			.is_validator()
1333	}
1334
1335	/// Submit an encoded transaction to the pool.
1336	///
1337	/// The transaction will end up in the pool.
1338	fn submit_transaction(&mut self, data: Vec<u8>) -> Result<(), ()> {
1339		self.extension::<TransactionPoolExt>()
1340			.expect(
1341				"submit_transaction can be called only in the offchain call context with
1342				TransactionPool capabilities enabled",
1343			)
1344			.submit_transaction(data)
1345	}
1346
1347	/// Returns information about the local node's network state.
1348	fn network_state(&mut self) -> Result<OpaqueNetworkState, ()> {
1349		self.extension::<OffchainWorkerExt>()
1350			.expect("network_state can be called only in the offchain worker context")
1351			.network_state()
1352	}
1353
1354	/// Returns current UNIX timestamp (in millis)
1355	fn timestamp(&mut self) -> Timestamp {
1356		self.extension::<OffchainWorkerExt>()
1357			.expect("timestamp can be called only in the offchain worker context")
1358			.timestamp()
1359	}
1360
1361	/// Pause the execution until `deadline` is reached.
1362	fn sleep_until(&mut self, deadline: Timestamp) {
1363		self.extension::<OffchainWorkerExt>()
1364			.expect("sleep_until can be called only in the offchain worker context")
1365			.sleep_until(deadline)
1366	}
1367
1368	/// Returns a random seed.
1369	///
1370	/// This is a truly random, non-deterministic seed generated by host environment.
1371	/// Obviously fine in the off-chain worker context.
1372	fn random_seed(&mut self) -> [u8; 32] {
1373		self.extension::<OffchainWorkerExt>()
1374			.expect("random_seed can be called only in the offchain worker context")
1375			.random_seed()
1376	}
1377
1378	/// Sets a value in the local storage.
1379	///
1380	/// Note this storage is not part of the consensus, it's only accessible by
1381	/// offchain worker tasks running on the same machine. It IS persisted between runs.
1382	fn local_storage_set(&mut self, kind: StorageKind, key: &[u8], value: &[u8]) {
1383		self.extension::<OffchainDbExt>()
1384			.expect(
1385				"local_storage_set can be called only in the offchain call context with
1386				OffchainDb extension",
1387			)
1388			.local_storage_set(kind, key, value)
1389	}
1390
1391	/// Remove a value from the local storage.
1392	///
1393	/// Note this storage is not part of the consensus, it's only accessible by
1394	/// offchain worker tasks running on the same machine. It IS persisted between runs.
1395	fn local_storage_clear(&mut self, kind: StorageKind, key: &[u8]) {
1396		self.extension::<OffchainDbExt>()
1397			.expect(
1398				"local_storage_clear can be called only in the offchain call context with
1399				OffchainDb extension",
1400			)
1401			.local_storage_clear(kind, key)
1402	}
1403
1404	/// Sets a value in the local storage if it matches current value.
1405	///
1406	/// Since multiple offchain workers may be running concurrently, to prevent
1407	/// data races use CAS to coordinate between them.
1408	///
1409	/// Returns `true` if the value has been set, `false` otherwise.
1410	///
1411	/// Note this storage is not part of the consensus, it's only accessible by
1412	/// offchain worker tasks running on the same machine. It IS persisted between runs.
1413	fn local_storage_compare_and_set(
1414		&mut self,
1415		kind: StorageKind,
1416		key: &[u8],
1417		old_value: Option<Vec<u8>>,
1418		new_value: &[u8],
1419	) -> bool {
1420		self.extension::<OffchainDbExt>()
1421			.expect(
1422				"local_storage_compare_and_set can be called only in the offchain call context
1423				with OffchainDb extension",
1424			)
1425			.local_storage_compare_and_set(kind, key, old_value.as_deref(), new_value)
1426	}
1427
1428	/// Gets a value from the local storage.
1429	///
1430	/// If the value does not exist in the storage `None` will be returned.
1431	/// Note this storage is not part of the consensus, it's only accessible by
1432	/// offchain worker tasks running on the same machine. It IS persisted between runs.
1433	fn local_storage_get(&mut self, kind: StorageKind, key: &[u8]) -> Option<Vec<u8>> {
1434		self.extension::<OffchainDbExt>()
1435			.expect(
1436				"local_storage_get can be called only in the offchain call context with
1437				OffchainDb extension",
1438			)
1439			.local_storage_get(kind, key)
1440	}
1441
1442	/// Initiates a http request given HTTP verb and the URL.
1443	///
1444	/// Meta is a future-reserved field containing additional, parity-scale-codec encoded
1445	/// parameters. Returns the id of newly started request.
1446	fn http_request_start(
1447		&mut self,
1448		method: &str,
1449		uri: &str,
1450		meta: &[u8],
1451	) -> Result<HttpRequestId, ()> {
1452		self.extension::<OffchainWorkerExt>()
1453			.expect("http_request_start can be called only in the offchain worker context")
1454			.http_request_start(method, uri, meta)
1455	}
1456
1457	/// Append header to the request.
1458	fn http_request_add_header(
1459		&mut self,
1460		request_id: HttpRequestId,
1461		name: &str,
1462		value: &str,
1463	) -> Result<(), ()> {
1464		self.extension::<OffchainWorkerExt>()
1465			.expect("http_request_add_header can be called only in the offchain worker context")
1466			.http_request_add_header(request_id, name, value)
1467	}
1468
1469	/// Write a chunk of request body.
1470	///
1471	/// Writing an empty chunks finalizes the request.
1472	/// Passing `None` as deadline blocks forever.
1473	///
1474	/// Returns an error in case deadline is reached or the chunk couldn't be written.
1475	fn http_request_write_body(
1476		&mut self,
1477		request_id: HttpRequestId,
1478		chunk: &[u8],
1479		deadline: Option<Timestamp>,
1480	) -> Result<(), HttpError> {
1481		self.extension::<OffchainWorkerExt>()
1482			.expect("http_request_write_body can be called only in the offchain worker context")
1483			.http_request_write_body(request_id, chunk, deadline)
1484	}
1485
1486	/// Block and wait for the responses for given requests.
1487	///
1488	/// Returns a vector of request statuses (the len is the same as ids).
1489	/// Note that if deadline is not provided the method will block indefinitely,
1490	/// otherwise unready responses will produce `DeadlineReached` status.
1491	///
1492	/// Passing `None` as deadline blocks forever.
1493	fn http_response_wait(
1494		&mut self,
1495		ids: &[HttpRequestId],
1496		deadline: Option<Timestamp>,
1497	) -> Vec<HttpRequestStatus> {
1498		self.extension::<OffchainWorkerExt>()
1499			.expect("http_response_wait can be called only in the offchain worker context")
1500			.http_response_wait(ids, deadline)
1501	}
1502
1503	/// Read all response headers.
1504	///
1505	/// Returns a vector of pairs `(HeaderKey, HeaderValue)`.
1506	/// NOTE: response headers have to be read before response body.
1507	fn http_response_headers(&mut self, request_id: HttpRequestId) -> Vec<(Vec<u8>, Vec<u8>)> {
1508		self.extension::<OffchainWorkerExt>()
1509			.expect("http_response_headers can be called only in the offchain worker context")
1510			.http_response_headers(request_id)
1511	}
1512
1513	/// Read a chunk of body response to given buffer.
1514	///
1515	/// Returns the number of bytes written or an error in case a deadline
1516	/// is reached or server closed the connection.
1517	/// If `0` is returned it means that the response has been fully consumed
1518	/// and the `request_id` is now invalid.
1519	/// NOTE: this implies that response headers must be read before draining the body.
1520	/// Passing `None` as a deadline blocks forever.
1521	fn http_response_read_body(
1522		&mut self,
1523		request_id: HttpRequestId,
1524		buffer: &mut [u8],
1525		deadline: Option<Timestamp>,
1526	) -> Result<u32, HttpError> {
1527		self.extension::<OffchainWorkerExt>()
1528			.expect("http_response_read_body can be called only in the offchain worker context")
1529			.http_response_read_body(request_id, buffer, deadline)
1530			.map(|r| r as u32)
1531	}
1532
1533	/// Set the authorized nodes and authorized_only flag.
1534	fn set_authorized_nodes(&mut self, nodes: Vec<OpaquePeerId>, authorized_only: bool) {
1535		self.extension::<OffchainWorkerExt>()
1536			.expect("set_authorized_nodes can be called only in the offchain worker context")
1537			.set_authorized_nodes(nodes, authorized_only)
1538	}
1539}
1540
1541/// Wasm only interface that provides functions for calling into the allocator.
1542#[runtime_interface(wasm_only)]
1543pub trait Allocator {
1544	/// Malloc the given number of bytes and return the pointer to the allocated memory location.
1545	fn malloc(&mut self, size: u32) -> Pointer<u8> {
1546		self.allocate_memory(size).expect("Failed to allocate memory")
1547	}
1548
1549	/// Free the given pointer.
1550	fn free(&mut self, ptr: Pointer<u8>) {
1551		self.deallocate_memory(ptr).expect("Failed to deallocate memory")
1552	}
1553}
1554
1555/// WASM-only interface which allows for aborting the execution in case
1556/// of an unrecoverable error.
1557#[runtime_interface(wasm_only)]
1558pub trait PanicHandler {
1559	/// Aborts the current execution with the given error message.
1560	#[trap_on_return]
1561	fn abort_on_panic(&mut self, message: &str) {
1562		self.register_panic_error_message(message);
1563	}
1564}
1565
1566/// Interface that provides functions for logging from within the runtime.
1567#[runtime_interface]
1568pub trait Logging {
1569	/// Request to print a log message on the host.
1570	///
1571	/// Note that this will be only displayed if the host is enabled to display log messages with
1572	/// given level and target.
1573	///
1574	/// Instead of using directly, prefer setting up `RuntimeLogger` and using `log` macros.
1575	fn log(level: LogLevel, target: &str, message: &[u8]) {
1576		if let Ok(message) = std::str::from_utf8(message) {
1577			log::log!(target: target, log::Level::from(level), "{}", message)
1578		}
1579	}
1580
1581	/// Returns the max log level used by the host.
1582	fn max_level() -> LogLevelFilter {
1583		log::max_level().into()
1584	}
1585}
1586
1587#[derive(Encode, Decode)]
1588/// Crossing is a helper wrapping any Encode-Decodeable type
1589/// for transferring over the wasm barrier.
1590pub struct Crossing<T: Encode + Decode>(T);
1591
1592impl<T: Encode + Decode> PassBy for Crossing<T> {
1593	type PassBy = sp_runtime_interface::pass_by::Codec<Self>;
1594}
1595
1596impl<T: Encode + Decode> Crossing<T> {
1597	/// Convert into the inner type
1598	pub fn into_inner(self) -> T {
1599		self.0
1600	}
1601}
1602
1603// useful for testing
1604impl<T> core::default::Default for Crossing<T>
1605where
1606	T: core::default::Default + Encode + Decode,
1607{
1608	fn default() -> Self {
1609		Self(Default::default())
1610	}
1611}
1612
1613/// Interface to provide tracing facilities for wasm. Modelled after tokios `tracing`-crate
1614/// interfaces. See `sp-tracing` for more information.
1615#[runtime_interface(wasm_only, no_tracing)]
1616pub trait WasmTracing {
1617	/// Whether the span described in `WasmMetadata` should be traced wasm-side
1618	/// On the host converts into a static Metadata and checks against the global `tracing`
1619	/// dispatcher.
1620	///
1621	/// When returning false the calling code should skip any tracing-related execution. In general
1622	/// within the same block execution this is not expected to change and it doesn't have to be
1623	/// checked more than once per metadata. This exists for optimisation purposes but is still not
1624	/// cheap as it will jump the wasm-native-barrier every time it is called. So an implementation
1625	/// might chose to cache the result for the execution of the entire block.
1626	fn enabled(&mut self, metadata: Crossing<sp_tracing::WasmMetadata>) -> bool {
1627		let metadata: &tracing_core::metadata::Metadata<'static> = (&metadata.into_inner()).into();
1628		tracing::dispatcher::get_default(|d| d.enabled(metadata))
1629	}
1630
1631	/// Open a new span with the given attributes. Return the u64 Id of the span.
1632	///
1633	/// On the native side this goes through the default `tracing` dispatcher to register the span
1634	/// and then calls `clone_span` with the ID to signal that we are keeping it around on the wasm-
1635	/// side even after the local span is dropped. The resulting ID is then handed over to the wasm-
1636	/// side.
1637	fn enter_span(&mut self, span: Crossing<sp_tracing::WasmEntryAttributes>) -> u64 {
1638		let span: tracing::Span = span.into_inner().into();
1639		match span.id() {
1640			Some(id) => tracing::dispatcher::get_default(|d| {
1641				// inform dispatch that we'll keep the ID around
1642				// then enter it immediately
1643				let final_id = d.clone_span(&id);
1644				d.enter(&final_id);
1645				final_id.into_u64()
1646			}),
1647			_ => 0,
1648		}
1649	}
1650
1651	/// Emit the given event to the global tracer on the native side
1652	fn event(&mut self, event: Crossing<sp_tracing::WasmEntryAttributes>) {
1653		event.into_inner().emit();
1654	}
1655
1656	/// Signal that a given span-id has been exited. On native, this directly
1657	/// proxies the span to the global dispatcher.
1658	fn exit(&mut self, span: u64) {
1659		tracing::dispatcher::get_default(|d| {
1660			let id = tracing_core::span::Id::from_u64(span);
1661			d.exit(&id);
1662		});
1663	}
1664}
1665
1666#[cfg(all(not(feature = "std"), feature = "with-tracing"))]
1667mod tracing_setup {
1668	use super::{wasm_tracing, Crossing};
1669	use core::sync::atomic::{AtomicBool, Ordering};
1670	use tracing_core::{
1671		dispatcher::{set_global_default, Dispatch},
1672		span::{Attributes, Id, Record},
1673		Event, Metadata,
1674	};
1675
1676	static TRACING_SET: AtomicBool = AtomicBool::new(false);
1677
1678	/// The PassingTracingSubscriber implements `tracing_core::Subscriber`
1679	/// and pushes the information across the runtime interface to the host
1680	struct PassingTracingSubscriber;
1681
1682	impl tracing_core::Subscriber for PassingTracingSubscriber {
1683		fn enabled(&self, metadata: &Metadata<'_>) -> bool {
1684			wasm_tracing::enabled(Crossing(metadata.into()))
1685		}
1686		fn new_span(&self, attrs: &Attributes<'_>) -> Id {
1687			Id::from_u64(wasm_tracing::enter_span(Crossing(attrs.into())))
1688		}
1689		fn enter(&self, _: &Id) {
1690			// Do nothing, we already entered the span previously
1691		}
1692		/// Not implemented! We do not support recording values later
1693		/// Will panic when used.
1694		fn record(&self, _: &Id, _: &Record<'_>) {
1695			unimplemented! {} // this usage is not supported
1696		}
1697		/// Not implemented! We do not support recording values later
1698		/// Will panic when used.
1699		fn record_follows_from(&self, _: &Id, _: &Id) {
1700			unimplemented! {} // this usage is not supported
1701		}
1702		fn event(&self, event: &Event<'_>) {
1703			wasm_tracing::event(Crossing(event.into()))
1704		}
1705		fn exit(&self, span: &Id) {
1706			wasm_tracing::exit(span.into_u64())
1707		}
1708	}
1709
1710	/// Initialize tracing of sp_tracing on wasm with `with-tracing` enabled.
1711	/// Can be called multiple times from within the same process and will only
1712	/// set the global bridging subscriber once.
1713	pub fn init_tracing() {
1714		if TRACING_SET.load(Ordering::Relaxed) == false {
1715			set_global_default(Dispatch::new(PassingTracingSubscriber {}))
1716				.expect("We only ever call this once");
1717			TRACING_SET.store(true, Ordering::Relaxed);
1718		}
1719	}
1720}
1721
1722#[cfg(not(all(not(feature = "std"), feature = "with-tracing")))]
1723mod tracing_setup {
1724	/// Initialize tracing of sp_tracing not necessary – noop. To enable build
1725	/// without std and with the `with-tracing`-feature.
1726	pub fn init_tracing() {}
1727}
1728
1729pub use tracing_setup::init_tracing;
1730
1731/// Crashes the execution of the program.
1732///
1733/// Equivalent to the WASM `unreachable` instruction, RISC-V `unimp` instruction,
1734/// or just the `unreachable!()` macro everywhere else.
1735pub fn unreachable() -> ! {
1736	#[cfg(target_family = "wasm")]
1737	{
1738		core::arch::wasm32::unreachable();
1739	}
1740
1741	#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
1742	unsafe {
1743		core::arch::asm!("unimp", options(noreturn));
1744	}
1745
1746	#[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64", target_family = "wasm")))]
1747	unreachable!();
1748}
1749
1750/// A default panic handler for the runtime environment.
1751#[cfg(all(not(feature = "disable_panic_handler"), substrate_runtime))]
1752#[panic_handler]
1753pub fn panic(info: &core::panic::PanicInfo) -> ! {
1754	let message = alloc::format!("{}", info);
1755	#[cfg(feature = "improved_panic_error_reporting")]
1756	{
1757		panic_handler::abort_on_panic(&message);
1758	}
1759	#[cfg(not(feature = "improved_panic_error_reporting"))]
1760	{
1761		logging::log(LogLevel::Error, "runtime", message.as_bytes());
1762		unreachable();
1763	}
1764}
1765
1766/// A default OOM handler for the runtime environment.
1767#[cfg(all(not(feature = "disable_oom"), enable_alloc_error_handler))]
1768#[alloc_error_handler]
1769pub fn oom(_: core::alloc::Layout) -> ! {
1770	#[cfg(feature = "improved_panic_error_reporting")]
1771	{
1772		panic_handler::abort_on_panic("Runtime memory exhausted.");
1773	}
1774	#[cfg(not(feature = "improved_panic_error_reporting"))]
1775	{
1776		logging::log(LogLevel::Error, "runtime", b"Runtime memory exhausted. Aborting");
1777		unreachable();
1778	}
1779}
1780
1781/// Type alias for Externalities implementation used in tests.
1782#[cfg(feature = "std")]
1783pub type TestExternalities = sp_state_machine::TestExternalities<sp_core::Blake2Hasher>;
1784
1785/// The host functions Substrate provides for the Wasm runtime environment.
1786///
1787/// All these host functions will be callable from inside the Wasm environment.
1788#[docify::export]
1789#[cfg(feature = "std")]
1790pub type SubstrateHostFunctions = (
1791	storage::HostFunctions,
1792	default_child_storage::HostFunctions,
1793	misc::HostFunctions,
1794	wasm_tracing::HostFunctions,
1795	offchain::HostFunctions,
1796	crypto::HostFunctions,
1797	hashing::HostFunctions,
1798	allocator::HostFunctions,
1799	panic_handler::HostFunctions,
1800	logging::HostFunctions,
1801	crate::trie::HostFunctions,
1802	offchain_index::HostFunctions,
1803	transaction_index::HostFunctions,
1804);
1805
1806#[cfg(test)]
1807mod tests {
1808	use super::*;
1809	use sp_core::{crypto::UncheckedInto, map, storage::Storage};
1810	use sp_state_machine::BasicExternalities;
1811
1812	#[test]
1813	fn storage_works() {
1814		let mut t = BasicExternalities::default();
1815		t.execute_with(|| {
1816			assert_eq!(storage::get(b"hello"), None);
1817			storage::set(b"hello", b"world");
1818			assert_eq!(storage::get(b"hello"), Some(b"world".to_vec().into()));
1819			assert_eq!(storage::get(b"foo"), None);
1820			storage::set(b"foo", &[1, 2, 3][..]);
1821		});
1822
1823		t = BasicExternalities::new(Storage {
1824			top: map![b"foo".to_vec() => b"bar".to_vec()],
1825			children_default: map![],
1826		});
1827
1828		t.execute_with(|| {
1829			assert_eq!(storage::get(b"hello"), None);
1830			assert_eq!(storage::get(b"foo"), Some(b"bar".to_vec().into()));
1831		});
1832
1833		let value = vec![7u8; 35];
1834		let storage =
1835			Storage { top: map![b"foo00".to_vec() => value.clone()], children_default: map![] };
1836		t = BasicExternalities::new(storage);
1837
1838		t.execute_with(|| {
1839			assert_eq!(storage::get(b"hello"), None);
1840			assert_eq!(storage::get(b"foo00"), Some(value.clone().into()));
1841		});
1842	}
1843
1844	#[test]
1845	fn read_storage_works() {
1846		let value = b"\x0b\0\0\0Hello world".to_vec();
1847		let mut t = BasicExternalities::new(Storage {
1848			top: map![b":test".to_vec() => value.clone()],
1849			children_default: map![],
1850		});
1851
1852		t.execute_with(|| {
1853			let mut v = [0u8; 4];
1854			assert_eq!(storage::read(b":test", &mut v[..], 0).unwrap(), value.len() as u32);
1855			assert_eq!(v, [11u8, 0, 0, 0]);
1856			let mut w = [0u8; 11];
1857			assert_eq!(storage::read(b":test", &mut w[..], 4).unwrap(), value.len() as u32 - 4);
1858			assert_eq!(&w, b"Hello world");
1859		});
1860	}
1861
1862	#[test]
1863	fn clear_prefix_works() {
1864		let mut t = BasicExternalities::new(Storage {
1865			top: map![
1866				b":a".to_vec() => b"\x0b\0\0\0Hello world".to_vec(),
1867				b":abcd".to_vec() => b"\x0b\0\0\0Hello world".to_vec(),
1868				b":abc".to_vec() => b"\x0b\0\0\0Hello world".to_vec(),
1869				b":abdd".to_vec() => b"\x0b\0\0\0Hello world".to_vec()
1870			],
1871			children_default: map![],
1872		});
1873
1874		t.execute_with(|| {
1875			// We can switch to this once we enable v3 of the `clear_prefix`.
1876			//assert!(matches!(
1877			//	storage::clear_prefix(b":abc", None),
1878			//	MultiRemovalResults::NoneLeft { db: 2, total: 2 }
1879			//));
1880			assert!(matches!(
1881				storage::clear_prefix(b":abc", None),
1882				KillStorageResult::AllRemoved(2),
1883			));
1884
1885			assert!(storage::get(b":a").is_some());
1886			assert!(storage::get(b":abdd").is_some());
1887			assert!(storage::get(b":abcd").is_none());
1888			assert!(storage::get(b":abc").is_none());
1889
1890			// We can switch to this once we enable v3 of the `clear_prefix`.
1891			//assert!(matches!(
1892			//	storage::clear_prefix(b":abc", None),
1893			//	MultiRemovalResults::NoneLeft { db: 0, total: 0 }
1894			//));
1895			assert!(matches!(
1896				storage::clear_prefix(b":abc", None),
1897				KillStorageResult::AllRemoved(0),
1898			));
1899		});
1900	}
1901
1902	fn zero_ed_pub() -> ed25519::Public {
1903		[0u8; 32].unchecked_into()
1904	}
1905
1906	fn zero_ed_sig() -> ed25519::Signature {
1907		ed25519::Signature::from_raw([0u8; 64])
1908	}
1909
1910	#[test]
1911	fn use_dalek_ext_works() {
1912		let mut ext = BasicExternalities::default();
1913		ext.register_extension(UseDalekExt::default());
1914
1915		// With dalek the zero signature should fail to verify.
1916		ext.execute_with(|| {
1917			assert!(!crypto::ed25519_verify(&zero_ed_sig(), &Vec::new(), &zero_ed_pub()));
1918		});
1919
1920		// But with zebra it should work.
1921		BasicExternalities::default().execute_with(|| {
1922			assert!(crypto::ed25519_verify(&zero_ed_sig(), &Vec::new(), &zero_ed_pub()));
1923		})
1924	}
1925
1926	#[test]
1927	fn dalek_should_not_panic_on_invalid_signature() {
1928		let mut ext = BasicExternalities::default();
1929		ext.register_extension(UseDalekExt::default());
1930
1931		ext.execute_with(|| {
1932			let mut bytes = [0u8; 64];
1933			// Make it invalid
1934			bytes[63] = 0b1110_0000;
1935
1936			assert!(!crypto::ed25519_verify(
1937				&ed25519::Signature::from_raw(bytes),
1938				&Vec::new(),
1939				&zero_ed_pub()
1940			));
1941		});
1942	}
1943}