referrerpolicy=no-referrer-when-downgrade

sp_io/
relay_chain.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
18use alloc::vec::Vec;
19
20#[cfg(not(substrate_runtime))]
21use tracing;
22
23#[cfg(not(substrate_runtime))]
24use sp_core::{
25	crypto::Pair,
26	hexdisplay::HexDisplay,
27	offchain::{OffchainDbExt, OffchainWorkerExt, TransactionPoolExt},
28	storage::ChildInfo,
29};
30#[cfg(not(substrate_runtime))]
31use sp_keystore::KeystoreExt;
32
33#[cfg(feature = "bandersnatch-experimental")]
34use sp_core::bandersnatch;
35use sp_core::{
36	crypto::KeyTypeId,
37	ecdsa, ed25519,
38	offchain::{
39		HttpError, HttpRequestId, HttpRequestStatus, OpaqueNetworkState, StorageKind, Timestamp,
40	},
41	sr25519,
42	storage::StateVersion,
43	LogLevelFilter, OpaquePeerId, RuntimeInterfaceLogLevel, H256,
44};
45
46#[cfg(feature = "bls-experimental")]
47use sp_core::{bls381, ecdsa_bls381};
48
49#[cfg(not(substrate_runtime))]
50use sp_trie::{LayoutV0, LayoutV1, TrieConfiguration};
51
52use sp_runtime_interface::{
53	pass_by::{
54		AllocateAndReturnByCodec, AllocateAndReturnFatPointer, AllocateAndReturnPointer, PassAs,
55		PassFatPointerAndDecode, PassFatPointerAndDecodeSlice, PassFatPointerAndRead,
56		PassFatPointerAndReadWrite, PassPointerAndRead, PassPointerAndReadCopy, ReturnAs,
57	},
58	runtime_interface, Pointer,
59};
60
61use codec::{Decode, Encode};
62
63#[cfg(not(substrate_runtime))]
64use secp256k1::{
65	ecdsa::{RecoverableSignature, RecoveryId},
66	Message,
67};
68
69#[cfg(not(substrate_runtime))]
70use sp_externalities::{Externalities, ExternalitiesExt};
71
72pub use sp_externalities::MultiRemovalResults;
73
74#[cfg(not(substrate_runtime))]
75const LOG_TARGET: &str = "runtime::io";
76
77/// Error verifying ECDSA signature
78#[derive(Encode, Decode)]
79pub enum EcdsaVerifyError {
80	/// Incorrect value of R or S
81	BadRS,
82	/// Incorrect value of V
83	BadV,
84	/// Invalid signature
85	BadSignature,
86}
87
88/// The outcome of calling `storage_kill`. Returned value is the number of storage items
89/// removed from the backend from making the `storage_kill` call.
90#[derive(Encode, Decode)]
91pub enum KillStorageResult {
92	/// All keys to remove were removed, return number of iterations performed during the
93	/// operation.
94	AllRemoved(u32),
95	/// Not all key to remove were removed, return number of iterations performed during the
96	/// operation.
97	SomeRemaining(u32),
98}
99
100impl From<MultiRemovalResults> for KillStorageResult {
101	fn from(r: MultiRemovalResults) -> Self {
102		// We use `loops` here rather than `backend` because that's the same as the original
103		// functionality pre-#11490. This won't matter once we switch to the new host function
104		// since we won't be using the `KillStorageResult` type in the runtime any more.
105		match r.maybe_cursor {
106			None => Self::AllRemoved(r.loops),
107			Some(..) => Self::SomeRemaining(r.loops),
108		}
109	}
110}
111
112/// Interface for accessing the storage from within the runtime.
113#[runtime_interface]
114pub trait Storage {
115	/// Returns the data for `key` in the storage or `None` if the key can not be found.
116	fn get(
117		&mut self,
118		key: PassFatPointerAndRead<&[u8]>,
119	) -> AllocateAndReturnByCodec<Option<bytes::Bytes>> {
120		self.storage(key).map(|s| bytes::Bytes::from(s.to_vec()))
121	}
122
123	/// Get `key` from storage, placing the value into `value_out` and return the number of
124	/// bytes that the entry in storage has beyond the offset or `None` if the storage entry
125	/// doesn't exist at all.
126	/// If `value_out` length is smaller than the returned length, only `value_out` length bytes
127	/// are copied into `value_out`.
128	fn read(
129		&mut self,
130		key: PassFatPointerAndRead<&[u8]>,
131		value_out: PassFatPointerAndReadWrite<&mut [u8]>,
132		value_offset: u32,
133	) -> AllocateAndReturnByCodec<Option<u32>> {
134		self.storage(key).map(|value| {
135			let value_offset = value_offset as usize;
136			let data = &value[value_offset.min(value.len())..];
137			let written = core::cmp::min(data.len(), value_out.len());
138			value_out[..written].copy_from_slice(&data[..written]);
139			data.len() as u32
140		})
141	}
142
143	/// Set `key` to `value` in the storage.
144	fn set(&mut self, key: PassFatPointerAndRead<&[u8]>, value: PassFatPointerAndRead<&[u8]>) {
145		self.set_storage(key.to_vec(), value.to_vec());
146	}
147
148	/// Clear the storage of the given `key` and its value.
149	fn clear(&mut self, key: PassFatPointerAndRead<&[u8]>) {
150		self.clear_storage(key)
151	}
152
153	/// Check whether the given `key` exists in storage.
154	fn exists(&mut self, key: PassFatPointerAndRead<&[u8]>) -> bool {
155		self.exists_storage(key)
156	}
157
158	/// Clear the storage of each key-value pair where the key starts with the given `prefix`.
159	fn clear_prefix(&mut self, prefix: PassFatPointerAndRead<&[u8]>) {
160		let _ = Externalities::clear_prefix(*self, prefix, None, None);
161	}
162
163	/// Clear the storage of each key-value pair where the key starts with the given `prefix`.
164	///
165	/// # Limit
166	///
167	/// Deletes all keys from the overlay and up to `limit` keys from the backend if
168	/// it is set to `Some`. No limit is applied when `limit` is set to `None`.
169	///
170	/// The limit can be used to partially delete a prefix storage in case it is too large
171	/// to delete in one go (block).
172	///
173	/// Returns [`KillStorageResult`] to inform about the result.
174	///
175	/// # Note
176	///
177	/// Please note that keys that are residing in the overlay for that prefix when
178	/// issuing this call are all deleted without counting towards the `limit`. Only keys
179	/// written during the current block are part of the overlay. Deleting with a `limit`
180	/// mostly makes sense with an empty overlay for that prefix.
181	///
182	/// Calling this function multiple times per block for the same `prefix` does
183	/// not make much sense because it is not cumulative when called inside the same block.
184	/// The deletion would always start from `prefix` resulting in the same keys being deleted
185	/// every time this function is called with the exact same arguments per block. This happens
186	/// because the keys in the overlay are not taken into account when deleting keys in the
187	/// backend.
188	#[version(2)]
189	fn clear_prefix(
190		&mut self,
191		prefix: PassFatPointerAndRead<&[u8]>,
192		limit: PassFatPointerAndDecode<Option<u32>>,
193	) -> AllocateAndReturnByCodec<KillStorageResult> {
194		Externalities::clear_prefix(*self, prefix, limit, None).into()
195	}
196
197	/// Partially clear the storage of each key-value pair where the key starts with the given
198	/// prefix.
199	///
200	/// # Limit
201	///
202	/// A *limit* should always be provided through `maybe_limit`. This is one fewer than the
203	/// maximum number of backend iterations which may be done by this operation and as such
204	/// represents the maximum number of backend deletions which may happen. A *limit* of zero
205	/// implies that no keys will be deleted, though there may be a single iteration done.
206	///
207	/// The limit can be used to partially delete a prefix storage in case it is too large or costly
208	/// to delete in a single operation.
209	///
210	/// # Cursor
211	///
212	/// A *cursor* may be passed in to this operation with `maybe_cursor`. `None` should only be
213	/// passed once (in the initial call) for any given `maybe_prefix` value. Subsequent calls
214	/// operating on the same prefix should always pass `Some`, and this should be equal to the
215	/// previous call result's `maybe_cursor` field.
216	///
217	/// Returns [`MultiRemovalResults`](sp_io::MultiRemovalResults) to inform about the result. Once
218	/// the resultant `maybe_cursor` field is `None`, then no further items remain to be deleted.
219	///
220	/// NOTE: After the initial call for any given prefix, it is important that no keys further
221	/// keys under the same prefix are inserted. If so, then they may or may not be deleted by
222	/// subsequent calls.
223	///
224	/// # Note
225	///
226	/// Please note that keys which are residing in the overlay for that prefix when
227	/// issuing this call are deleted without counting towards the `limit`.
228	#[version(3, register_only)]
229	fn clear_prefix(
230		&mut self,
231		maybe_prefix: PassFatPointerAndRead<&[u8]>,
232		maybe_limit: PassFatPointerAndDecode<Option<u32>>,
233		maybe_cursor: PassFatPointerAndDecode<Option<Vec<u8>>>, /* TODO Make work or just
234		                                                         * Option<Vec<u8>>? */
235	) -> AllocateAndReturnByCodec<MultiRemovalResults> {
236		Externalities::clear_prefix(
237			*self,
238			maybe_prefix,
239			maybe_limit,
240			maybe_cursor.as_ref().map(|x| &x[..]),
241		)
242		.into()
243	}
244
245	/// Append the encoded `value` to the storage item at `key`.
246	///
247	/// The storage item needs to implement [`EncodeAppend`](codec::EncodeAppend).
248	///
249	/// # Warning
250	///
251	/// If the storage item does not support [`EncodeAppend`](codec::EncodeAppend) or
252	/// something else fails at appending, the storage item will be set to `[value]`.
253	fn append(&mut self, key: PassFatPointerAndRead<&[u8]>, value: PassFatPointerAndRead<Vec<u8>>) {
254		self.storage_append(key.to_vec(), value);
255	}
256
257	/// Append the encoded `value` to the storage item at `key`.
258	///
259	/// The storage item needs to implement [`EncodeAppend`](codec::EncodeAppend).
260	///
261	/// Unlike version 1, the append drops a storage root cached by an earlier `storage::root`, see
262	/// [`Externalities::storage_append_v2`](sp_externalities::Externalities::storage_append_v2).
263	///
264	/// Registered only: dropping the marker goes together with switching `host_storage_append` in
265	/// `validate_block` and with dropping the markers of the other registered-only versions, see
266	/// the crate docs of `cumulus-primitives-proof-size-hostfunction`.
267	///
268	/// # Warning
269	///
270	/// If the storage item does not support [`EncodeAppend`](codec::EncodeAppend) or
271	/// something else fails at appending, the storage item will be set to `[value]`.
272	#[version(2, register_only)]
273	fn append(&mut self, key: PassFatPointerAndRead<&[u8]>, value: PassFatPointerAndRead<Vec<u8>>) {
274		self.storage_append_v2(key.to_vec(), value);
275	}
276
277	/// "Commit" all existing operations and compute the resulting storage root.
278	///
279	/// The hashing algorithm is defined by the `Block`.
280	///
281	/// Returns a `Vec<u8>` that holds the SCALE encoded hash.
282	fn root(&mut self) -> AllocateAndReturnFatPointer<Vec<u8>> {
283		self.storage_root_with_version(StateVersion::V0)
284	}
285
286	/// "Commit" all existing operations and compute the resulting storage root.
287	///
288	/// The hashing algorithm is defined by the `Block`.
289	///
290	/// Returns a `Vec<u8>` that holds the SCALE encoded hash.
291	#[version(2)]
292	fn root(&mut self, version: PassAs<StateVersion, u8>) -> AllocateAndReturnFatPointer<Vec<u8>> {
293		self.storage_root_with_version(version)
294	}
295
296	/// Always returns `None`. This function exists for compatibility reasons.
297	fn changes_root(
298		&mut self,
299		_parent_hash: PassFatPointerAndRead<&[u8]>,
300	) -> AllocateAndReturnByCodec<Option<Vec<u8>>> {
301		None
302	}
303
304	/// Get the next key in storage after the given one in lexicographic order.
305	fn next_key(
306		&mut self,
307		key: PassFatPointerAndRead<&[u8]>,
308	) -> AllocateAndReturnByCodec<Option<Vec<u8>>> {
309		self.next_storage_key(key)
310	}
311
312	/// Start a new nested transaction.
313	///
314	/// This allows to either commit or roll back all changes that are made after this call.
315	/// For every transaction there must be a matching call to either `rollback_transaction`
316	/// or `commit_transaction`. This is also effective for all values manipulated using the
317	/// `DefaultChildStorage` API.
318	///
319	/// # Warning
320	///
321	/// This is a low level API that is potentially dangerous as it can easily result
322	/// in unbalanced transactions. For example, FRAME users should use high level storage
323	/// abstractions.
324	fn start_transaction(&mut self) {
325		self.storage_start_transaction();
326	}
327
328	/// Rollback the last transaction started by `start_transaction`.
329	///
330	/// Any changes made during that transaction are discarded.
331	///
332	/// # Panics
333	///
334	/// Will panic if there is no open transaction.
335	fn rollback_transaction(&mut self) {
336		self.storage_rollback_transaction()
337			.expect("No open transaction that can be rolled back.");
338	}
339
340	/// Commit the last transaction started by `start_transaction`.
341	///
342	/// Any changes made during that transaction are committed.
343	///
344	/// # Panics
345	///
346	/// Will panic if there is no open transaction.
347	fn commit_transaction(&mut self) {
348		self.storage_commit_transaction()
349			.expect("No open transaction that can be committed.");
350	}
351}
352
353/// Interface for accessing the child storage for default child trie,
354/// from within the runtime.
355#[runtime_interface]
356pub trait DefaultChildStorage {
357	/// Get a default child storage value for a given key.
358	///
359	/// Parameter `storage_key` is the unprefixed location of the root of the child trie in the
360	/// parent trie. Result is `None` if the value for `key` in the child storage can not be found.
361	fn get(
362		&mut self,
363		storage_key: PassFatPointerAndRead<&[u8]>,
364		key: PassFatPointerAndRead<&[u8]>,
365	) -> AllocateAndReturnByCodec<Option<Vec<u8>>> {
366		let child_info = ChildInfo::new_default(storage_key);
367		self.child_storage(&child_info, key).map(|s| s.to_vec())
368	}
369
370	/// Allocation efficient variant of `get`.
371	///
372	/// Get `key` from child storage, placing the value into `value_out` and return the number
373	/// of bytes that the entry in storage has beyond the offset or `None` if the storage entry
374	/// doesn't exist at all.
375	/// If `value_out` length is smaller than the returned length, only `value_out` length bytes
376	/// are copied into `value_out`.
377	fn read(
378		&mut self,
379		storage_key: PassFatPointerAndRead<&[u8]>,
380		key: PassFatPointerAndRead<&[u8]>,
381		value_out: PassFatPointerAndReadWrite<&mut [u8]>,
382		value_offset: u32,
383	) -> AllocateAndReturnByCodec<Option<u32>> {
384		let child_info = ChildInfo::new_default(storage_key);
385		self.child_storage(&child_info, key).map(|value| {
386			let value_offset = value_offset as usize;
387			let data = &value[value_offset.min(value.len())..];
388			let written = core::cmp::min(data.len(), value_out.len());
389			value_out[..written].copy_from_slice(&data[..written]);
390			data.len() as u32
391		})
392	}
393
394	/// Set a child storage value.
395	///
396	/// Set `key` to `value` in the child storage denoted by `storage_key`.
397	fn set(
398		&mut self,
399		storage_key: PassFatPointerAndRead<&[u8]>,
400		key: PassFatPointerAndRead<&[u8]>,
401		value: PassFatPointerAndRead<&[u8]>,
402	) {
403		let child_info = ChildInfo::new_default(storage_key);
404		self.set_child_storage(&child_info, key.to_vec(), value.to_vec());
405	}
406
407	/// Clear a child storage key.
408	///
409	/// For the default child storage at `storage_key`, clear value at `key`.
410	fn clear(
411		&mut self,
412		storage_key: PassFatPointerAndRead<&[u8]>,
413		key: PassFatPointerAndRead<&[u8]>,
414	) {
415		let child_info = ChildInfo::new_default(storage_key);
416		self.clear_child_storage(&child_info, key);
417	}
418
419	/// Clear an entire child storage.
420	///
421	/// If it exists, the child storage for `storage_key`
422	/// is removed.
423	fn storage_kill(&mut self, storage_key: PassFatPointerAndRead<&[u8]>) {
424		let child_info = ChildInfo::new_default(storage_key);
425		let _ = self.kill_child_storage(&child_info, None, None);
426	}
427
428	/// Clear a child storage key.
429	///
430	/// See `Storage` module `clear_prefix` documentation for `limit` usage.
431	#[version(2)]
432	fn storage_kill(
433		&mut self,
434		storage_key: PassFatPointerAndRead<&[u8]>,
435		limit: PassFatPointerAndDecode<Option<u32>>,
436	) -> bool {
437		let child_info = ChildInfo::new_default(storage_key);
438		let r = self.kill_child_storage(&child_info, limit, None);
439		r.maybe_cursor.is_none()
440	}
441
442	/// Clear a child storage key.
443	///
444	/// See `Storage` module `clear_prefix` documentation for `limit` usage.
445	#[version(3)]
446	fn storage_kill(
447		&mut self,
448		storage_key: PassFatPointerAndRead<&[u8]>,
449		limit: PassFatPointerAndDecode<Option<u32>>,
450	) -> AllocateAndReturnByCodec<KillStorageResult> {
451		let child_info = ChildInfo::new_default(storage_key);
452		self.kill_child_storage(&child_info, limit, None).into()
453	}
454
455	/// Clear a child storage key.
456	///
457	/// See `Storage` module `clear_prefix` documentation for `limit` usage.
458	#[version(4, register_only)]
459	fn storage_kill(
460		&mut self,
461		storage_key: PassFatPointerAndRead<&[u8]>,
462		maybe_limit: PassFatPointerAndDecode<Option<u32>>,
463		maybe_cursor: PassFatPointerAndDecode<Option<Vec<u8>>>,
464	) -> AllocateAndReturnByCodec<MultiRemovalResults> {
465		let child_info = ChildInfo::new_default(storage_key);
466		self.kill_child_storage(&child_info, maybe_limit, maybe_cursor.as_ref().map(|x| &x[..]))
467			.into()
468	}
469
470	/// Check a child storage key.
471	///
472	/// Check whether the given `key` exists in default child defined at `storage_key`.
473	fn exists(
474		&mut self,
475		storage_key: PassFatPointerAndRead<&[u8]>,
476		key: PassFatPointerAndRead<&[u8]>,
477	) -> bool {
478		let child_info = ChildInfo::new_default(storage_key);
479		self.exists_child_storage(&child_info, key)
480	}
481
482	/// Clear child default key by prefix.
483	///
484	/// Clear the child storage of each key-value pair where the key starts with the given `prefix`.
485	fn clear_prefix(
486		&mut self,
487		storage_key: PassFatPointerAndRead<&[u8]>,
488		prefix: PassFatPointerAndRead<&[u8]>,
489	) {
490		let child_info = ChildInfo::new_default(storage_key);
491		let _ = self.clear_child_prefix(&child_info, prefix, None, None);
492	}
493
494	/// Clear the child storage of each key-value pair where the key starts with the given `prefix`.
495	///
496	/// See `Storage` module `clear_prefix` documentation for `limit` usage.
497	#[version(2)]
498	fn clear_prefix(
499		&mut self,
500		storage_key: PassFatPointerAndRead<&[u8]>,
501		prefix: PassFatPointerAndRead<&[u8]>,
502		limit: PassFatPointerAndDecode<Option<u32>>,
503	) -> AllocateAndReturnByCodec<KillStorageResult> {
504		let child_info = ChildInfo::new_default(storage_key);
505		self.clear_child_prefix(&child_info, prefix, limit, None).into()
506	}
507
508	/// Clear the child storage of each key-value pair where the key starts with the given `prefix`.
509	///
510	/// See `Storage` module `clear_prefix` documentation for `limit` usage.
511	#[version(3, register_only)]
512	fn clear_prefix(
513		&mut self,
514		storage_key: PassFatPointerAndRead<&[u8]>,
515		prefix: 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.clear_child_prefix(
521			&child_info,
522			prefix,
523			maybe_limit,
524			maybe_cursor.as_ref().map(|x| &x[..]),
525		)
526		.into()
527	}
528
529	/// Default child root calculation.
530	///
531	/// "Commit" all existing operations and compute the resulting child storage root.
532	/// The hashing algorithm is defined by the `Block`.
533	///
534	/// Returns a `Vec<u8>` that holds the SCALE encoded hash.
535	fn root(
536		&mut self,
537		storage_key: PassFatPointerAndRead<&[u8]>,
538	) -> AllocateAndReturnFatPointer<Vec<u8>> {
539		let child_info = ChildInfo::new_default(storage_key);
540		self.child_storage_root_with_version(&child_info, StateVersion::V0)
541	}
542
543	/// Default child root calculation.
544	///
545	/// "Commit" all existing operations and compute the resulting child storage root.
546	/// The hashing algorithm is defined by the `Block`.
547	///
548	/// Returns a `Vec<u8>` that holds the SCALE encoded hash.
549	#[version(2)]
550	fn root(
551		&mut self,
552		storage_key: PassFatPointerAndRead<&[u8]>,
553		version: PassAs<StateVersion, u8>,
554	) -> AllocateAndReturnFatPointer<Vec<u8>> {
555		let child_info = ChildInfo::new_default(storage_key);
556		self.child_storage_root_with_version(&child_info, version)
557	}
558
559	/// Default child root calculation.
560	///
561	/// "Commit" all existing operations and compute the resulting child storage root.
562	/// The hashing algorithm is defined by the `Block`.
563	///
564	/// Returns a `Vec<u8>` that holds the SCALE encoded hash.
565	///
566	/// Unlike version 2, it takes no state version: the trie layout follows the runtime's state
567	/// version. It never writes the child root into the main storage. It also returns the
568	/// current root after a mid-block `storage::root`, where version 2 returns a stale one. See
569	/// [`sp_externalities::Externalities::child_storage_root_v3`].
570	///
571	/// Registered only: dropping the marker goes together with switching
572	/// `host_default_child_storage_root` in `validate_block` and with dropping the markers of the
573	/// other registered-only versions, see the crate docs of
574	/// `cumulus-primitives-proof-size-hostfunction`.
575	#[version(3, register_only)]
576	fn root(
577		&mut self,
578		storage_key: PassFatPointerAndRead<&[u8]>,
579	) -> AllocateAndReturnFatPointer<Vec<u8>> {
580		let child_info = ChildInfo::new_default(storage_key);
581		self.child_storage_root_v3(&child_info)
582	}
583
584	/// Child storage key iteration.
585	///
586	/// Get the next key in storage after the given one in lexicographic order in child storage.
587	fn next_key(
588		&mut self,
589		storage_key: PassFatPointerAndRead<&[u8]>,
590		key: PassFatPointerAndRead<&[u8]>,
591	) -> AllocateAndReturnByCodec<Option<Vec<u8>>> {
592		let child_info = ChildInfo::new_default(storage_key);
593		self.next_child_storage_key(&child_info, key)
594	}
595}
596
597/// Interface that provides trie related functionality.
598#[runtime_interface]
599pub trait Trie {
600	/// A trie root formed from the iterated items.
601	fn blake2_256_root(
602		input: PassFatPointerAndDecode<Vec<(Vec<u8>, Vec<u8>)>>,
603	) -> AllocateAndReturnPointer<H256, 32> {
604		LayoutV0::<sp_core::Blake2Hasher>::trie_root(input)
605	}
606
607	/// A trie root formed from the iterated items.
608	#[version(2)]
609	fn blake2_256_root(
610		input: PassFatPointerAndDecode<Vec<(Vec<u8>, Vec<u8>)>>,
611		version: PassAs<StateVersion, u8>,
612	) -> AllocateAndReturnPointer<H256, 32> {
613		match version {
614			StateVersion::V0 => LayoutV0::<sp_core::Blake2Hasher>::trie_root(input),
615			StateVersion::V1 => LayoutV1::<sp_core::Blake2Hasher>::trie_root(input),
616		}
617	}
618
619	/// A trie root formed from the enumerated items.
620	fn blake2_256_ordered_root(
621		input: PassFatPointerAndDecode<Vec<Vec<u8>>>,
622	) -> AllocateAndReturnPointer<H256, 32> {
623		LayoutV0::<sp_core::Blake2Hasher>::ordered_trie_root(input)
624	}
625
626	/// A trie root formed from the enumerated items.
627	#[version(2)]
628	fn blake2_256_ordered_root(
629		input: PassFatPointerAndDecode<Vec<Vec<u8>>>,
630		version: PassAs<StateVersion, u8>,
631	) -> AllocateAndReturnPointer<H256, 32> {
632		match version {
633			StateVersion::V0 => LayoutV0::<sp_core::Blake2Hasher>::ordered_trie_root(input),
634			StateVersion::V1 => LayoutV1::<sp_core::Blake2Hasher>::ordered_trie_root(input),
635		}
636	}
637
638	/// A trie root formed from the iterated items.
639	fn keccak_256_root(
640		input: PassFatPointerAndDecode<Vec<(Vec<u8>, Vec<u8>)>>,
641	) -> AllocateAndReturnPointer<H256, 32> {
642		LayoutV0::<sp_core::KeccakHasher>::trie_root(input)
643	}
644
645	/// A trie root formed from the iterated items.
646	#[version(2)]
647	fn keccak_256_root(
648		input: PassFatPointerAndDecode<Vec<(Vec<u8>, Vec<u8>)>>,
649		version: PassAs<StateVersion, u8>,
650	) -> AllocateAndReturnPointer<H256, 32> {
651		match version {
652			StateVersion::V0 => LayoutV0::<sp_core::KeccakHasher>::trie_root(input),
653			StateVersion::V1 => LayoutV1::<sp_core::KeccakHasher>::trie_root(input),
654		}
655	}
656
657	/// A trie root formed from the enumerated items.
658	fn keccak_256_ordered_root(
659		input: PassFatPointerAndDecode<Vec<Vec<u8>>>,
660	) -> AllocateAndReturnPointer<H256, 32> {
661		LayoutV0::<sp_core::KeccakHasher>::ordered_trie_root(input)
662	}
663
664	/// A trie root formed from the enumerated items.
665	#[version(2)]
666	fn keccak_256_ordered_root(
667		input: PassFatPointerAndDecode<Vec<Vec<u8>>>,
668		version: PassAs<StateVersion, u8>,
669	) -> AllocateAndReturnPointer<H256, 32> {
670		match version {
671			StateVersion::V0 => LayoutV0::<sp_core::KeccakHasher>::ordered_trie_root(input),
672			StateVersion::V1 => LayoutV1::<sp_core::KeccakHasher>::ordered_trie_root(input),
673		}
674	}
675
676	/// Verify trie proof
677	fn blake2_256_verify_proof(
678		root: PassPointerAndReadCopy<H256, 32>,
679		proof: PassFatPointerAndDecodeSlice<&[Vec<u8>]>,
680		key: PassFatPointerAndRead<&[u8]>,
681		value: PassFatPointerAndRead<&[u8]>,
682	) -> bool {
683		sp_trie::verify_trie_proof::<LayoutV0<sp_core::Blake2Hasher>, _, _, _>(
684			&root,
685			proof,
686			&[(key, Some(value))],
687		)
688		.is_ok()
689	}
690
691	/// Verify trie proof
692	#[version(2)]
693	fn blake2_256_verify_proof(
694		root: PassPointerAndReadCopy<H256, 32>,
695		proof: PassFatPointerAndDecodeSlice<&[Vec<u8>]>,
696		key: PassFatPointerAndRead<&[u8]>,
697		value: PassFatPointerAndRead<&[u8]>,
698		version: PassAs<StateVersion, u8>,
699	) -> bool {
700		match version {
701			StateVersion::V0 => sp_trie::verify_trie_proof::<
702				LayoutV0<sp_core::Blake2Hasher>,
703				_,
704				_,
705				_,
706			>(&root, proof, &[(key, Some(value))])
707			.is_ok(),
708			StateVersion::V1 => sp_trie::verify_trie_proof::<
709				LayoutV1<sp_core::Blake2Hasher>,
710				_,
711				_,
712				_,
713			>(&root, proof, &[(key, Some(value))])
714			.is_ok(),
715		}
716	}
717
718	/// Verify trie proof
719	fn keccak_256_verify_proof(
720		root: PassPointerAndReadCopy<H256, 32>,
721		proof: PassFatPointerAndDecodeSlice<&[Vec<u8>]>,
722		key: PassFatPointerAndRead<&[u8]>,
723		value: PassFatPointerAndRead<&[u8]>,
724	) -> bool {
725		sp_trie::verify_trie_proof::<LayoutV0<sp_core::KeccakHasher>, _, _, _>(
726			&root,
727			proof,
728			&[(key, Some(value))],
729		)
730		.is_ok()
731	}
732
733	/// Verify trie proof
734	#[version(2)]
735	fn keccak_256_verify_proof(
736		root: PassPointerAndReadCopy<H256, 32>,
737		proof: PassFatPointerAndDecodeSlice<&[Vec<u8>]>,
738		key: PassFatPointerAndRead<&[u8]>,
739		value: PassFatPointerAndRead<&[u8]>,
740		version: PassAs<StateVersion, u8>,
741	) -> bool {
742		match version {
743			StateVersion::V0 => sp_trie::verify_trie_proof::<
744				LayoutV0<sp_core::KeccakHasher>,
745				_,
746				_,
747				_,
748			>(&root, proof, &[(key, Some(value))])
749			.is_ok(),
750			StateVersion::V1 => sp_trie::verify_trie_proof::<
751				LayoutV1<sp_core::KeccakHasher>,
752				_,
753				_,
754				_,
755			>(&root, proof, &[(key, Some(value))])
756			.is_ok(),
757		}
758	}
759}
760
761/// Interface that provides miscellaneous functions for communicating between the runtime and the
762/// node.
763#[runtime_interface]
764pub trait Misc {
765	// NOTE: We use the target 'runtime' for messages produced by general printing functions,
766	// instead of LOG_TARGET.
767
768	/// Print a number.
769	fn print_num(val: u64) {
770		log::debug!(target: "runtime", "{}", val);
771	}
772
773	/// Print any valid `utf8` buffer.
774	fn print_utf8(utf8: PassFatPointerAndRead<&[u8]>) {
775		if let Ok(data) = core::str::from_utf8(utf8) {
776			log::debug!(target: "runtime", "{}", data)
777		}
778	}
779
780	/// Print any `u8` slice as hex.
781	fn print_hex(data: PassFatPointerAndRead<&[u8]>) {
782		log::debug!(target: "runtime", "{}", HexDisplay::from(&data));
783	}
784
785	/// Extract the runtime version of the given wasm blob by calling `Core_version`.
786	///
787	/// Returns `None` if calling the function failed for any reason or `Some(Vec<u8>)` where
788	/// the `Vec<u8>` holds the SCALE encoded runtime version.
789	///
790	/// # Performance
791	///
792	/// This function may be very expensive to call depending on the wasm binary. It may be
793	/// relatively cheap if the wasm binary contains version information. In that case,
794	/// uncompression of the wasm blob is the dominating factor.
795	///
796	/// If the wasm binary does not have the version information attached, then a legacy mechanism
797	/// may be involved. This means that a runtime call will be performed to query the version.
798	///
799	/// Calling into the runtime may be incredible expensive and should be approached with care.
800	fn runtime_version(
801		&mut self,
802		wasm: PassFatPointerAndRead<&[u8]>,
803	) -> AllocateAndReturnByCodec<Option<Vec<u8>>> {
804		use sp_core::traits::ReadRuntimeVersionExt;
805
806		let mut ext = sp_state_machine::BasicExternalities::default();
807
808		match self
809			.extension::<ReadRuntimeVersionExt>()
810			.expect("No `ReadRuntimeVersionExt` associated for the current context!")
811			.read_runtime_version(wasm, &mut ext)
812		{
813			Ok(v) => Some(v),
814			Err(err) => {
815				log::debug!(
816					target: LOG_TARGET,
817					"cannot read version from the given runtime: {}",
818					err,
819				);
820				None
821			},
822		}
823	}
824}
825
826#[cfg(not(substrate_runtime))]
827sp_externalities::decl_extension! {
828	/// Extension to signal to [`crypt::ed25519_verify`] to use the dalek crate.
829	///
830	/// The switch from `ed25519-dalek` to `ed25519-zebra` was a breaking change.
831	/// `ed25519-zebra` is more permissive when it comes to the verification of signatures.
832	/// This means that some chains may fail to sync from genesis when using `ed25519-zebra`.
833	/// So, this extension can be registered to the runtime execution environment to signal
834	/// that `ed25519-dalek` should be used for verification. The extension can be registered
835	/// in the following way:
836	///
837	/// ```nocompile
838	/// client.execution_extensions().set_extensions_factory(
839	/// 	// Let the `UseDalekExt` extension being registered for each runtime invocation
840	/// 	// until the execution happens in the context of block `1000`.
841	/// 	sc_client_api::execution_extensions::ExtensionBeforeBlock::<Block, UseDalekExt>::new(1000)
842	/// );
843	/// ```
844	pub struct UseDalekExt;
845}
846
847#[cfg(not(substrate_runtime))]
848impl Default for UseDalekExt {
849	fn default() -> Self {
850		Self
851	}
852}
853
854/// Interfaces for working with crypto related types from within the runtime.
855#[runtime_interface]
856pub trait Crypto {
857	/// Returns all `ed25519` public keys for the given key id from the keystore.
858	fn ed25519_public_keys(
859		&mut self,
860		id: PassPointerAndReadCopy<KeyTypeId, 4>,
861	) -> AllocateAndReturnByCodec<Vec<ed25519::Public>> {
862		self.extension::<KeystoreExt>()
863			.expect("No `keystore` associated for the current context!")
864			.ed25519_public_keys(id)
865	}
866
867	/// Generate an `ed22519` key for the given key type using an optional `seed` and
868	/// store it in the keystore.
869	///
870	/// The `seed` needs to be a valid utf8.
871	///
872	/// Returns the public key.
873	fn ed25519_generate(
874		&mut self,
875		id: PassPointerAndReadCopy<KeyTypeId, 4>,
876		seed: PassFatPointerAndDecode<Option<Vec<u8>>>,
877	) -> AllocateAndReturnPointer<ed25519::Public, 32> {
878		let seed = seed.as_ref().map(|s| core::str::from_utf8(s).expect("Seed is valid utf8!"));
879		self.extension::<KeystoreExt>()
880			.expect("No `keystore` associated for the current context!")
881			.ed25519_generate_new(id, seed)
882			.expect("`ed25519_generate` failed")
883	}
884
885	/// Sign the given `msg` with the `ed25519` key that corresponds to the given public key and
886	/// key type in the keystore.
887	///
888	/// Returns the signature.
889	fn ed25519_sign(
890		&mut self,
891		id: PassPointerAndReadCopy<KeyTypeId, 4>,
892		pub_key: PassPointerAndRead<&ed25519::Public, 32>,
893		msg: PassFatPointerAndRead<&[u8]>,
894	) -> AllocateAndReturnByCodec<Option<ed25519::Signature>> {
895		self.extension::<KeystoreExt>()
896			.expect("No `keystore` associated for the current context!")
897			.ed25519_sign(id, pub_key, msg)
898			.ok()
899			.flatten()
900	}
901
902	/// Verify `ed25519` signature.
903	///
904	/// Returns `true` when the verification was successful.
905	fn ed25519_verify(
906		sig: PassPointerAndRead<&ed25519::Signature, 64>,
907		msg: PassFatPointerAndRead<&[u8]>,
908		pub_key: PassPointerAndRead<&ed25519::Public, 32>,
909	) -> bool {
910		// We don't want to force everyone needing to call the function in an externalities context.
911		// So, we assume that we should not use dalek when we are not in externalities context.
912		// Otherwise, we check if the extension is present.
913		if sp_externalities::with_externalities(|mut e| e.extension::<UseDalekExt>().is_some())
914			.unwrap_or_default()
915		{
916			use ed25519_dalek::Verifier;
917
918			let Ok(public_key) = ed25519_dalek::VerifyingKey::from_bytes(&pub_key.0) else {
919				return false;
920			};
921
922			let sig = ed25519_dalek::Signature::from_bytes(&sig.0);
923
924			public_key.verify(msg, &sig).is_ok()
925		} else {
926			ed25519::Pair::verify(sig, msg, pub_key)
927		}
928	}
929
930	/// Register a `ed25519` signature for batch verification.
931	///
932	/// Batch verification must be enabled by calling [`start_batch_verify`].
933	/// If batch verification is not enabled, the signature will be verified immediately.
934	/// To get the result of the batch verification, [`finish_batch_verify`]
935	/// needs to be called.
936	///
937	/// Returns `true` when the verification is either successful or batched.
938	///
939	/// NOTE: Is tagged with `register_only` to keep the functions around for backwards
940	/// compatibility with old runtimes, but it should not be used anymore by new runtimes.
941	/// The implementation emulates the old behavior, but isn't doing any batch verification
942	/// anymore.
943	#[version(1, register_only)]
944	fn ed25519_batch_verify(
945		&mut self,
946		sig: PassPointerAndRead<&ed25519::Signature, 64>,
947		msg: PassFatPointerAndRead<&[u8]>,
948		pub_key: PassPointerAndRead<&ed25519::Public, 32>,
949	) -> bool {
950		let res = ed25519_verify(sig, msg, pub_key);
951
952		if let Some(ext) = self.extension::<VerificationExtDeprecated>() {
953			ext.0 &= res;
954		}
955
956		res
957	}
958
959	/// Verify `sr25519` signature.
960	///
961	/// Returns `true` when the verification was successful.
962	#[version(2)]
963	fn sr25519_verify(
964		sig: PassPointerAndRead<&sr25519::Signature, 64>,
965		msg: PassFatPointerAndRead<&[u8]>,
966		pub_key: PassPointerAndRead<&sr25519::Public, 32>,
967	) -> bool {
968		sr25519::Pair::verify(sig, msg, pub_key)
969	}
970
971	/// Register a `sr25519` signature for batch verification.
972	///
973	/// Batch verification must be enabled by calling [`start_batch_verify`].
974	/// If batch verification is not enabled, the signature will be verified immediately.
975	/// To get the result of the batch verification, [`finish_batch_verify`]
976	/// needs to be called.
977	///
978	/// Returns `true` when the verification is either successful or batched.
979	///
980	/// NOTE: Is tagged with `register_only` to keep the functions around for backwards
981	/// compatibility with old runtimes, but it should not be used anymore by new runtimes.
982	/// The implementation emulates the old behavior, but isn't doing any batch verification
983	/// anymore.
984	#[version(1, register_only)]
985	fn sr25519_batch_verify(
986		&mut self,
987		sig: PassPointerAndRead<&sr25519::Signature, 64>,
988		msg: PassFatPointerAndRead<&[u8]>,
989		pub_key: PassPointerAndRead<&sr25519::Public, 32>,
990	) -> bool {
991		let res = sr25519_verify(sig, msg, pub_key);
992
993		if let Some(ext) = self.extension::<VerificationExtDeprecated>() {
994			ext.0 &= res;
995		}
996
997		res
998	}
999
1000	/// Start verification extension.
1001	///
1002	/// NOTE: Is tagged with `register_only` to keep the functions around for backwards
1003	/// compatibility with old runtimes, but it should not be used anymore by new runtimes.
1004	/// The implementation emulates the old behavior, but isn't doing any batch verification
1005	/// anymore.
1006	#[version(1, register_only)]
1007	fn start_batch_verify(&mut self) {
1008		self.register_extension(VerificationExtDeprecated(true))
1009			.expect("Failed to register required extension: `VerificationExt`");
1010	}
1011
1012	/// Finish batch-verification of signatures.
1013	///
1014	/// Verify or wait for verification to finish for all signatures which were previously
1015	/// deferred by `sr25519_verify`/`ed25519_verify`.
1016	///
1017	/// Will panic if no `VerificationExt` is registered (`start_batch_verify` was not called).
1018	///
1019	/// NOTE: Is tagged with `register_only` to keep the functions around for backwards
1020	/// compatibility with old runtimes, but it should not be used anymore by new runtimes.
1021	/// The implementation emulates the old behavior, but isn't doing any batch verification
1022	/// anymore.
1023	#[version(1, register_only)]
1024	fn finish_batch_verify(&mut self) -> bool {
1025		let result = self
1026			.extension::<VerificationExtDeprecated>()
1027			.expect("`finish_batch_verify` should only be called after `start_batch_verify`")
1028			.0;
1029
1030		self.deregister_extension::<VerificationExtDeprecated>()
1031			.expect("No verification extension in current context!");
1032
1033		result
1034	}
1035
1036	/// Returns all `sr25519` public keys for the given key id from the keystore.
1037	fn sr25519_public_keys(
1038		&mut self,
1039		id: PassPointerAndReadCopy<KeyTypeId, 4>,
1040	) -> AllocateAndReturnByCodec<Vec<sr25519::Public>> {
1041		self.extension::<KeystoreExt>()
1042			.expect("No `keystore` associated for the current context!")
1043			.sr25519_public_keys(id)
1044	}
1045
1046	/// Generate an `sr22519` key for the given key type using an optional seed and
1047	/// store it in the keystore.
1048	///
1049	/// The `seed` needs to be a valid utf8.
1050	///
1051	/// Returns the public key.
1052	fn sr25519_generate(
1053		&mut self,
1054		id: PassPointerAndReadCopy<KeyTypeId, 4>,
1055		seed: PassFatPointerAndDecode<Option<Vec<u8>>>,
1056	) -> AllocateAndReturnPointer<sr25519::Public, 32> {
1057		let seed = seed.as_ref().map(|s| core::str::from_utf8(s).expect("Seed is valid utf8!"));
1058		self.extension::<KeystoreExt>()
1059			.expect("No `keystore` associated for the current context!")
1060			.sr25519_generate_new(id, seed)
1061			.expect("`sr25519_generate` failed")
1062	}
1063
1064	/// Sign the given `msg` with the `sr25519` key that corresponds to the given public key and
1065	/// key type in the keystore.
1066	///
1067	/// Returns the signature.
1068	fn sr25519_sign(
1069		&mut self,
1070		id: PassPointerAndReadCopy<KeyTypeId, 4>,
1071		pub_key: PassPointerAndRead<&sr25519::Public, 32>,
1072		msg: PassFatPointerAndRead<&[u8]>,
1073	) -> AllocateAndReturnByCodec<Option<sr25519::Signature>> {
1074		self.extension::<KeystoreExt>()
1075			.expect("No `keystore` associated for the current context!")
1076			.sr25519_sign(id, pub_key, msg)
1077			.ok()
1078			.flatten()
1079	}
1080
1081	/// Verify an `sr25519` signature.
1082	///
1083	/// Returns `true` when the verification in successful regardless of
1084	/// signature version.
1085	fn sr25519_verify(
1086		sig: PassPointerAndRead<&sr25519::Signature, 64>,
1087		msg: PassFatPointerAndRead<&[u8]>,
1088		pubkey: PassPointerAndRead<&sr25519::Public, 32>,
1089	) -> bool {
1090		sr25519::Pair::verify_deprecated(sig, msg, pubkey)
1091	}
1092
1093	/// Returns all `ecdsa` public keys for the given key id from the keystore.
1094	fn ecdsa_public_keys(
1095		&mut self,
1096		id: PassPointerAndReadCopy<KeyTypeId, 4>,
1097	) -> AllocateAndReturnByCodec<Vec<ecdsa::Public>> {
1098		self.extension::<KeystoreExt>()
1099			.expect("No `keystore` associated for the current context!")
1100			.ecdsa_public_keys(id)
1101	}
1102
1103	/// Generate an `ecdsa` key for the given key type using an optional `seed` and
1104	/// store it in the keystore.
1105	///
1106	/// The `seed` needs to be a valid utf8.
1107	///
1108	/// Returns the public key.
1109	fn ecdsa_generate(
1110		&mut self,
1111		id: PassPointerAndReadCopy<KeyTypeId, 4>,
1112		seed: PassFatPointerAndDecode<Option<Vec<u8>>>,
1113	) -> AllocateAndReturnPointer<ecdsa::Public, 33> {
1114		let seed = seed.as_ref().map(|s| core::str::from_utf8(s).expect("Seed is valid utf8!"));
1115		self.extension::<KeystoreExt>()
1116			.expect("No `keystore` associated for the current context!")
1117			.ecdsa_generate_new(id, seed)
1118			.expect("`ecdsa_generate` failed")
1119	}
1120
1121	/// Sign the given `msg` with the `ecdsa` key that corresponds to the given public key and
1122	/// key type in the keystore.
1123	///
1124	/// Returns the signature.
1125	fn ecdsa_sign(
1126		&mut self,
1127		id: PassPointerAndReadCopy<KeyTypeId, 4>,
1128		pub_key: PassPointerAndRead<&ecdsa::Public, 33>,
1129		msg: PassFatPointerAndRead<&[u8]>,
1130	) -> AllocateAndReturnByCodec<Option<ecdsa::Signature>> {
1131		self.extension::<KeystoreExt>()
1132			.expect("No `keystore` associated for the current context!")
1133			.ecdsa_sign(id, pub_key, msg)
1134			.ok()
1135			.flatten()
1136	}
1137
1138	/// Sign the given a pre-hashed `msg` with the `ecdsa` key that corresponds to the given public
1139	/// key and key type in the keystore.
1140	///
1141	/// Returns the signature.
1142	fn ecdsa_sign_prehashed(
1143		&mut self,
1144		id: PassPointerAndReadCopy<KeyTypeId, 4>,
1145		pub_key: PassPointerAndRead<&ecdsa::Public, 33>,
1146		msg: PassPointerAndRead<&[u8; 32], 32>,
1147	) -> AllocateAndReturnByCodec<Option<ecdsa::Signature>> {
1148		self.extension::<KeystoreExt>()
1149			.expect("No `keystore` associated for the current context!")
1150			.ecdsa_sign_prehashed(id, pub_key, msg)
1151			.ok()
1152			.flatten()
1153	}
1154
1155	/// Verify `ecdsa` signature.
1156	///
1157	/// Returns `true` when the verification was successful.
1158	/// This version is able to handle, non-standard, overflowing signatures.
1159	///
1160	/// **Note:** This function does **not** enforce low-S signature normalization.
1161	/// Callers that require canonical (BIP-62 / EIP-2) signatures should check
1162	/// [`sp_core::ecdsa::is_signature_normalized`] before calling this function.
1163	fn ecdsa_verify(
1164		sig: PassPointerAndRead<&ecdsa::Signature, 65>,
1165		msg: PassFatPointerAndRead<&[u8]>,
1166		pub_key: PassPointerAndRead<&ecdsa::Public, 33>,
1167	) -> bool {
1168		#[allow(deprecated)]
1169		ecdsa::Pair::verify_deprecated(sig, msg, pub_key)
1170	}
1171
1172	/// Verify `ecdsa` signature.
1173	///
1174	/// Returns `true` when the verification was successful.
1175	///
1176	/// **Note:** This function does **not** enforce low-S signature normalization.
1177	/// Callers that require canonical (BIP-62 / EIP-2) signatures should check
1178	/// [`sp_core::ecdsa::is_signature_normalized`] before calling this function.
1179	#[version(2)]
1180	fn ecdsa_verify(
1181		sig: PassPointerAndRead<&ecdsa::Signature, 65>,
1182		msg: PassFatPointerAndRead<&[u8]>,
1183		pub_key: PassPointerAndRead<&ecdsa::Public, 33>,
1184	) -> bool {
1185		ecdsa::Pair::verify(sig, msg, pub_key)
1186	}
1187
1188	/// Verify `ecdsa` signature with pre-hashed `msg`.
1189	///
1190	/// Returns `true` when the verification was successful.
1191	///
1192	/// **Note:** This function does **not** enforce low-S signature normalization.
1193	/// Callers that require canonical (BIP-62 / EIP-2) signatures should check
1194	/// [`sp_core::ecdsa::is_signature_normalized`] before calling this function.
1195	fn ecdsa_verify_prehashed(
1196		sig: PassPointerAndRead<&ecdsa::Signature, 65>,
1197		msg: PassPointerAndRead<&[u8; 32], 32>,
1198		pub_key: PassPointerAndRead<&ecdsa::Public, 33>,
1199	) -> bool {
1200		ecdsa::Pair::verify_prehashed(sig, msg, pub_key)
1201	}
1202
1203	/// Register a `ecdsa` signature for batch verification.
1204	///
1205	/// Batch verification must be enabled by calling [`start_batch_verify`].
1206	/// If batch verification is not enabled, the signature will be verified immediately.
1207	/// To get the result of the batch verification, [`finish_batch_verify`]
1208	/// needs to be called.
1209	///
1210	/// Returns `true` when the verification is either successful or batched.
1211	///
1212	/// NOTE: Is tagged with `register_only` to keep the functions around for backwards
1213	/// compatibility with old runtimes, but it should not be used anymore by new runtimes.
1214	/// The implementation emulates the old behavior, but isn't doing any batch verification
1215	/// anymore.
1216	#[version(1, register_only)]
1217	fn ecdsa_batch_verify(
1218		&mut self,
1219		sig: PassPointerAndRead<&ecdsa::Signature, 65>,
1220		msg: PassFatPointerAndRead<&[u8]>,
1221		pub_key: PassPointerAndRead<&ecdsa::Public, 33>,
1222	) -> bool {
1223		let res = ecdsa_verify(sig, msg, pub_key);
1224
1225		if let Some(ext) = self.extension::<VerificationExtDeprecated>() {
1226			ext.0 &= res;
1227		}
1228
1229		res
1230	}
1231
1232	/// Verify and recover a SECP256k1 ECDSA signature.
1233	///
1234	/// - `sig` is passed in RSV format. V should be either `0/1` or `27/28`.
1235	/// - `msg` is the blake2-256 hash of the message.
1236	///
1237	/// Returns `Err` if the signature is bad, otherwise the 64-byte pubkey
1238	/// (doesn't include the 0x04 prefix).
1239	/// This version is able to handle, non-standard, overflowing signatures.
1240	///
1241	/// **Note:** This function does **not** enforce low-S signature normalization.
1242	/// Callers that require canonical (BIP-62 / EIP-2) signatures should check
1243	/// [`sp_core::ecdsa::is_signature_normalized`] before calling this function.
1244	fn secp256k1_ecdsa_recover(
1245		sig: PassPointerAndRead<&[u8; 65], 65>,
1246		msg: PassPointerAndRead<&[u8; 32], 32>,
1247	) -> AllocateAndReturnByCodec<Result<[u8; 64], EcdsaVerifyError>> {
1248		let rid = libsecp256k1::RecoveryId::parse(
1249			if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as u8,
1250		)
1251		.map_err(|_| EcdsaVerifyError::BadV)?;
1252		let sig = libsecp256k1::Signature::parse_overflowing_slice(&sig[..64])
1253			.map_err(|_| EcdsaVerifyError::BadRS)?;
1254		let msg = libsecp256k1::Message::parse(msg);
1255		let pubkey =
1256			libsecp256k1::recover(&msg, &sig, &rid).map_err(|_| EcdsaVerifyError::BadSignature)?;
1257		let mut res = [0u8; 64];
1258		res.copy_from_slice(&pubkey.serialize()[1..65]);
1259		Ok(res)
1260	}
1261
1262	/// Verify and recover a SECP256k1 ECDSA signature.
1263	///
1264	/// - `sig` is passed in RSV format. V should be either `0/1` or `27/28`.
1265	/// - `msg` is the blake2-256 hash of the message.
1266	///
1267	/// Returns `Err` if the signature is bad, otherwise the 64-byte pubkey
1268	/// (doesn't include the 0x04 prefix).
1269	///
1270	/// **Note:** This function does **not** enforce low-S signature normalization.
1271	/// Callers that require canonical (BIP-62 / EIP-2) signatures should check
1272	/// [`sp_core::ecdsa::is_signature_normalized`] before calling this function.
1273	#[version(2)]
1274	fn secp256k1_ecdsa_recover(
1275		sig: PassPointerAndRead<&[u8; 65], 65>,
1276		msg: PassPointerAndRead<&[u8; 32], 32>,
1277	) -> AllocateAndReturnByCodec<Result<[u8; 64], EcdsaVerifyError>> {
1278		let rid = RecoveryId::from_i32(if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as i32)
1279			.map_err(|_| EcdsaVerifyError::BadV)?;
1280		let sig = RecoverableSignature::from_compact(&sig[..64], rid)
1281			.map_err(|_| EcdsaVerifyError::BadRS)?;
1282		let msg = Message::from_digest_slice(msg).expect("Message is 32 bytes; qed");
1283		#[cfg(feature = "std")]
1284		let ctx = secp256k1::SECP256K1;
1285		#[cfg(not(feature = "std"))]
1286		let ctx = secp256k1::Secp256k1::<secp256k1::VerifyOnly>::gen_new();
1287		let pubkey = ctx.recover_ecdsa(&msg, &sig).map_err(|_| EcdsaVerifyError::BadSignature)?;
1288		let mut res = [0u8; 64];
1289		res.copy_from_slice(&pubkey.serialize_uncompressed()[1..]);
1290		Ok(res)
1291	}
1292
1293	/// Verify and recover a SECP256k1 ECDSA signature.
1294	///
1295	/// - `sig` is passed in RSV format. V should be either `0/1` or `27/28`.
1296	/// - `msg` is the blake2-256 hash of the message.
1297	///
1298	/// Returns `Err` if the signature is bad, otherwise the 33-byte compressed pubkey.
1299	///
1300	/// **Note:** This function does **not** enforce low-S signature normalization.
1301	/// Callers that require canonical (BIP-62 / EIP-2) signatures should check
1302	/// [`sp_core::ecdsa::is_signature_normalized`] before calling this function.
1303	fn secp256k1_ecdsa_recover_compressed(
1304		sig: PassPointerAndRead<&[u8; 65], 65>,
1305		msg: PassPointerAndRead<&[u8; 32], 32>,
1306	) -> AllocateAndReturnByCodec<Result<[u8; 33], EcdsaVerifyError>> {
1307		let rid = libsecp256k1::RecoveryId::parse(
1308			if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as u8,
1309		)
1310		.map_err(|_| EcdsaVerifyError::BadV)?;
1311		let sig = libsecp256k1::Signature::parse_overflowing_slice(&sig[0..64])
1312			.map_err(|_| EcdsaVerifyError::BadRS)?;
1313		let msg = libsecp256k1::Message::parse(msg);
1314		let pubkey =
1315			libsecp256k1::recover(&msg, &sig, &rid).map_err(|_| EcdsaVerifyError::BadSignature)?;
1316		Ok(pubkey.serialize_compressed())
1317	}
1318
1319	/// Verify and recover a SECP256k1 ECDSA signature.
1320	///
1321	/// - `sig` is passed in RSV format. V should be either `0/1` or `27/28`.
1322	/// - `msg` is the blake2-256 hash of the message.
1323	///
1324	/// Returns `Err` if the signature is bad, otherwise the 33-byte compressed pubkey.
1325	///
1326	/// **Note:** This function does **not** enforce low-S signature normalization.
1327	/// Callers that require canonical (BIP-62 / EIP-2) signatures should check
1328	/// [`sp_core::ecdsa::is_signature_normalized`] before calling this function.
1329	#[version(2)]
1330	fn secp256k1_ecdsa_recover_compressed(
1331		sig: PassPointerAndRead<&[u8; 65], 65>,
1332		msg: PassPointerAndRead<&[u8; 32], 32>,
1333	) -> AllocateAndReturnByCodec<Result<[u8; 33], EcdsaVerifyError>> {
1334		let rid = RecoveryId::from_i32(if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as i32)
1335			.map_err(|_| EcdsaVerifyError::BadV)?;
1336		let sig = RecoverableSignature::from_compact(&sig[..64], rid)
1337			.map_err(|_| EcdsaVerifyError::BadRS)?;
1338		let msg = Message::from_digest_slice(msg).expect("Message is 32 bytes; qed");
1339		#[cfg(feature = "std")]
1340		let ctx = secp256k1::SECP256K1;
1341		#[cfg(not(feature = "std"))]
1342		let ctx = secp256k1::Secp256k1::<secp256k1::VerifyOnly>::gen_new();
1343		let pubkey = ctx.recover_ecdsa(&msg, &sig).map_err(|_| EcdsaVerifyError::BadSignature)?;
1344		Ok(pubkey.serialize())
1345	}
1346
1347	/// Generate an `bls12-381` key for the given key type using an optional `seed` and
1348	/// store it in the keystore.
1349	///
1350	/// The `seed` needs to be a valid utf8.
1351	///
1352	/// Returns the public key.
1353	#[cfg(feature = "bls-experimental")]
1354	fn bls381_generate(
1355		&mut self,
1356		id: PassPointerAndReadCopy<KeyTypeId, 4>,
1357		seed: PassFatPointerAndDecode<Option<Vec<u8>>>,
1358	) -> AllocateAndReturnPointer<bls381::Public, 144> {
1359		let seed = seed.as_ref().map(|s| core::str::from_utf8(s).expect("Seed is valid utf8!"));
1360		self.extension::<KeystoreExt>()
1361			.expect("No `keystore` associated for the current context!")
1362			.bls381_generate_new(id, seed)
1363			.expect("`bls381_generate` failed")
1364	}
1365
1366	/// Generate a 'bls12-381' Proof Of Possession for the corresponding public key.
1367	///
1368	/// Returns the Proof Of Possession as an option of the ['bls381::Signature'] type
1369	/// or 'None' if an error occurs.
1370	#[cfg(feature = "bls-experimental")]
1371	fn bls381_generate_proof_of_possession(
1372		&mut self,
1373		id: PassPointerAndReadCopy<KeyTypeId, 4>,
1374		pub_key: PassPointerAndRead<&bls381::Public, 144>,
1375		owner: PassFatPointerAndRead<&[u8]>,
1376	) -> AllocateAndReturnByCodec<Option<bls381::ProofOfPossession>> {
1377		self.extension::<KeystoreExt>()
1378			.expect("No `keystore` associated for the current context!")
1379			.bls381_generate_proof_of_possession(id, pub_key, owner)
1380			.ok()
1381			.flatten()
1382	}
1383
1384	/// Generate combination `ecdsa & bls12-381` key for the given key type using an optional `seed`
1385	/// and store it in the keystore.
1386	///
1387	/// The `seed` needs to be a valid utf8.
1388	///
1389	/// Returns the public key.
1390	#[cfg(feature = "bls-experimental")]
1391	fn ecdsa_bls381_generate(
1392		&mut self,
1393		id: PassPointerAndReadCopy<KeyTypeId, 4>,
1394		seed: PassFatPointerAndDecode<Option<Vec<u8>>>,
1395	) -> AllocateAndReturnPointer<ecdsa_bls381::Public, { 144 + 33 }> {
1396		let seed = seed.as_ref().map(|s| core::str::from_utf8(s).expect("Seed is valid utf8!"));
1397		self.extension::<KeystoreExt>()
1398			.expect("No `keystore` associated for the current context!")
1399			.ecdsa_bls381_generate_new(id, seed)
1400			.expect("`ecdsa_bls381_generate` failed")
1401	}
1402
1403	/// Generate a `bandersnatch` key pair for the given key type using an optional
1404	/// `seed` and store it in the keystore.
1405	///
1406	/// The `seed` needs to be a valid utf8.
1407	///
1408	/// Returns the public key.
1409	#[cfg(feature = "bandersnatch-experimental")]
1410	fn bandersnatch_generate(
1411		&mut self,
1412		id: PassPointerAndReadCopy<KeyTypeId, 4>,
1413		seed: PassFatPointerAndDecode<Option<Vec<u8>>>,
1414	) -> AllocateAndReturnPointer<bandersnatch::Public, 32> {
1415		let seed = seed.as_ref().map(|s| core::str::from_utf8(s).expect("Seed is valid utf8!"));
1416		self.extension::<KeystoreExt>()
1417			.expect("No `keystore` associated for the current context!")
1418			.bandersnatch_generate_new(id, seed)
1419			.expect("`bandernatch_generate` failed")
1420	}
1421
1422	/// Sign the given `msg` with the `bandersnatch` key that corresponds to the given public key
1423	/// and key type in the keystore.
1424	///
1425	/// Returns the signature or `None` if an error occurred.
1426	#[cfg(feature = "bandersnatch-experimental")]
1427	fn bandersnatch_sign(
1428		&mut self,
1429		id: PassPointerAndReadCopy<KeyTypeId, 4>,
1430		pub_key: PassPointerAndRead<&bandersnatch::Public, 32>,
1431		msg: PassFatPointerAndRead<&[u8]>,
1432	) -> AllocateAndReturnByCodec<Option<bandersnatch::Signature>> {
1433		self.extension::<KeystoreExt>()
1434			.expect("No `keystore` associated for the current context!")
1435			.bandersnatch_sign(id, pub_key, msg)
1436			.ok()
1437			.flatten()
1438	}
1439}
1440
1441/// Interface that provides functions for hashing with different algorithms.
1442#[runtime_interface]
1443pub trait Hashing {
1444	/// Conduct a 256-bit Keccak hash.
1445	fn keccak_256(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 32], 32> {
1446		sp_crypto_hashing::keccak_256(data)
1447	}
1448
1449	/// Conduct a 512-bit Keccak hash.
1450	fn keccak_512(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 64], 64> {
1451		sp_crypto_hashing::keccak_512(data)
1452	}
1453
1454	/// Conduct a 256-bit Sha2 hash.
1455	fn sha2_256(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 32], 32> {
1456		sp_crypto_hashing::sha2_256(data)
1457	}
1458
1459	/// Conduct a 128-bit Blake2 hash.
1460	fn blake2_128(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 16], 16> {
1461		sp_crypto_hashing::blake2_128(data)
1462	}
1463
1464	/// Conduct a 256-bit Blake2 hash.
1465	fn blake2_256(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 32], 32> {
1466		sp_crypto_hashing::blake2_256(data)
1467	}
1468
1469	/// Conduct four XX hashes to give a 256-bit result.
1470	fn twox_256(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 32], 32> {
1471		sp_crypto_hashing::twox_256(data)
1472	}
1473
1474	/// Conduct two XX hashes to give a 128-bit result.
1475	fn twox_128(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 16], 16> {
1476		sp_crypto_hashing::twox_128(data)
1477	}
1478
1479	/// Conduct two XX hashes to give a 64-bit result.
1480	fn twox_64(data: PassFatPointerAndRead<&[u8]>) -> AllocateAndReturnPointer<[u8; 8], 8> {
1481		sp_crypto_hashing::twox_64(data)
1482	}
1483}
1484
1485/// Interface that provides transaction indexing API.
1486#[runtime_interface]
1487pub trait TransactionIndex {
1488	/// Indexes the specified transaction for the given `extrinsic` and `context_hash`.
1489	fn index(
1490		&mut self,
1491		extrinsic: u32,
1492		size: u32,
1493		context_hash: PassPointerAndReadCopy<[u8; 32], 32>,
1494	) {
1495		self.storage_index_transaction(extrinsic, &context_hash, size);
1496	}
1497
1498	/// Renews the transaction index entry for the given `extrinsic` using the provided
1499	/// `context_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	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);
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);
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
2159	#[test]
2160	fn secp256k1_ecdsa_recover_valid_signature() {
2161		let pair = ecdsa::Pair::from_seed(b"12345678901234567890123456789012");
2162		let msg = sp_crypto_hashing::blake2_256(b"test message");
2163		let sig = pair.sign_prehashed(&msg);
2164
2165		assert!(ecdsa::is_signature_normalized(&sig.0));
2166
2167		let result = crypto::secp256k1_ecdsa_recover(&sig.0, &msg);
2168		assert!(result.is_ok());
2169		let recovered = ecdsa::Public::from_full(&result.ok().unwrap()).unwrap();
2170		assert_eq!(recovered, pair.public());
2171	}
2172
2173	#[test]
2174	fn secp256k1_ecdsa_recover_compressed_valid_signature() {
2175		let pair = ecdsa::Pair::from_seed(b"12345678901234567890123456789012");
2176		let msg = sp_crypto_hashing::blake2_256(b"test message");
2177		let sig = pair.sign_prehashed(&msg);
2178
2179		let result = crypto::secp256k1_ecdsa_recover_compressed(&sig.0, &msg);
2180		assert!(result.is_ok());
2181		assert_eq!(&result.ok().unwrap()[..], &pair.public().0[..]);
2182	}
2183
2184	#[test]
2185	fn ecdsa_verify_valid_signature() {
2186		let pair = ecdsa::Pair::from_seed(b"12345678901234567890123456789012");
2187		let message = b"test message";
2188		let sig = pair.sign(message);
2189
2190		assert!(ecdsa::is_signature_normalized(&sig.0));
2191		assert!(crypto::ecdsa_verify(&sig, message, &pair.public()));
2192	}
2193
2194	#[test]
2195	fn ecdsa_verify_prehashed_valid_signature() {
2196		let pair = ecdsa::Pair::from_seed(b"12345678901234567890123456789012");
2197		let msg = sp_crypto_hashing::blake2_256(b"test message");
2198		let sig = pair.sign_prehashed(&msg);
2199
2200		assert!(crypto::ecdsa_verify_prehashed(&sig, &msg, &pair.public()));
2201	}
2202
2203	#[test]
2204	fn ecdsa_verify_accepts_high_s_signatures() {
2205		fn make_high_s(sig: &ecdsa::Signature) -> ecdsa::Signature {
2206			let order: [u8; 32] = [
2207				0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
2208				0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c,
2209				0xd0, 0x36, 0x41, 0x41,
2210			];
2211			let s: [u8; 32] = sig.0[32..64].try_into().expect("slice has fixed length");
2212			let mut high_s = [0u8; 32];
2213			let mut borrow = 0i16;
2214			for i in (0..32).rev() {
2215				let diff = order[i] as i16 - s[i] as i16 - borrow;
2216				if diff < 0 {
2217					high_s[i] = (diff + 256) as u8;
2218					borrow = 1;
2219				} else {
2220					high_s[i] = diff as u8;
2221					borrow = 0;
2222				}
2223			}
2224
2225			let mut result = sig.0;
2226			result[32..64].copy_from_slice(&high_s);
2227			result[64] ^= 1;
2228			ecdsa::Signature::from_raw(result)
2229		}
2230
2231		let pair = ecdsa::Pair::from_seed(b"12345678901234567890123456789012");
2232		let message = b"test message";
2233		let signature = make_high_s(&pair.sign(message));
2234		assert!(!ecdsa::is_signature_normalized(&signature.0));
2235		assert!(crypto::ecdsa_verify(&signature, message, &pair.public()));
2236
2237		let prehash = sp_crypto_hashing::blake2_256(message);
2238		let signature = make_high_s(&pair.sign_prehashed(&prehash));
2239		assert!(!ecdsa::is_signature_normalized(&signature.0));
2240		assert!(crypto::ecdsa_verify_prehashed(&signature, &prehash, &pair.public()));
2241	}
2242
2243	#[test]
2244	fn storage_root_uses_passed_version() {
2245		// A value of 64 bytes exceeds `TRIE_VALUE_NODE_THRESHOLD`, so V0 and V1 produce
2246		// different roots. The legacy host functions must follow the passed version, not the one
2247		// the externalities were configured with.
2248		let value = vec![42u8; 64];
2249		let mut ext =
2250			TestExternalities::new_with_state_version(Storage::default(), StateVersion::V1);
2251
2252		ext.execute_with(|| {
2253			storage::set(b"key", &value);
2254
2255			// `TestExternalities` always inserts the (empty) `:code` entry.
2256			let top = vec![(b":code".to_vec(), Vec::new()), (b"key".to_vec(), value.clone())];
2257			assert_eq!(
2258				storage::root(StateVersion::V0),
2259				LayoutV0::<sp_core::Blake2Hasher>::trie_root(top.clone()).as_ref().to_vec()
2260			);
2261			assert_eq!(
2262				storage::root(StateVersion::V1),
2263				LayoutV1::<sp_core::Blake2Hasher>::trie_root(top).as_ref().to_vec()
2264			);
2265
2266			default_child_storage::set(b"child", b"ck", &value);
2267			let child = vec![(b"ck".to_vec(), value.clone())];
2268			assert_eq!(
2269				default_child_storage::root(b"child", StateVersion::V0),
2270				LayoutV0::<sp_core::Blake2Hasher>::trie_root(child.clone()).as_ref().to_vec()
2271			);
2272			assert_eq!(
2273				default_child_storage::root(b"child", StateVersion::V1),
2274				LayoutV1::<sp_core::Blake2Hasher>::trie_root(child).as_ref().to_vec()
2275			);
2276		});
2277	}
2278}