referrerpolicy=no-referrer-when-downgrade

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