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	/// Indexes the specified transaction for the given `extrinsic` and `context_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	/// Renews the transaction index entry for the given `extrinsic` using the provided
1500	/// `context_hash`.
1501	fn renew(&mut self, extrinsic: u32, context_hash: PassPointerAndReadCopy<[u8; 32], 32>) {
1502		self.storage_renew_transaction_index(extrinsic, &context_hash);
1503	}
1504}
1505
1506/// Interface that provides functions to access the Offchain DB.
1507#[runtime_interface]
1508pub trait OffchainIndex {
1509	/// Write a key value pair to the Offchain DB database in a buffered fashion.
1510	fn set(&mut self, key: PassFatPointerAndRead<&[u8]>, value: PassFatPointerAndRead<&[u8]>) {
1511		self.set_offchain_storage(key, Some(value));
1512	}
1513
1514	/// Remove a key and its associated value from the Offchain DB.
1515	fn clear(&mut self, key: PassFatPointerAndRead<&[u8]>) {
1516		self.set_offchain_storage(key, None);
1517	}
1518}
1519
1520#[cfg(not(substrate_runtime))]
1521sp_externalities::decl_extension! {
1522	/// Deprecated verification context.
1523	///
1524	/// Stores the combined result of all verifications that are done in the same context.
1525	struct VerificationExtDeprecated(bool);
1526}
1527
1528/// Interface that provides functions to access the offchain functionality.
1529///
1530/// These functions are being made available to the runtime and are called by the runtime.
1531#[runtime_interface]
1532pub trait Offchain {
1533	/// Returns if the local node is a potential validator.
1534	///
1535	/// Even if this function returns `true`, it does not mean that any keys are configured
1536	/// and that the validator is registered in the chain.
1537	fn is_validator(&mut self) -> bool {
1538		self.extension::<OffchainWorkerExt>()
1539			.expect("is_validator can be called only in the offchain worker context")
1540			.is_validator()
1541	}
1542
1543	/// Submit an encoded transaction to the pool.
1544	///
1545	/// The transaction will end up in the pool.
1546	fn submit_transaction(
1547		&mut self,
1548		data: PassFatPointerAndRead<Vec<u8>>,
1549	) -> AllocateAndReturnByCodec<Result<(), ()>> {
1550		self.extension::<TransactionPoolExt>()
1551			.expect(
1552				"submit_transaction can be called only in the offchain call context with
1553				TransactionPool capabilities enabled",
1554			)
1555			.submit_transaction(data)
1556	}
1557
1558	/// Returns information about the local node's network state.
1559	fn network_state(&mut self) -> AllocateAndReturnByCodec<Result<OpaqueNetworkState, ()>> {
1560		self.extension::<OffchainWorkerExt>()
1561			.expect("network_state can be called only in the offchain worker context")
1562			.network_state()
1563	}
1564
1565	/// Returns current UNIX timestamp (in millis)
1566	fn timestamp(&mut self) -> ReturnAs<Timestamp, u64> {
1567		self.extension::<OffchainWorkerExt>()
1568			.expect("timestamp can be called only in the offchain worker context")
1569			.timestamp()
1570	}
1571
1572	/// Pause the execution until `deadline` is reached.
1573	fn sleep_until(&mut self, deadline: PassAs<Timestamp, u64>) {
1574		self.extension::<OffchainWorkerExt>()
1575			.expect("sleep_until can be called only in the offchain worker context")
1576			.sleep_until(deadline)
1577	}
1578
1579	/// Returns a random seed.
1580	///
1581	/// This is a truly random, non-deterministic seed generated by host environment.
1582	/// Obviously fine in the off-chain worker context.
1583	fn random_seed(&mut self) -> AllocateAndReturnPointer<[u8; 32], 32> {
1584		self.extension::<OffchainWorkerExt>()
1585			.expect("random_seed can be called only in the offchain worker context")
1586			.random_seed()
1587	}
1588
1589	/// Sets a value in the local storage.
1590	///
1591	/// Note this storage is not part of the consensus, it's only accessible by
1592	/// offchain worker tasks running on the same machine. It IS persisted between runs.
1593	fn local_storage_set(
1594		&mut self,
1595		kind: PassAs<StorageKind, u32>,
1596		key: PassFatPointerAndRead<&[u8]>,
1597		value: PassFatPointerAndRead<&[u8]>,
1598	) {
1599		self.extension::<OffchainDbExt>()
1600			.expect(
1601				"local_storage_set can be called only in the offchain call context with
1602				OffchainDb extension",
1603			)
1604			.local_storage_set(kind, key, value)
1605	}
1606
1607	/// Remove a value from the local storage.
1608	///
1609	/// Note this storage is not part of the consensus, it's only accessible by
1610	/// offchain worker tasks running on the same machine. It IS persisted between runs.
1611	fn local_storage_clear(
1612		&mut self,
1613		kind: PassAs<StorageKind, u32>,
1614		key: PassFatPointerAndRead<&[u8]>,
1615	) {
1616		self.extension::<OffchainDbExt>()
1617			.expect(
1618				"local_storage_clear can be called only in the offchain call context with
1619				OffchainDb extension",
1620			)
1621			.local_storage_clear(kind, key)
1622	}
1623
1624	/// Sets a value in the local storage if it matches current value.
1625	///
1626	/// Since multiple offchain workers may be running concurrently, to prevent
1627	/// data races use CAS to coordinate between them.
1628	///
1629	/// Returns `true` if the value has been set, `false` otherwise.
1630	///
1631	/// Note this storage is not part of the consensus, it's only accessible by
1632	/// offchain worker tasks running on the same machine. It IS persisted between runs.
1633	fn local_storage_compare_and_set(
1634		&mut self,
1635		kind: PassAs<StorageKind, u32>,
1636		key: PassFatPointerAndRead<&[u8]>,
1637		old_value: PassFatPointerAndDecode<Option<Vec<u8>>>,
1638		new_value: PassFatPointerAndRead<&[u8]>,
1639	) -> bool {
1640		self.extension::<OffchainDbExt>()
1641			.expect(
1642				"local_storage_compare_and_set can be called only in the offchain call context
1643				with OffchainDb extension",
1644			)
1645			.local_storage_compare_and_set(kind, key, old_value.as_deref(), new_value)
1646	}
1647
1648	/// Gets a value from the local storage.
1649	///
1650	/// If the value does not exist in the storage `None` will be returned.
1651	/// Note this storage is not part of the consensus, it's only accessible by
1652	/// offchain worker tasks running on the same machine. It IS persisted between runs.
1653	fn local_storage_get(
1654		&mut self,
1655		kind: PassAs<StorageKind, u32>,
1656		key: PassFatPointerAndRead<&[u8]>,
1657	) -> AllocateAndReturnByCodec<Option<Vec<u8>>> {
1658		self.extension::<OffchainDbExt>()
1659			.expect(
1660				"local_storage_get can be called only in the offchain call context with
1661				OffchainDb extension",
1662			)
1663			.local_storage_get(kind, key)
1664	}
1665
1666	/// Initiates a http request given HTTP verb and the URL.
1667	///
1668	/// Meta is a future-reserved field containing additional, parity-scale-codec encoded
1669	/// parameters. Returns the id of newly started request.
1670	fn http_request_start(
1671		&mut self,
1672		method: PassFatPointerAndRead<&str>,
1673		uri: PassFatPointerAndRead<&str>,
1674		meta: PassFatPointerAndRead<&[u8]>,
1675	) -> AllocateAndReturnByCodec<Result<HttpRequestId, ()>> {
1676		self.extension::<OffchainWorkerExt>()
1677			.expect("http_request_start can be called only in the offchain worker context")
1678			.http_request_start(method, uri, meta)
1679	}
1680
1681	/// Append header to the request.
1682	fn http_request_add_header(
1683		&mut self,
1684		request_id: PassAs<HttpRequestId, u16>,
1685		name: PassFatPointerAndRead<&str>,
1686		value: PassFatPointerAndRead<&str>,
1687	) -> AllocateAndReturnByCodec<Result<(), ()>> {
1688		self.extension::<OffchainWorkerExt>()
1689			.expect("http_request_add_header can be called only in the offchain worker context")
1690			.http_request_add_header(request_id, name, value)
1691	}
1692
1693	/// Write a chunk of request body.
1694	///
1695	/// Writing an empty chunks finalizes the request.
1696	/// Passing `None` as deadline blocks forever.
1697	///
1698	/// Returns an error in case deadline is reached or the chunk couldn't be written.
1699	fn http_request_write_body(
1700		&mut self,
1701		request_id: PassAs<HttpRequestId, u16>,
1702		chunk: PassFatPointerAndRead<&[u8]>,
1703		deadline: PassFatPointerAndDecode<Option<Timestamp>>,
1704	) -> AllocateAndReturnByCodec<Result<(), HttpError>> {
1705		self.extension::<OffchainWorkerExt>()
1706			.expect("http_request_write_body can be called only in the offchain worker context")
1707			.http_request_write_body(request_id, chunk, deadline)
1708	}
1709
1710	/// Block and wait for the responses for given requests.
1711	///
1712	/// Returns a vector of request statuses (the len is the same as ids).
1713	/// Note that if deadline is not provided the method will block indefinitely,
1714	/// otherwise unready responses will produce `DeadlineReached` status.
1715	///
1716	/// Passing `None` as deadline blocks forever.
1717	fn http_response_wait(
1718		&mut self,
1719		ids: PassFatPointerAndDecodeSlice<&[HttpRequestId]>,
1720		deadline: PassFatPointerAndDecode<Option<Timestamp>>,
1721	) -> AllocateAndReturnByCodec<Vec<HttpRequestStatus>> {
1722		self.extension::<OffchainWorkerExt>()
1723			.expect("http_response_wait can be called only in the offchain worker context")
1724			.http_response_wait(ids, deadline)
1725	}
1726
1727	/// Read all response headers.
1728	///
1729	/// Returns a vector of pairs `(HeaderKey, HeaderValue)`.
1730	/// NOTE: response headers have to be read before response body.
1731	fn http_response_headers(
1732		&mut self,
1733		request_id: PassAs<HttpRequestId, u16>,
1734	) -> AllocateAndReturnByCodec<Vec<(Vec<u8>, Vec<u8>)>> {
1735		self.extension::<OffchainWorkerExt>()
1736			.expect("http_response_headers can be called only in the offchain worker context")
1737			.http_response_headers(request_id)
1738	}
1739
1740	/// Read a chunk of body response to given buffer.
1741	///
1742	/// Returns the number of bytes written or an error in case a deadline
1743	/// is reached or server closed the connection.
1744	/// If `0` is returned it means that the response has been fully consumed
1745	/// and the `request_id` is now invalid.
1746	/// NOTE: this implies that response headers must be read before draining the body.
1747	/// Passing `None` as a deadline blocks forever.
1748	fn http_response_read_body(
1749		&mut self,
1750		request_id: PassAs<HttpRequestId, u16>,
1751		buffer: PassFatPointerAndReadWrite<&mut [u8]>,
1752		deadline: PassFatPointerAndDecode<Option<Timestamp>>,
1753	) -> AllocateAndReturnByCodec<Result<u32, HttpError>> {
1754		self.extension::<OffchainWorkerExt>()
1755			.expect("http_response_read_body can be called only in the offchain worker context")
1756			.http_response_read_body(request_id, buffer, deadline)
1757			.map(|r| r as u32)
1758	}
1759
1760	/// Set the authorized nodes and authorized_only flag.
1761	fn set_authorized_nodes(
1762		&mut self,
1763		nodes: PassFatPointerAndDecode<Vec<OpaquePeerId>>,
1764		authorized_only: bool,
1765	) {
1766		self.extension::<OffchainWorkerExt>()
1767			.expect("set_authorized_nodes can be called only in the offchain worker context")
1768			.set_authorized_nodes(nodes, authorized_only)
1769	}
1770}
1771
1772/// Wasm only interface that provides functions for calling into the allocator.
1773#[runtime_interface(wasm_only)]
1774pub trait Allocator {
1775	/// Malloc the given number of bytes and return the pointer to the allocated memory location.
1776	fn malloc(&mut self, size: u32) -> Pointer<u8> {
1777		self.allocate_memory(size).expect("Failed to allocate memory")
1778	}
1779
1780	/// Free the given pointer.
1781	fn free(&mut self, ptr: Pointer<u8>) {
1782		self.deallocate_memory(ptr).expect("Failed to deallocate memory")
1783	}
1784}
1785
1786/// WASM-only interface which allows for aborting the execution in case
1787/// of an unrecoverable error.
1788#[runtime_interface(wasm_only)]
1789pub trait PanicHandler {
1790	/// Aborts the current execution with the given error message.
1791	#[trap_on_return]
1792	fn abort_on_panic(&mut self, message: PassFatPointerAndRead<&str>) {
1793		self.register_panic_error_message(message);
1794	}
1795}
1796
1797/// Interface that provides functions for logging from within the runtime.
1798#[runtime_interface]
1799pub trait Logging {
1800	/// Request to print a log message on the host.
1801	///
1802	/// Note that this will be only displayed if the host is enabled to display log messages with
1803	/// given level and target.
1804	///
1805	/// Instead of using directly, prefer setting up `RuntimeLogger` and using `log` macros.
1806	fn log(
1807		level: PassAs<RuntimeInterfaceLogLevel, u8>,
1808		target: PassFatPointerAndRead<&str>,
1809		message: PassFatPointerAndRead<&[u8]>,
1810	) {
1811		if let Ok(message) = core::str::from_utf8(message) {
1812			log::log!(target: target, log::Level::from(level), "{}", message)
1813		}
1814	}
1815
1816	/// Returns the max log level used by the host.
1817	fn max_level() -> ReturnAs<LogLevelFilter, u8> {
1818		log::max_level().into()
1819	}
1820}
1821
1822/// Interface to provide tracing facilities for wasm. Modelled after tokios `tracing`-crate
1823/// interfaces. See `sp-tracing` for more information.
1824#[runtime_interface(wasm_only, no_tracing)]
1825pub trait WasmTracing {
1826	/// Whether the span described in `WasmMetadata` should be traced wasm-side
1827	/// On the host converts into a static Metadata and checks against the global `tracing`
1828	/// dispatcher.
1829	///
1830	/// When returning false the calling code should skip any tracing-related execution. In general
1831	/// within the same block execution this is not expected to change and it doesn't have to be
1832	/// checked more than once per metadata. This exists for optimisation purposes but is still not
1833	/// cheap as it will jump the wasm-native-barrier every time it is called. So an implementation
1834	/// might chose to cache the result for the execution of the entire block.
1835	fn enabled(&mut self, metadata: PassFatPointerAndDecode<sp_tracing::WasmMetadata>) -> bool {
1836		let metadata: &tracing_core::metadata::Metadata<'static> = (&metadata).into();
1837		tracing::dispatcher::get_default(|d| d.enabled(metadata))
1838	}
1839
1840	/// Open a new span with the given attributes. Return the u64 Id of the span.
1841	///
1842	/// On the native side this goes through the default `tracing` dispatcher to register the span
1843	/// and then calls `clone_span` with the ID to signal that we are keeping it around on the wasm-
1844	/// side even after the local span is dropped. The resulting ID is then handed over to the wasm-
1845	/// side.
1846	fn enter_span(
1847		&mut self,
1848		span: PassFatPointerAndDecode<sp_tracing::WasmEntryAttributes>,
1849	) -> u64 {
1850		let span: tracing::Span = span.into();
1851		match span.id() {
1852			Some(id) => tracing::dispatcher::get_default(|d| {
1853				// inform dispatch that we'll keep the ID around
1854				// then enter it immediately
1855				let final_id = d.clone_span(&id);
1856				d.enter(&final_id);
1857				final_id.into_u64()
1858			}),
1859			_ => 0,
1860		}
1861	}
1862
1863	/// Emit the given event to the global tracer on the native side
1864	fn event(&mut self, event: PassFatPointerAndDecode<sp_tracing::WasmEntryAttributes>) {
1865		event.emit();
1866	}
1867
1868	/// Signal that a given span-id has been exited. On native, this directly
1869	/// proxies the span to the global dispatcher.
1870	fn exit(&mut self, span: u64) {
1871		tracing::dispatcher::get_default(|d| {
1872			let id = tracing_core::span::Id::from_u64(span);
1873			d.exit(&id);
1874		});
1875	}
1876}
1877
1878#[cfg(all(substrate_runtime, feature = "with-tracing"))]
1879mod tracing_setup {
1880	use super::wasm_tracing;
1881	use core::sync::atomic::{AtomicBool, Ordering};
1882	use tracing_core::{
1883		dispatcher::{set_global_default, Dispatch},
1884		span::{Attributes, Id, Record},
1885		Event, Metadata,
1886	};
1887
1888	static TRACING_SET: AtomicBool = AtomicBool::new(false);
1889
1890	/// The PassingTracingSubscriber implements `tracing_core::Subscriber`
1891	/// and pushes the information across the runtime interface to the host
1892	struct PassingTracingSubscriber;
1893
1894	impl tracing_core::Subscriber for PassingTracingSubscriber {
1895		fn enabled(&self, metadata: &Metadata<'_>) -> bool {
1896			wasm_tracing::enabled(metadata.into())
1897		}
1898		fn new_span(&self, attrs: &Attributes<'_>) -> Id {
1899			Id::from_u64(wasm_tracing::enter_span(attrs.into()))
1900		}
1901		fn enter(&self, _: &Id) {
1902			// Do nothing, we already entered the span previously
1903		}
1904		/// Not implemented! We do not support recording values later
1905		/// Will panic when used.
1906		fn record(&self, _: &Id, _: &Record<'_>) {
1907			unimplemented! {} // this usage is not supported
1908		}
1909		/// Not implemented! We do not support recording values later
1910		/// Will panic when used.
1911		fn record_follows_from(&self, _: &Id, _: &Id) {
1912			unimplemented! {} // this usage is not supported
1913		}
1914		fn event(&self, event: &Event<'_>) {
1915			wasm_tracing::event(event.into())
1916		}
1917		fn exit(&self, span: &Id) {
1918			wasm_tracing::exit(span.into_u64())
1919		}
1920	}
1921
1922	/// Initialize tracing of sp_tracing on wasm with `with-tracing` enabled.
1923	/// Can be called multiple times from within the same process and will only
1924	/// set the global bridging subscriber once.
1925	pub fn init_tracing() {
1926		if TRACING_SET.load(Ordering::Relaxed) == false {
1927			set_global_default(Dispatch::new(PassingTracingSubscriber {}))
1928				.expect("We only ever call this once");
1929			TRACING_SET.store(true, Ordering::Relaxed);
1930		}
1931	}
1932}
1933
1934#[cfg(not(all(substrate_runtime, feature = "with-tracing")))]
1935mod tracing_setup {
1936	/// Initialize tracing of sp_tracing not necessary – noop. To enable build
1937	/// when not both `substrate_runtime` and `with-tracing`-feature.
1938	pub fn init_tracing() {}
1939}
1940
1941pub use tracing_setup::init_tracing;
1942
1943/// Crashes the execution of the program.
1944///
1945/// Equivalent to the WASM `unreachable` instruction, RISC-V `unimp` instruction,
1946/// or just the `unreachable!()` macro everywhere else.
1947pub fn unreachable() -> ! {
1948	#[cfg(target_family = "wasm")]
1949	{
1950		core::arch::wasm32::unreachable();
1951	}
1952
1953	#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
1954	unsafe {
1955		core::arch::asm!("unimp", options(noreturn));
1956	}
1957
1958	#[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64", target_family = "wasm")))]
1959	unreachable!();
1960}
1961
1962/// A default panic handler for the runtime environment.
1963#[cfg(all(not(feature = "disable_panic_handler"), substrate_runtime))]
1964#[panic_handler]
1965pub fn panic(info: &core::panic::PanicInfo) -> ! {
1966	let message = alloc::format!("{}", info);
1967	#[cfg(feature = "improved_panic_error_reporting")]
1968	{
1969		panic_handler::abort_on_panic(&message);
1970	}
1971	#[cfg(not(feature = "improved_panic_error_reporting"))]
1972	{
1973		logging::log(RuntimeInterfaceLogLevel::Error, "runtime", message.as_bytes());
1974		unreachable();
1975	}
1976}
1977
1978/// A default OOM handler for the runtime environment.
1979#[cfg(all(not(feature = "disable_oom"), enable_alloc_error_handler))]
1980#[alloc_error_handler]
1981pub fn oom(_: core::alloc::Layout) -> ! {
1982	#[cfg(feature = "improved_panic_error_reporting")]
1983	{
1984		panic_handler::abort_on_panic("Runtime memory exhausted.");
1985	}
1986	#[cfg(not(feature = "improved_panic_error_reporting"))]
1987	{
1988		logging::log(
1989			RuntimeInterfaceLogLevel::Error,
1990			"runtime",
1991			b"Runtime memory exhausted. Aborting",
1992		);
1993		unreachable();
1994	}
1995}
1996
1997/// Type alias for Externalities implementation used in tests.
1998#[cfg(feature = "std")] // NOTE: Deliberately isn't `not(substrate_runtime)`.
1999pub type TestExternalities = sp_state_machine::TestExternalities<sp_core::Blake2Hasher>;
2000
2001/// The host functions Substrate provides for the Wasm runtime environment.
2002///
2003/// All these host functions will be callable from inside the Wasm environment.
2004#[docify::export]
2005#[cfg(not(substrate_runtime))]
2006pub type SubstrateHostFunctions = (
2007	storage::HostFunctions,
2008	default_child_storage::HostFunctions,
2009	misc::HostFunctions,
2010	wasm_tracing::HostFunctions,
2011	offchain::HostFunctions,
2012	crypto::HostFunctions,
2013	hashing::HostFunctions,
2014	allocator::HostFunctions,
2015	panic_handler::HostFunctions,
2016	logging::HostFunctions,
2017	crate::trie::HostFunctions,
2018	offchain_index::HostFunctions,
2019	transaction_index::HostFunctions,
2020);
2021
2022#[cfg(test)]
2023mod tests {
2024	use super::*;
2025	use sp_core::{crypto::UncheckedInto, map, storage::Storage};
2026	use sp_state_machine::BasicExternalities;
2027
2028	#[test]
2029	fn storage_works() {
2030		let mut t = BasicExternalities::default();
2031		t.execute_with(|| {
2032			assert_eq!(storage::get(b"hello"), None);
2033			storage::set(b"hello", b"world");
2034			assert_eq!(storage::get(b"hello"), Some(b"world".to_vec().into()));
2035			assert_eq!(storage::get(b"foo"), None);
2036			storage::set(b"foo", &[1, 2, 3][..]);
2037		});
2038
2039		t = BasicExternalities::new(Storage {
2040			top: map![b"foo".to_vec() => b"bar".to_vec()],
2041			children_default: map![],
2042		});
2043
2044		t.execute_with(|| {
2045			assert_eq!(storage::get(b"hello"), None);
2046			assert_eq!(storage::get(b"foo"), Some(b"bar".to_vec().into()));
2047		});
2048
2049		let value = vec![7u8; 35];
2050		let storage =
2051			Storage { top: map![b"foo00".to_vec() => value.clone()], children_default: map![] };
2052		t = BasicExternalities::new(storage);
2053
2054		t.execute_with(|| {
2055			assert_eq!(storage::get(b"hello"), None);
2056			assert_eq!(storage::get(b"foo00"), Some(value.clone().into()));
2057		});
2058	}
2059
2060	#[test]
2061	fn read_storage_works() {
2062		let value = b"\x0b\0\0\0Hello world".to_vec();
2063		let mut t = BasicExternalities::new(Storage {
2064			top: map![b":test".to_vec() => value.clone()],
2065			children_default: map![],
2066		});
2067
2068		t.execute_with(|| {
2069			let mut v = [0u8; 4];
2070			assert_eq!(storage::read(b":test", &mut v[..], 0).unwrap(), value.len() as u32);
2071			assert_eq!(v, [11u8, 0, 0, 0]);
2072			let mut w = [0u8; 11];
2073			assert_eq!(storage::read(b":test", &mut w[..], 4).unwrap(), value.len() as u32 - 4);
2074			assert_eq!(&w, b"Hello world");
2075		});
2076	}
2077
2078	#[test]
2079	fn clear_prefix_works() {
2080		let mut t = BasicExternalities::new(Storage {
2081			top: map![
2082				b":a".to_vec() => b"\x0b\0\0\0Hello world".to_vec(),
2083				b":abcd".to_vec() => b"\x0b\0\0\0Hello world".to_vec(),
2084				b":abc".to_vec() => b"\x0b\0\0\0Hello world".to_vec(),
2085				b":abdd".to_vec() => b"\x0b\0\0\0Hello world".to_vec()
2086			],
2087			children_default: map![],
2088		});
2089
2090		t.execute_with(|| {
2091			// We can switch to this once we enable v3 of the `clear_prefix`.
2092			//assert!(matches!(
2093			//	storage::clear_prefix(b":abc", None),
2094			//	MultiRemovalResults::NoneLeft { db: 2, total: 2 }
2095			//));
2096			assert!(matches!(
2097				storage::clear_prefix(b":abc", None),
2098				KillStorageResult::AllRemoved(2),
2099			));
2100
2101			assert!(storage::get(b":a").is_some());
2102			assert!(storage::get(b":abdd").is_some());
2103			assert!(storage::get(b":abcd").is_none());
2104			assert!(storage::get(b":abc").is_none());
2105
2106			// We can switch to this once we enable v3 of the `clear_prefix`.
2107			//assert!(matches!(
2108			//	storage::clear_prefix(b":abc", None),
2109			//	MultiRemovalResults::NoneLeft { db: 0, total: 0 }
2110			//));
2111			assert!(matches!(
2112				storage::clear_prefix(b":abc", None),
2113				KillStorageResult::AllRemoved(0),
2114			));
2115		});
2116	}
2117
2118	fn zero_ed_pub() -> ed25519::Public {
2119		[0u8; 32].unchecked_into()
2120	}
2121
2122	fn zero_ed_sig() -> ed25519::Signature {
2123		ed25519::Signature::from_raw([0u8; 64])
2124	}
2125
2126	#[test]
2127	fn use_dalek_ext_works() {
2128		let mut ext = BasicExternalities::default();
2129		ext.register_extension(UseDalekExt::default());
2130
2131		// With dalek the zero signature should fail to verify.
2132		ext.execute_with(|| {
2133			assert!(!crypto::ed25519_verify(&zero_ed_sig(), &Vec::new(), &zero_ed_pub()));
2134		});
2135
2136		// But with zebra it should work.
2137		BasicExternalities::default().execute_with(|| {
2138			assert!(crypto::ed25519_verify(&zero_ed_sig(), &Vec::new(), &zero_ed_pub()));
2139		})
2140	}
2141
2142	#[test]
2143	fn dalek_should_not_panic_on_invalid_signature() {
2144		let mut ext = BasicExternalities::default();
2145		ext.register_extension(UseDalekExt::default());
2146
2147		ext.execute_with(|| {
2148			let mut bytes = [0u8; 64];
2149			// Make it invalid
2150			bytes[63] = 0b1110_0000;
2151
2152			assert!(!crypto::ed25519_verify(
2153				&ed25519::Signature::from_raw(bytes),
2154				&Vec::new(),
2155				&zero_ed_pub()
2156			));
2157		});
2158	}
2159}