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

            
80
extern crate alloc;
81

            
82
use alloc::vec::Vec;
83

            
84
#[cfg(feature = "std")]
85
use tracing;
86

            
87
#[cfg(feature = "std")]
88
use sp_core::{
89
	crypto::Pair,
90
	hexdisplay::HexDisplay,
91
	offchain::{OffchainDbExt, OffchainWorkerExt, TransactionPoolExt},
92
	storage::ChildInfo,
93
};
94
#[cfg(feature = "std")]
95
use sp_keystore::KeystoreExt;
96

            
97
#[cfg(feature = "bandersnatch-experimental")]
98
use sp_core::bandersnatch;
99
use sp_core::{
100
	crypto::KeyTypeId,
101
	ecdsa, ed25519,
102
	offchain::{
103
		HttpError, HttpRequestId, HttpRequestStatus, OpaqueNetworkState, StorageKind, Timestamp,
104
	},
105
	sr25519,
106
	storage::StateVersion,
107
	LogLevel, LogLevelFilter, OpaquePeerId, H256,
108
};
109

            
110
#[cfg(feature = "bls-experimental")]
111
use sp_core::{bls377, ecdsa_bls377};
112

            
113
#[cfg(feature = "std")]
114
use sp_trie::{LayoutV0, LayoutV1, TrieConfiguration};
115

            
116
use sp_runtime_interface::{
117
	pass_by::{PassBy, PassByCodec},
118
	runtime_interface, Pointer,
119
};
120

            
121
use codec::{Decode, Encode};
122

            
123
#[cfg(feature = "std")]
124
use secp256k1::{
125
	ecdsa::{RecoverableSignature, RecoveryId},
126
	Message, SECP256K1,
127
};
128

            
129
#[cfg(feature = "std")]
130
use sp_externalities::{Externalities, ExternalitiesExt};
131

            
132
pub use sp_externalities::MultiRemovalResults;
133

            
134
#[cfg(all(not(feature = "disable_allocator"), substrate_runtime, target_family = "wasm"))]
135
mod global_alloc_wasm;
136

            
137
#[cfg(all(
138
	not(feature = "disable_allocator"),
139
	substrate_runtime,
140
	any(target_arch = "riscv32", target_arch = "riscv64")
141
))]
142
mod global_alloc_riscv;
143

            
144
#[cfg(feature = "std")]
145
const LOG_TARGET: &str = "runtime::io";
146

            
147
/// Error verifying ECDSA signature
148
#[derive(Encode, Decode)]
149
pub enum EcdsaVerifyError {
150
	/// Incorrect value of R or S
151
	BadRS,
152
	/// Incorrect value of V
153
	BadV,
154
	/// Invalid signature
155
	BadSignature,
156
}
157

            
158
/// The outcome of calling `storage_kill`. Returned value is the number of storage items
159
/// removed from the backend from making the `storage_kill` call.
160
#[derive(PassByCodec, Encode, Decode)]
161
pub enum KillStorageResult {
162
	/// All keys to remove were removed, return number of iterations performed during the
163
	/// operation.
164
	AllRemoved(u32),
165
	/// Not all key to remove were removed, return number of iterations performed during the
166
	/// operation.
167
	SomeRemaining(u32),
168
}
169

            
170
impl From<MultiRemovalResults> for KillStorageResult {
171
485966
	fn from(r: MultiRemovalResults) -> Self {
172
485966
		// We use `loops` here rather than `backend` because that's the same as the original
173
485966
		// functionality pre-#11490. This won't matter once we switch to the new host function
174
485966
		// since we won't be using the `KillStorageResult` type in the runtime any more.
175
485966
		match r.maybe_cursor {
176
485966
			None => Self::AllRemoved(r.loops),
177
			Some(..) => Self::SomeRemaining(r.loops),
178
		}
179
485966
	}
180
}
181

            
182
/// Interface for accessing the storage from within the runtime.
183
#[runtime_interface]
184
pub trait Storage {
185
29436154
	/// Returns the data for `key` in the storage or `None` if the key can not be found.
186
29436154
	fn get(&mut self, key: &[u8]) -> Option<bytes::Bytes> {
187
29436154
		self.storage(key).map(bytes::Bytes::from)
188
29436154
	}
189

            
190
208584
	/// Get `key` from storage, placing the value into `value_out` and return the number of
191
208584
	/// bytes that the entry in storage has beyond the offset or `None` if the storage entry
192
208584
	/// doesn't exist at all.
193
208584
	/// If `value_out` length is smaller than the returned length, only `value_out` length bytes
194
208584
	/// are copied into `value_out`.
195
208584
	fn read(&mut self, key: &[u8], value_out: &mut [u8], value_offset: u32) -> Option<u32> {
196
208584
		self.storage(key).map(|value| {
197
207200
			let value_offset = value_offset as usize;
198
207200
			let data = &value[value_offset.min(value.len())..];
199
207200
			let written = std::cmp::min(data.len(), value_out.len());
200
207200
			value_out[..written].copy_from_slice(&data[..written]);
201
207200
			data.len() as u32
202
208584
		})
203
208584
	}
204

            
205
10252606
	/// Set `key` to `value` in the storage.
206
10252606
	fn set(&mut self, key: &[u8], value: &[u8]) {
207
10252606
		self.set_storage(key.to_vec(), value.to_vec());
208
10252606
	}
209

            
210
3918690
	/// Clear the storage of the given `key` and its value.
211
3918690
	fn clear(&mut self, key: &[u8]) {
212
3918690
		self.clear_storage(key)
213
3918690
	}
214

            
215
1276444
	/// Check whether the given `key` exists in storage.
216
1276444
	fn exists(&mut self, key: &[u8]) -> bool {
217
1276444
		self.exists_storage(key)
218
1276444
	}
219

            
220
	/// Clear the storage of each key-value pair where the key starts with the given `prefix`.
221
	fn clear_prefix(&mut self, prefix: &[u8]) {
222
		let _ = Externalities::clear_prefix(*self, prefix, None, None);
223
	}
224

            
225
333512
	/// Clear the storage of each key-value pair where the key starts with the given `prefix`.
226
333512
	///
227
333512
	/// # Limit
228
333512
	///
229
333512
	/// Deletes all keys from the overlay and up to `limit` keys from the backend if
230
333512
	/// it is set to `Some`. No limit is applied when `limit` is set to `None`.
231
333512
	///
232
333512
	/// The limit can be used to partially delete a prefix storage in case it is too large
233
333512
	/// to delete in one go (block).
234
333512
	///
235
333512
	/// Returns [`KillStorageResult`] to inform about the result.
236
333512
	///
237
333512
	/// # Note
238
333512
	///
239
333512
	/// Please note that keys that are residing in the overlay for that prefix when
240
333512
	/// issuing this call are all deleted without counting towards the `limit`. Only keys
241
333512
	/// written during the current block are part of the overlay. Deleting with a `limit`
242
333512
	/// mostly makes sense with an empty overlay for that prefix.
243
333512
	///
244
333512
	/// Calling this function multiple times per block for the same `prefix` does
245
333512
	/// not make much sense because it is not cumulative when called inside the same block.
246
333512
	/// The deletion would always start from `prefix` resulting in the same keys being deleted
247
333512
	/// every time this function is called with the exact same arguments per block. This happens
248
333512
	/// because the keys in the overlay are not taken into account when deleting keys in the
249
333512
	/// backend.
250
333512
	#[version(2)]
251
333512
	fn clear_prefix(&mut self, prefix: &[u8], limit: Option<u32>) -> KillStorageResult {
252
333512
		Externalities::clear_prefix(*self, prefix, limit, None).into()
253
333512
	}
254

            
255
	/// Partially clear the storage of each key-value pair where the key starts with the given
256
	/// prefix.
257
	///
258
	/// # Limit
259
	///
260
	/// A *limit* should always be provided through `maybe_limit`. This is one fewer than the
261
	/// maximum number of backend iterations which may be done by this operation and as such
262
	/// represents the maximum number of backend deletions which may happen. A *limit* of zero
263
	/// implies that no keys will be deleted, though there may be a single iteration done.
264
	///
265
	/// The limit can be used to partially delete a prefix storage in case it is too large or costly
266
	/// to delete in a single operation.
267
	///
268
	/// # Cursor
269
	///
270
	/// A *cursor* may be passed in to this operation with `maybe_cursor`. `None` should only be
271
	/// passed once (in the initial call) for any given `maybe_prefix` value. Subsequent calls
272
	/// operating on the same prefix should always pass `Some`, and this should be equal to the
273
	/// previous call result's `maybe_cursor` field.
274
	///
275
	/// Returns [`MultiRemovalResults`](sp_io::MultiRemovalResults) to inform about the result. Once
276
	/// the resultant `maybe_cursor` field is `None`, then no further items remain to be deleted.
277
	///
278
	/// NOTE: After the initial call for any given prefix, it is important that no keys further
279
	/// keys under the same prefix are inserted. If so, then they may or may not be deleted by
280
	/// subsequent calls.
281
	///
282
	/// # Note
283
	///
284
	/// Please note that keys which are residing in the overlay for that prefix when
285
	/// issuing this call are deleted without counting towards the `limit`.
286
	#[version(3, register_only)]
287
	fn clear_prefix(
288
		&mut self,
289
		maybe_prefix: &[u8],
290
		maybe_limit: Option<u32>,
291
		maybe_cursor: Option<Vec<u8>>, //< TODO Make work or just Option<Vec<u8>>?
292
	) -> MultiRemovalResults {
293
		Externalities::clear_prefix(
294
			*self,
295
			maybe_prefix,
296
			maybe_limit,
297
			maybe_cursor.as_ref().map(|x| &x[..]),
298
		)
299
		.into()
300
	}
301

            
302
574310
	/// Append the encoded `value` to the storage item at `key`.
303
574310
	///
304
574310
	/// The storage item needs to implement [`EncodeAppend`](codec::EncodeAppend).
305
574310
	///
306
574310
	/// # Warning
307
574310
	///
308
574310
	/// If the storage item does not support [`EncodeAppend`](codec::EncodeAppend) or
309
574310
	/// something else fails at appending, the storage item will be set to `[value]`.
310
574310
	fn append(&mut self, key: &[u8], value: Vec<u8>) {
311
574310
		self.storage_append(key.to_vec(), value);
312
574310
	}
313

            
314
	/// "Commit" all existing operations and compute the resulting storage root.
315
	///
316
	/// The hashing algorithm is defined by the `Block`.
317
	///
318
	/// Returns a `Vec<u8>` that holds the SCALE encoded hash.
319
	fn root(&mut self) -> Vec<u8> {
320
		self.storage_root(StateVersion::V0)
321
	}
322

            
323
129842
	/// "Commit" all existing operations and compute the resulting storage root.
324
129842
	///
325
129842
	/// The hashing algorithm is defined by the `Block`.
326
129842
	///
327
129842
	/// Returns a `Vec<u8>` that holds the SCALE encoded hash.
328
129842
	#[version(2)]
329
129842
	fn root(&mut self, version: StateVersion) -> Vec<u8> {
330
129842
		self.storage_root(version)
331
129842
	}
332

            
333
	/// Always returns `None`. This function exists for compatibility reasons.
334
	fn changes_root(&mut self, _parent_hash: &[u8]) -> Option<Vec<u8>> {
335
		None
336
	}
337

            
338
2126002
	/// Get the next key in storage after the given one in lexicographic order.
339
2126002
	fn next_key(&mut self, key: &[u8]) -> Option<Vec<u8>> {
340
2126002
		self.next_storage_key(key)
341
2126002
	}
342

            
343
593658
	/// Start a new nested transaction.
344
593658
	///
345
593658
	/// This allows to either commit or roll back all changes that are made after this call.
346
593658
	/// For every transaction there must be a matching call to either `rollback_transaction`
347
593658
	/// or `commit_transaction`. This is also effective for all values manipulated using the
348
593658
	/// `DefaultChildStorage` API.
349
593658
	///
350
593658
	/// # Warning
351
593658
	///
352
593658
	/// This is a low level API that is potentially dangerous as it can easily result
353
593658
	/// in unbalanced transactions. For example, FRAME users should use high level storage
354
593658
	/// abstractions.
355
593658
	fn start_transaction(&mut self) {
356
593658
		self.storage_start_transaction();
357
593658
	}
358

            
359
111424
	/// Rollback the last transaction started by `start_transaction`.
360
111424
	///
361
111424
	/// Any changes made during that transaction are discarded.
362
111424
	///
363
111424
	/// # Panics
364
111424
	///
365
111424
	/// Will panic if there is no open transaction.
366
111424
	fn rollback_transaction(&mut self) {
367
111424
		self.storage_rollback_transaction()
368
111424
			.expect("No open transaction that can be rolled back.");
369
111424
	}
370

            
371
482234
	/// Commit the last transaction started by `start_transaction`.
372
482234
	///
373
482234
	/// Any changes made during that transaction are committed.
374
482234
	///
375
482234
	/// # Panics
376
482234
	///
377
482234
	/// Will panic if there is no open transaction.
378
482234
	fn commit_transaction(&mut self) {
379
482234
		self.storage_commit_transaction()
380
482234
			.expect("No open transaction that can be committed.");
381
482234
	}
382
}
383

            
384
/// Interface for accessing the child storage for default child trie,
385
/// from within the runtime.
386
#[runtime_interface]
387
pub trait DefaultChildStorage {
388
	/// Get a default child storage value for a given key.
389
	///
390
	/// Parameter `storage_key` is the unprefixed location of the root of the child trie in the
391
	/// parent trie. Result is `None` if the value for `key` in the child storage can not be found.
392
	fn get(&mut self, storage_key: &[u8], key: &[u8]) -> Option<Vec<u8>> {
393
		let child_info = ChildInfo::new_default(storage_key);
394
		self.child_storage(&child_info, key).map(|s| s.to_vec())
395
	}
396

            
397
	/// Allocation efficient variant of `get`.
398
	///
399
	/// Get `key` from child storage, placing the value into `value_out` and return the number
400
	/// of bytes that the entry in storage has beyond the offset or `None` if the storage entry
401
	/// doesn't exist at all.
402
	/// If `value_out` length is smaller than the returned length, only `value_out` length bytes
403
	/// are copied into `value_out`.
404
	fn read(
405
		&mut self,
406
		storage_key: &[u8],
407
		key: &[u8],
408
		value_out: &mut [u8],
409
		value_offset: u32,
410
	) -> Option<u32> {
411
		let child_info = ChildInfo::new_default(storage_key);
412
		self.child_storage(&child_info, key).map(|value| {
413
			let value_offset = value_offset as usize;
414
			let data = &value[value_offset.min(value.len())..];
415
			let written = std::cmp::min(data.len(), value_out.len());
416
			value_out[..written].copy_from_slice(&data[..written]);
417
			data.len() as u32
418
		})
419
	}
420

            
421
	/// Set a child storage value.
422
	///
423
	/// Set `key` to `value` in the child storage denoted by `storage_key`.
424
	fn set(&mut self, storage_key: &[u8], key: &[u8], value: &[u8]) {
425
		let child_info = ChildInfo::new_default(storage_key);
426
		self.set_child_storage(&child_info, key.to_vec(), value.to_vec());
427
	}
428

            
429
	/// Clear a child storage key.
430
	///
431
	/// For the default child storage at `storage_key`, clear value at `key`.
432
	fn clear(&mut self, storage_key: &[u8], key: &[u8]) {
433
		let child_info = ChildInfo::new_default(storage_key);
434
		self.clear_child_storage(&child_info, key);
435
	}
436

            
437
	/// Clear an entire child storage.
438
	///
439
	/// If it exists, the child storage for `storage_key`
440
	/// is removed.
441
	fn storage_kill(&mut self, storage_key: &[u8]) {
442
		let child_info = ChildInfo::new_default(storage_key);
443
		let _ = self.kill_child_storage(&child_info, None, None);
444
	}
445

            
446
	/// Clear a child storage key.
447
	///
448
	/// See `Storage` module `clear_prefix` documentation for `limit` usage.
449
	#[version(2)]
450
	fn storage_kill(&mut self, storage_key: &[u8], limit: Option<u32>) -> bool {
451
		let child_info = ChildInfo::new_default(storage_key);
452
		let r = self.kill_child_storage(&child_info, limit, None);
453
		r.maybe_cursor.is_none()
454
	}
455

            
456
	/// Clear a child storage key.
457
	///
458
	/// See `Storage` module `clear_prefix` documentation for `limit` usage.
459
	#[version(3)]
460
	fn storage_kill(&mut self, storage_key: &[u8], limit: Option<u32>) -> KillStorageResult {
461
		let child_info = ChildInfo::new_default(storage_key);
462
		self.kill_child_storage(&child_info, limit, None).into()
463
	}
464

            
465
	/// Clear a child storage key.
466
	///
467
	/// See `Storage` module `clear_prefix` documentation for `limit` usage.
468
	#[version(4, register_only)]
469
	fn storage_kill(
470
		&mut self,
471
		storage_key: &[u8],
472
		maybe_limit: Option<u32>,
473
		maybe_cursor: Option<Vec<u8>>,
474
	) -> MultiRemovalResults {
475
		let child_info = ChildInfo::new_default(storage_key);
476
		self.kill_child_storage(&child_info, maybe_limit, maybe_cursor.as_ref().map(|x| &x[..]))
477
			.into()
478
	}
479

            
480
	/// Check a child storage key.
481
	///
482
	/// Check whether the given `key` exists in default child defined at `storage_key`.
483
	fn exists(&mut self, storage_key: &[u8], key: &[u8]) -> bool {
484
		let child_info = ChildInfo::new_default(storage_key);
485
		self.exists_child_storage(&child_info, key)
486
	}
487

            
488
	/// Clear child default key by prefix.
489
	///
490
	/// Clear the child storage of each key-value pair where the key starts with the given `prefix`.
491
	fn clear_prefix(&mut self, storage_key: &[u8], prefix: &[u8]) {
492
		let child_info = ChildInfo::new_default(storage_key);
493
		let _ = self.clear_child_prefix(&child_info, prefix, None, None);
494
	}
495

            
496
	/// Clear the child storage of each key-value pair where the key starts with the given `prefix`.
497
	///
498
	/// See `Storage` module `clear_prefix` documentation for `limit` usage.
499
	#[version(2)]
500
	fn clear_prefix(
501
		&mut self,
502
		storage_key: &[u8],
503
		prefix: &[u8],
504
		limit: Option<u32>,
505
	) -> KillStorageResult {
506
		let child_info = ChildInfo::new_default(storage_key);
507
		self.clear_child_prefix(&child_info, prefix, limit, None).into()
508
	}
509

            
510
	/// Clear the child storage of each key-value pair where the key starts with the given `prefix`.
511
	///
512
	/// See `Storage` module `clear_prefix` documentation for `limit` usage.
513
	#[version(3, register_only)]
514
	fn clear_prefix(
515
		&mut self,
516
		storage_key: &[u8],
517
		prefix: &[u8],
518
		maybe_limit: Option<u32>,
519
		maybe_cursor: Option<Vec<u8>>,
520
	) -> MultiRemovalResults {
521
		let child_info = ChildInfo::new_default(storage_key);
522
		self.clear_child_prefix(
523
			&child_info,
524
			prefix,
525
			maybe_limit,
526
			maybe_cursor.as_ref().map(|x| &x[..]),
527
		)
528
		.into()
529
	}
530

            
531
	/// Default child root calculation.
532
	///
533
	/// "Commit" all existing operations and compute the resulting child storage root.
534
	/// The hashing algorithm is defined by the `Block`.
535
	///
536
	/// Returns a `Vec<u8>` that holds the SCALE encoded hash.
537
	fn root(&mut self, storage_key: &[u8]) -> Vec<u8> {
538
		let child_info = ChildInfo::new_default(storage_key);
539
		self.child_storage_root(&child_info, StateVersion::V0)
540
	}
541

            
542
	/// Default child root calculation.
543
	///
544
	/// "Commit" all existing operations and compute the resulting child storage root.
545
	/// The hashing algorithm is defined by the `Block`.
546
	///
547
	/// Returns a `Vec<u8>` that holds the SCALE encoded hash.
548
	#[version(2)]
549
	fn root(&mut self, storage_key: &[u8], version: StateVersion) -> Vec<u8> {
550
		let child_info = ChildInfo::new_default(storage_key);
551
		self.child_storage_root(&child_info, version)
552
	}
553

            
554
	/// Child storage key iteration.
555
	///
556
	/// Get the next key in storage after the given one in lexicographic order in child storage.
557
	fn next_key(&mut self, storage_key: &[u8], key: &[u8]) -> Option<Vec<u8>> {
558
		let child_info = ChildInfo::new_default(storage_key);
559
		self.next_child_storage_key(&child_info, key)
560
	}
561
}
562

            
563
/// Interface that provides trie related functionality.
564
#[runtime_interface]
565
pub trait Trie {
566
	/// A trie root formed from the iterated items.
567
	fn blake2_256_root(input: Vec<(Vec<u8>, Vec<u8>)>) -> H256 {
568
		LayoutV0::<sp_core::Blake2Hasher>::trie_root(input)
569
	}
570

            
571
	/// A trie root formed from the iterated items.
572
	#[version(2)]
573
	fn blake2_256_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> H256 {
574
		match version {
575
			StateVersion::V0 => LayoutV0::<sp_core::Blake2Hasher>::trie_root(input),
576
			StateVersion::V1 => LayoutV1::<sp_core::Blake2Hasher>::trie_root(input),
577
		}
578
	}
579

            
580
	/// A trie root formed from the enumerated items.
581
	fn blake2_256_ordered_root(input: Vec<Vec<u8>>) -> H256 {
582
		LayoutV0::<sp_core::Blake2Hasher>::ordered_trie_root(input)
583
	}
584

            
585
129842
	/// A trie root formed from the enumerated items.
586
129842
	#[version(2)]
587
129842
	fn blake2_256_ordered_root(input: Vec<Vec<u8>>, version: StateVersion) -> H256 {
588
129842
		match version {
589
129842
			StateVersion::V0 => LayoutV0::<sp_core::Blake2Hasher>::ordered_trie_root(input),
590
129842
			StateVersion::V1 => LayoutV1::<sp_core::Blake2Hasher>::ordered_trie_root(input),
591
129842
		}
592
259684
	}
593

            
594
	/// A trie root formed from the iterated items.
595
	fn keccak_256_root(input: Vec<(Vec<u8>, Vec<u8>)>) -> H256 {
596
		LayoutV0::<sp_core::KeccakHasher>::trie_root(input)
597
	}
598

            
599
	/// A trie root formed from the iterated items.
600
	#[version(2)]
601
	fn keccak_256_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> H256 {
602
		match version {
603
			StateVersion::V0 => LayoutV0::<sp_core::KeccakHasher>::trie_root(input),
604
			StateVersion::V1 => LayoutV1::<sp_core::KeccakHasher>::trie_root(input),
605
		}
606
	}
607

            
608
	/// A trie root formed from the enumerated items.
609
	fn keccak_256_ordered_root(input: Vec<Vec<u8>>) -> H256 {
610
		LayoutV0::<sp_core::KeccakHasher>::ordered_trie_root(input)
611
	}
612

            
613
	/// A trie root formed from the enumerated items.
614
	#[version(2)]
615
	fn keccak_256_ordered_root(input: Vec<Vec<u8>>, version: StateVersion) -> H256 {
616
		match version {
617
			StateVersion::V0 => LayoutV0::<sp_core::KeccakHasher>::ordered_trie_root(input),
618
			StateVersion::V1 => LayoutV1::<sp_core::KeccakHasher>::ordered_trie_root(input),
619
		}
620
	}
621

            
622
	/// Verify trie proof
623
	fn blake2_256_verify_proof(root: H256, proof: &[Vec<u8>], key: &[u8], value: &[u8]) -> bool {
624
		sp_trie::verify_trie_proof::<LayoutV0<sp_core::Blake2Hasher>, _, _, _>(
625
			&root,
626
			proof,
627
			&[(key, Some(value))],
628
		)
629
		.is_ok()
630
	}
631

            
632
	/// Verify trie proof
633
	#[version(2)]
634
	fn blake2_256_verify_proof(
635
		root: H256,
636
		proof: &[Vec<u8>],
637
		key: &[u8],
638
		value: &[u8],
639
		version: StateVersion,
640
	) -> bool {
641
		match version {
642
			StateVersion::V0 => sp_trie::verify_trie_proof::<
643
				LayoutV0<sp_core::Blake2Hasher>,
644
				_,
645
				_,
646
				_,
647
			>(&root, proof, &[(key, Some(value))])
648
			.is_ok(),
649
			StateVersion::V1 => sp_trie::verify_trie_proof::<
650
				LayoutV1<sp_core::Blake2Hasher>,
651
				_,
652
				_,
653
				_,
654
			>(&root, proof, &[(key, Some(value))])
655
			.is_ok(),
656
		}
657
	}
658

            
659
	/// Verify trie proof
660
	fn keccak_256_verify_proof(root: H256, proof: &[Vec<u8>], key: &[u8], value: &[u8]) -> bool {
661
		sp_trie::verify_trie_proof::<LayoutV0<sp_core::KeccakHasher>, _, _, _>(
662
			&root,
663
			proof,
664
			&[(key, Some(value))],
665
		)
666
		.is_ok()
667
	}
668

            
669
	/// Verify trie proof
670
	#[version(2)]
671
	fn keccak_256_verify_proof(
672
		root: H256,
673
		proof: &[Vec<u8>],
674
		key: &[u8],
675
		value: &[u8],
676
		version: StateVersion,
677
	) -> bool {
678
		match version {
679
			StateVersion::V0 => sp_trie::verify_trie_proof::<
680
				LayoutV0<sp_core::KeccakHasher>,
681
				_,
682
				_,
683
				_,
684
			>(&root, proof, &[(key, Some(value))])
685
			.is_ok(),
686
			StateVersion::V1 => sp_trie::verify_trie_proof::<
687
				LayoutV1<sp_core::KeccakHasher>,
688
				_,
689
				_,
690
				_,
691
			>(&root, proof, &[(key, Some(value))])
692
			.is_ok(),
693
		}
694
	}
695
}
696

            
697
/// Interface that provides miscellaneous functions for communicating between the runtime and the
698
/// node.
699
#[runtime_interface]
700
pub trait Misc {
701
	// NOTE: We use the target 'runtime' for messages produced by general printing functions,
702
	// instead of LOG_TARGET.
703

            
704
	/// Print a number.
705
	fn print_num(val: u64) {
706
		log::debug!(target: "runtime", "{}", val);
707
	}
708

            
709
	/// Print any valid `utf8` buffer.
710
	fn print_utf8(utf8: &[u8]) {
711
		if let Ok(data) = std::str::from_utf8(utf8) {
712
			log::debug!(target: "runtime", "{}", data)
713
		}
714
	}
715

            
716
	/// Print any `u8` slice as hex.
717
	fn print_hex(data: &[u8]) {
718
		log::debug!(target: "runtime", "{}", HexDisplay::from(&data));
719
	}
720

            
721
	/// Extract the runtime version of the given wasm blob by calling `Core_version`.
722
	///
723
	/// Returns `None` if calling the function failed for any reason or `Some(Vec<u8>)` where
724
	/// the `Vec<u8>` holds the SCALE encoded runtime version.
725
	///
726
	/// # Performance
727
	///
728
	/// This function may be very expensive to call depending on the wasm binary. It may be
729
	/// relatively cheap if the wasm binary contains version information. In that case,
730
	/// uncompression of the wasm blob is the dominating factor.
731
	///
732
	/// If the wasm binary does not have the version information attached, then a legacy mechanism
733
	/// may be involved. This means that a runtime call will be performed to query the version.
734
	///
735
	/// Calling into the runtime may be incredible expensive and should be approached with care.
736
	fn runtime_version(&mut self, wasm: &[u8]) -> Option<Vec<u8>> {
737
		use sp_core::traits::ReadRuntimeVersionExt;
738

            
739
		let mut ext = sp_state_machine::BasicExternalities::default();
740

            
741
		match self
742
			.extension::<ReadRuntimeVersionExt>()
743
			.expect("No `ReadRuntimeVersionExt` associated for the current context!")
744
			.read_runtime_version(wasm, &mut ext)
745
		{
746
			Ok(v) => Some(v),
747
			Err(err) => {
748
				log::debug!(
749
					target: LOG_TARGET,
750
					"cannot read version from the given runtime: {}",
751
					err,
752
				);
753
				None
754
			},
755
		}
756
	}
757
}
758

            
759
#[cfg(feature = "std")]
760
sp_externalities::decl_extension! {
761
	/// Extension to signal to [`crypt::ed25519_verify`] to use the dalek crate.
762
	///
763
	/// The switch from `ed25519-dalek` to `ed25519-zebra` was a breaking change.
764
	/// `ed25519-zebra` is more permissive when it comes to the verification of signatures.
765
	/// This means that some chains may fail to sync from genesis when using `ed25519-zebra`.
766
	/// So, this extension can be registered to the runtime execution environment to signal
767
	/// that `ed25519-dalek` should be used for verification. The extension can be registered
768
	/// in the following way:
769
	///
770
	/// ```nocompile
771
	/// client.execution_extensions().set_extensions_factory(
772
	/// 	// Let the `UseDalekExt` extension being registered for each runtime invocation
773
	/// 	// until the execution happens in the context of block `1000`.
774
	/// 	sc_client_api::execution_extensions::ExtensionBeforeBlock::<Block, UseDalekExt>::new(1000)
775
	/// );
776
	/// ```
777
	pub struct UseDalekExt;
778
}
779

            
780
#[cfg(feature = "std")]
781
impl Default for UseDalekExt {
782
	fn default() -> Self {
783
		Self
784
	}
785
}
786

            
787
/// Interfaces for working with crypto related types from within the runtime.
788
#[runtime_interface]
789
pub trait Crypto {
790
	/// Returns all `ed25519` public keys for the given key id from the keystore.
791
	fn ed25519_public_keys(&mut self, id: KeyTypeId) -> Vec<ed25519::Public> {
792
		self.extension::<KeystoreExt>()
793
			.expect("No `keystore` associated for the current context!")
794
			.ed25519_public_keys(id)
795
	}
796

            
797
	/// Generate an `ed22519` key for the given key type using an optional `seed` and
798
	/// store it in the keystore.
799
	///
800
	/// The `seed` needs to be a valid utf8.
801
	///
802
	/// Returns the public key.
803
	fn ed25519_generate(&mut self, id: KeyTypeId, seed: Option<Vec<u8>>) -> ed25519::Public {
804
		let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!"));
805
		self.extension::<KeystoreExt>()
806
			.expect("No `keystore` associated for the current context!")
807
			.ed25519_generate_new(id, seed)
808
			.expect("`ed25519_generate` failed")
809
	}
810

            
811
	/// Sign the given `msg` with the `ed25519` key that corresponds to the given public key and
812
	/// key type in the keystore.
813
	///
814
	/// Returns the signature.
815
	fn ed25519_sign(
816
		&mut self,
817
		id: KeyTypeId,
818
		pub_key: &ed25519::Public,
819
		msg: &[u8],
820
	) -> Option<ed25519::Signature> {
821
		self.extension::<KeystoreExt>()
822
			.expect("No `keystore` associated for the current context!")
823
			.ed25519_sign(id, pub_key, msg)
824
			.ok()
825
			.flatten()
826
	}
827

            
828
1876
	/// Verify `ed25519` signature.
829
1876
	///
830
1876
	/// Returns `true` when the verification was successful.
831
1876
	fn ed25519_verify(sig: &ed25519::Signature, msg: &[u8], pub_key: &ed25519::Public) -> bool {
832
1876
		// We don't want to force everyone needing to call the function in an externalities context.
833
1876
		// So, we assume that we should not use dalek when we are not in externalities context.
834
1876
		// Otherwise, we check if the extension is present.
835
1876
		if sp_externalities::with_externalities(|mut e| e.extension::<UseDalekExt>().is_some())
836
1876
			.unwrap_or_default()
837
1876
		{
838
1876
			use ed25519_dalek::Verifier;
839
1876

            
840
1876
			let Ok(public_key) = ed25519_dalek::VerifyingKey::from_bytes(&pub_key.0) else {
841
1876
				return false
842
1876
			};
843
1876

            
844
1876
			let sig = ed25519_dalek::Signature::from_bytes(&sig.0);
845

            
846
			public_key.verify(msg, &sig).is_ok()
847
1876
		} else {
848
1876
			ed25519::Pair::verify(sig, msg, pub_key)
849
1876
		}
850
3752
	}
851

            
852
	/// Register a `ed25519` signature for batch verification.
853
	///
854
	/// Batch verification must be enabled by calling [`start_batch_verify`].
855
	/// If batch verification is not enabled, the signature will be verified immediately.
856
	/// To get the result of the batch verification, [`finish_batch_verify`]
857
	/// needs to be called.
858
	///
859
	/// Returns `true` when the verification is either successful or batched.
860
	///
861
	/// NOTE: Is tagged with `register_only` to keep the functions around for backwards
862
	/// compatibility with old runtimes, but it should not be used anymore by new runtimes.
863
	/// The implementation emulates the old behavior, but isn't doing any batch verification
864
	/// anymore.
865
	#[version(1, register_only)]
866
	fn ed25519_batch_verify(
867
		&mut self,
868
		sig: &ed25519::Signature,
869
		msg: &[u8],
870
		pub_key: &ed25519::Public,
871
	) -> bool {
872
		let res = ed25519_verify(sig, msg, pub_key);
873

            
874
		if let Some(ext) = self.extension::<VerificationExtDeprecated>() {
875
			ext.0 &= res;
876
		}
877

            
878
		res
879
	}
880

            
881
	/// Verify `sr25519` signature.
882
	///
883
	/// Returns `true` when the verification was successful.
884
	#[version(2)]
885
	fn sr25519_verify(sig: &sr25519::Signature, msg: &[u8], pub_key: &sr25519::Public) -> bool {
886
		sr25519::Pair::verify(sig, msg, pub_key)
887
	}
888

            
889
	/// Register a `sr25519` signature for batch verification.
890
	///
891
	/// Batch verification must be enabled by calling [`start_batch_verify`].
892
	/// If batch verification is not enabled, the signature will be verified immediately.
893
	/// To get the result of the batch verification, [`finish_batch_verify`]
894
	/// needs to be called.
895
	///
896
	/// Returns `true` when the verification is either successful or batched.
897
	///
898
	/// NOTE: Is tagged with `register_only` to keep the functions around for backwards
899
	/// compatibility with old runtimes, but it should not be used anymore by new runtimes.
900
	/// The implementation emulates the old behavior, but isn't doing any batch verification
901
	/// anymore.
902
	#[version(1, register_only)]
903
	fn sr25519_batch_verify(
904
		&mut self,
905
		sig: &sr25519::Signature,
906
		msg: &[u8],
907
		pub_key: &sr25519::Public,
908
	) -> bool {
909
		let res = sr25519_verify(sig, msg, pub_key);
910

            
911
		if let Some(ext) = self.extension::<VerificationExtDeprecated>() {
912
			ext.0 &= res;
913
		}
914

            
915
		res
916
	}
917

            
918
	/// Start verification extension.
919
	///
920
	/// NOTE: Is tagged with `register_only` to keep the functions around for backwards
921
	/// compatibility with old runtimes, but it should not be used anymore by new runtimes.
922
	/// The implementation emulates the old behavior, but isn't doing any batch verification
923
	/// anymore.
924
	#[version(1, register_only)]
925
	fn start_batch_verify(&mut self) {
926
		self.register_extension(VerificationExtDeprecated(true))
927
			.expect("Failed to register required extension: `VerificationExt`");
928
	}
929

            
930
	/// Finish batch-verification of signatures.
931
	///
932
	/// Verify or wait for verification to finish for all signatures which were previously
933
	/// deferred by `sr25519_verify`/`ed25519_verify`.
934
	///
935
	/// Will panic if no `VerificationExt` is registered (`start_batch_verify` was not called).
936
	///
937
	/// NOTE: Is tagged with `register_only` to keep the functions around for backwards
938
	/// compatibility with old runtimes, but it should not be used anymore by new runtimes.
939
	/// The implementation emulates the old behavior, but isn't doing any batch verification
940
	/// anymore.
941
	#[version(1, register_only)]
942
	fn finish_batch_verify(&mut self) -> bool {
943
		let result = self
944
			.extension::<VerificationExtDeprecated>()
945
			.expect("`finish_batch_verify` should only be called after `start_batch_verify`")
946
			.0;
947

            
948
		self.deregister_extension::<VerificationExtDeprecated>()
949
			.expect("No verification extension in current context!");
950

            
951
		result
952
	}
953

            
954
	/// Returns all `sr25519` public keys for the given key id from the keystore.
955
	fn sr25519_public_keys(&mut self, id: KeyTypeId) -> Vec<sr25519::Public> {
956
		self.extension::<KeystoreExt>()
957
			.expect("No `keystore` associated for the current context!")
958
			.sr25519_public_keys(id)
959
	}
960

            
961
	/// Generate an `sr22519` key for the given key type using an optional seed and
962
	/// store it in the keystore.
963
	///
964
	/// The `seed` needs to be a valid utf8.
965
	///
966
	/// Returns the public key.
967
	fn sr25519_generate(&mut self, id: KeyTypeId, seed: Option<Vec<u8>>) -> sr25519::Public {
968
		let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!"));
969
		self.extension::<KeystoreExt>()
970
			.expect("No `keystore` associated for the current context!")
971
			.sr25519_generate_new(id, seed)
972
			.expect("`sr25519_generate` failed")
973
	}
974

            
975
	/// Sign the given `msg` with the `sr25519` key that corresponds to the given public key and
976
	/// key type in the keystore.
977
	///
978
	/// Returns the signature.
979
	fn sr25519_sign(
980
		&mut self,
981
		id: KeyTypeId,
982
		pub_key: &sr25519::Public,
983
		msg: &[u8],
984
	) -> Option<sr25519::Signature> {
985
		self.extension::<KeystoreExt>()
986
			.expect("No `keystore` associated for the current context!")
987
			.sr25519_sign(id, pub_key, msg)
988
			.ok()
989
			.flatten()
990
	}
991

            
992
	/// Verify an `sr25519` signature.
993
	///
994
	/// Returns `true` when the verification in successful regardless of
995
	/// signature version.
996
	fn sr25519_verify(sig: &sr25519::Signature, msg: &[u8], pubkey: &sr25519::Public) -> bool {
997
		sr25519::Pair::verify_deprecated(sig, msg, pubkey)
998
	}
999

            
	/// Returns all `ecdsa` public keys for the given key id from the keystore.
	fn ecdsa_public_keys(&mut self, id: KeyTypeId) -> Vec<ecdsa::Public> {
		self.extension::<KeystoreExt>()
			.expect("No `keystore` associated for the current context!")
			.ecdsa_public_keys(id)
	}
	/// Generate an `ecdsa` key for the given key type using an optional `seed` and
	/// store it in the keystore.
	///
	/// The `seed` needs to be a valid utf8.
	///
	/// Returns the public key.
	fn ecdsa_generate(&mut self, id: KeyTypeId, seed: Option<Vec<u8>>) -> ecdsa::Public {
		let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!"));
		self.extension::<KeystoreExt>()
			.expect("No `keystore` associated for the current context!")
			.ecdsa_generate_new(id, seed)
			.expect("`ecdsa_generate` failed")
	}
	/// Sign the given `msg` with the `ecdsa` key that corresponds to the given public key and
	/// key type in the keystore.
	///
	/// Returns the signature.
	fn ecdsa_sign(
		&mut self,
		id: KeyTypeId,
		pub_key: &ecdsa::Public,
		msg: &[u8],
	) -> Option<ecdsa::Signature> {
		self.extension::<KeystoreExt>()
			.expect("No `keystore` associated for the current context!")
			.ecdsa_sign(id, pub_key, msg)
			.ok()
			.flatten()
	}
	/// Sign the given a pre-hashed `msg` with the `ecdsa` key that corresponds to the given public
	/// key and key type in the keystore.
	///
	/// Returns the signature.
	fn ecdsa_sign_prehashed(
		&mut self,
		id: KeyTypeId,
		pub_key: &ecdsa::Public,
		msg: &[u8; 32],
	) -> Option<ecdsa::Signature> {
		self.extension::<KeystoreExt>()
			.expect("No `keystore` associated for the current context!")
			.ecdsa_sign_prehashed(id, pub_key, msg)
			.ok()
			.flatten()
	}
	/// Verify `ecdsa` signature.
	///
	/// Returns `true` when the verification was successful.
	/// This version is able to handle, non-standard, overflowing signatures.
	fn ecdsa_verify(sig: &ecdsa::Signature, msg: &[u8], pub_key: &ecdsa::Public) -> bool {
		#[allow(deprecated)]
		ecdsa::Pair::verify_deprecated(sig, msg, pub_key)
	}
	/// Verify `ecdsa` signature.
	///
	/// Returns `true` when the verification was successful.
	#[version(2)]
	fn ecdsa_verify(sig: &ecdsa::Signature, msg: &[u8], pub_key: &ecdsa::Public) -> bool {
		ecdsa::Pair::verify(sig, msg, pub_key)
	}
	/// Verify `ecdsa` signature with pre-hashed `msg`.
	///
	/// Returns `true` when the verification was successful.
	fn ecdsa_verify_prehashed(
		sig: &ecdsa::Signature,
		msg: &[u8; 32],
		pub_key: &ecdsa::Public,
	) -> bool {
		ecdsa::Pair::verify_prehashed(sig, msg, pub_key)
	}
	/// Register a `ecdsa` signature for batch verification.
	///
	/// Batch verification must be enabled by calling [`start_batch_verify`].
	/// If batch verification is not enabled, the signature will be verified immediately.
	/// To get the result of the batch verification, [`finish_batch_verify`]
	/// needs to be called.
	///
	/// Returns `true` when the verification is either successful or batched.
	///
	/// NOTE: Is tagged with `register_only` to keep the functions around for backwards
	/// compatibility with old runtimes, but it should not be used anymore by new runtimes.
	/// The implementation emulates the old behavior, but isn't doing any batch verification
	/// anymore.
	#[version(1, register_only)]
	fn ecdsa_batch_verify(
		&mut self,
		sig: &ecdsa::Signature,
		msg: &[u8],
		pub_key: &ecdsa::Public,
	) -> bool {
		let res = ecdsa_verify(sig, msg, pub_key);
		if let Some(ext) = self.extension::<VerificationExtDeprecated>() {
			ext.0 &= res;
		}
		res
	}
	/// Verify and recover a SECP256k1 ECDSA signature.
	///
	/// - `sig` is passed in RSV format. V should be either `0/1` or `27/28`.
	/// - `msg` is the blake2-256 hash of the message.
	///
	/// Returns `Err` if the signature is bad, otherwise the 64-byte pubkey
	/// (doesn't include the 0x04 prefix).
	/// This version is able to handle, non-standard, overflowing signatures.
	fn secp256k1_ecdsa_recover(
		sig: &[u8; 65],
		msg: &[u8; 32],
	) -> Result<[u8; 64], EcdsaVerifyError> {
		let rid = libsecp256k1::RecoveryId::parse(
			if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as u8,
		)
		.map_err(|_| EcdsaVerifyError::BadV)?;
		let sig = libsecp256k1::Signature::parse_overflowing_slice(&sig[..64])
			.map_err(|_| EcdsaVerifyError::BadRS)?;
		let msg = libsecp256k1::Message::parse(msg);
		let pubkey =
			libsecp256k1::recover(&msg, &sig, &rid).map_err(|_| EcdsaVerifyError::BadSignature)?;
		let mut res = [0u8; 64];
		res.copy_from_slice(&pubkey.serialize()[1..65]);
		Ok(res)
	}
	/// Verify and recover a SECP256k1 ECDSA signature.
	///
	/// - `sig` is passed in RSV format. V should be either `0/1` or `27/28`.
	/// - `msg` is the blake2-256 hash of the message.
	///
	/// Returns `Err` if the signature is bad, otherwise the 64-byte pubkey
	/// (doesn't include the 0x04 prefix).
	#[version(2)]
	fn secp256k1_ecdsa_recover(
		sig: &[u8; 65],
		msg: &[u8; 32],
	) -> Result<[u8; 64], EcdsaVerifyError> {
		let rid = RecoveryId::from_i32(if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as i32)
			.map_err(|_| EcdsaVerifyError::BadV)?;
		let sig = RecoverableSignature::from_compact(&sig[..64], rid)
			.map_err(|_| EcdsaVerifyError::BadRS)?;
		let msg = Message::from_digest_slice(msg).expect("Message is 32 bytes; qed");
		let pubkey = SECP256K1
			.recover_ecdsa(&msg, &sig)
			.map_err(|_| EcdsaVerifyError::BadSignature)?;
		let mut res = [0u8; 64];
		res.copy_from_slice(&pubkey.serialize_uncompressed()[1..]);
		Ok(res)
	}
	/// Verify and recover a SECP256k1 ECDSA signature.
	///
	/// - `sig` is passed in RSV format. V should be either `0/1` or `27/28`.
	/// - `msg` is the blake2-256 hash of the message.
	///
	/// Returns `Err` if the signature is bad, otherwise the 33-byte compressed pubkey.
	fn secp256k1_ecdsa_recover_compressed(
		sig: &[u8; 65],
		msg: &[u8; 32],
	) -> Result<[u8; 33], EcdsaVerifyError> {
		let rid = libsecp256k1::RecoveryId::parse(
			if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as u8,
		)
		.map_err(|_| EcdsaVerifyError::BadV)?;
		let sig = libsecp256k1::Signature::parse_overflowing_slice(&sig[0..64])
			.map_err(|_| EcdsaVerifyError::BadRS)?;
		let msg = libsecp256k1::Message::parse(msg);
		let pubkey =
			libsecp256k1::recover(&msg, &sig, &rid).map_err(|_| EcdsaVerifyError::BadSignature)?;
		Ok(pubkey.serialize_compressed())
	}
	/// Verify and recover a SECP256k1 ECDSA signature.
	///
	/// - `sig` is passed in RSV format. V should be either `0/1` or `27/28`.
	/// - `msg` is the blake2-256 hash of the message.
	///
	/// Returns `Err` if the signature is bad, otherwise the 33-byte compressed pubkey.
	#[version(2)]
	fn secp256k1_ecdsa_recover_compressed(
		sig: &[u8; 65],
		msg: &[u8; 32],
	) -> Result<[u8; 33], EcdsaVerifyError> {
		let rid = RecoveryId::from_i32(if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as i32)
			.map_err(|_| EcdsaVerifyError::BadV)?;
		let sig = RecoverableSignature::from_compact(&sig[..64], rid)
			.map_err(|_| EcdsaVerifyError::BadRS)?;
		let msg = Message::from_digest_slice(msg).expect("Message is 32 bytes; qed");
		let pubkey = SECP256K1
			.recover_ecdsa(&msg, &sig)
			.map_err(|_| EcdsaVerifyError::BadSignature)?;
		Ok(pubkey.serialize())
	}
	/// Generate an `bls12-377` key for the given key type using an optional `seed` and
	/// store it in the keystore.
	///
	/// The `seed` needs to be a valid utf8.
	///
	/// Returns the public key.
	#[cfg(feature = "bls-experimental")]
	fn bls377_generate(&mut self, id: KeyTypeId, seed: Option<Vec<u8>>) -> bls377::Public {
		let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!"));
		self.extension::<KeystoreExt>()
			.expect("No `keystore` associated for the current context!")
			.bls377_generate_new(id, seed)
			.expect("`bls377_generate` failed")
	}
	/// Generate an `(ecdsa,bls12-377)` key for the given key type using an optional `seed` and
	/// store it in the keystore.
	///
	/// The `seed` needs to be a valid utf8.
	///
	/// Returns the public key.
	#[cfg(feature = "bls-experimental")]
	fn ecdsa_bls377_generate(
		&mut self,
		id: KeyTypeId,
		seed: Option<Vec<u8>>,
	) -> ecdsa_bls377::Public {
		let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!"));
		self.extension::<KeystoreExt>()
			.expect("No `keystore` associated for the current context!")
			.ecdsa_bls377_generate_new(id, seed)
			.expect("`ecdsa_bls377_generate` failed")
	}
	/// Generate a `bandersnatch` key pair for the given key type using an optional
	/// `seed` and store it in the keystore.
	///
	/// The `seed` needs to be a valid utf8.
	///
	/// Returns the public key.
	#[cfg(feature = "bandersnatch-experimental")]
	fn bandersnatch_generate(
		&mut self,
		id: KeyTypeId,
		seed: Option<Vec<u8>>,
	) -> bandersnatch::Public {
		let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!"));
		self.extension::<KeystoreExt>()
			.expect("No `keystore` associated for the current context!")
			.bandersnatch_generate_new(id, seed)
			.expect("`bandernatch_generate` failed")
	}
}
/// Interface that provides functions for hashing with different algorithms.
#[runtime_interface]
pub trait Hashing {
426388
	/// Conduct a 256-bit Keccak hash.
426388
	fn keccak_256(data: &[u8]) -> [u8; 32] {
426388
		sp_crypto_hashing::keccak_256(data)
426388
	}
	/// Conduct a 512-bit Keccak hash.
	fn keccak_512(data: &[u8]) -> [u8; 64] {
		sp_crypto_hashing::keccak_512(data)
	}
	/// Conduct a 256-bit Sha2 hash.
	fn sha2_256(data: &[u8]) -> [u8; 32] {
		sp_crypto_hashing::sha2_256(data)
	}
913914
	/// Conduct a 128-bit Blake2 hash.
913914
	fn blake2_128(data: &[u8]) -> [u8; 16] {
913914
		sp_crypto_hashing::blake2_128(data)
913914
	}
532924
	/// Conduct a 256-bit Blake2 hash.
532924
	fn blake2_256(data: &[u8]) -> [u8; 32] {
532924
		sp_crypto_hashing::blake2_256(data)
532924
	}
	/// Conduct four XX hashes to give a 256-bit result.
	fn twox_256(data: &[u8]) -> [u8; 32] {
		sp_crypto_hashing::twox_256(data)
	}
11751384
	/// Conduct two XX hashes to give a 128-bit result.
11751384
	fn twox_128(data: &[u8]) -> [u8; 16] {
11751384
		sp_crypto_hashing::twox_128(data)
11751384
	}
3782344
	/// Conduct two XX hashes to give a 64-bit result.
3782344
	fn twox_64(data: &[u8]) -> [u8; 8] {
3782344
		sp_crypto_hashing::twox_64(data)
3782344
	}
}
/// Interface that provides transaction indexing API.
#[runtime_interface]
pub trait TransactionIndex {
	/// Add transaction index. Returns indexed content hash.
	fn index(&mut self, extrinsic: u32, size: u32, context_hash: [u8; 32]) {
		self.storage_index_transaction(extrinsic, &context_hash, size);
	}
	/// Conduct a 512-bit Keccak hash.
	fn renew(&mut self, extrinsic: u32, context_hash: [u8; 32]) {
		self.storage_renew_transaction_index(extrinsic, &context_hash);
	}
}
/// Interface that provides functions to access the Offchain DB.
#[runtime_interface]
pub trait OffchainIndex {
305862
	/// Write a key value pair to the Offchain DB database in a buffered fashion.
305862
	fn set(&mut self, key: &[u8], value: &[u8]) {
305862
		self.set_offchain_storage(key, Some(value));
305862
	}
	/// Remove a key and its associated value from the Offchain DB.
	fn clear(&mut self, key: &[u8]) {
		self.set_offchain_storage(key, None);
	}
}
#[cfg(feature = "std")]
sp_externalities::decl_extension! {
	/// Deprecated verification context.
	///
	/// Stores the combined result of all verifications that are done in the same context.
	struct VerificationExtDeprecated(bool);
}
/// Interface that provides functions to access the offchain functionality.
///
/// These functions are being made available to the runtime and are called by the runtime.
#[runtime_interface]
pub trait Offchain {
	/// Returns if the local node is a potential validator.
	///
	/// Even if this function returns `true`, it does not mean that any keys are configured
	/// and that the validator is registered in the chain.
	fn is_validator(&mut self) -> bool {
		self.extension::<OffchainWorkerExt>()
			.expect("is_validator can be called only in the offchain worker context")
			.is_validator()
	}
	/// Submit an encoded transaction to the pool.
	///
	/// The transaction will end up in the pool.
	fn submit_transaction(&mut self, data: Vec<u8>) -> Result<(), ()> {
		self.extension::<TransactionPoolExt>()
			.expect(
				"submit_transaction can be called only in the offchain call context with
				TransactionPool capabilities enabled",
			)
			.submit_transaction(data)
	}
	/// Returns information about the local node's network state.
	fn network_state(&mut self) -> Result<OpaqueNetworkState, ()> {
		self.extension::<OffchainWorkerExt>()
			.expect("network_state can be called only in the offchain worker context")
			.network_state()
	}
	/// Returns current UNIX timestamp (in millis)
	fn timestamp(&mut self) -> Timestamp {
		self.extension::<OffchainWorkerExt>()
			.expect("timestamp can be called only in the offchain worker context")
			.timestamp()
	}
	/// Pause the execution until `deadline` is reached.
	fn sleep_until(&mut self, deadline: Timestamp) {
		self.extension::<OffchainWorkerExt>()
			.expect("sleep_until can be called only in the offchain worker context")
			.sleep_until(deadline)
	}
	/// Returns a random seed.
	///
	/// This is a truly random, non-deterministic seed generated by host environment.
	/// Obviously fine in the off-chain worker context.
	fn random_seed(&mut self) -> [u8; 32] {
		self.extension::<OffchainWorkerExt>()
			.expect("random_seed can be called only in the offchain worker context")
			.random_seed()
	}
	/// Sets a value in the local storage.
	///
	/// Note this storage is not part of the consensus, it's only accessible by
	/// offchain worker tasks running on the same machine. It IS persisted between runs.
	fn local_storage_set(&mut self, kind: StorageKind, key: &[u8], value: &[u8]) {
		self.extension::<OffchainDbExt>()
			.expect(
				"local_storage_set can be called only in the offchain call context with
				OffchainDb extension",
			)
			.local_storage_set(kind, key, value)
	}
	/// Remove a value from the local storage.
	///
	/// Note this storage is not part of the consensus, it's only accessible by
	/// offchain worker tasks running on the same machine. It IS persisted between runs.
	fn local_storage_clear(&mut self, kind: StorageKind, key: &[u8]) {
		self.extension::<OffchainDbExt>()
			.expect(
				"local_storage_clear can be called only in the offchain call context with
				OffchainDb extension",
			)
			.local_storage_clear(kind, key)
	}
	/// Sets a value in the local storage if it matches current value.
	///
	/// Since multiple offchain workers may be running concurrently, to prevent
	/// data races use CAS to coordinate between them.
	///
	/// Returns `true` if the value has been set, `false` otherwise.
	///
	/// Note this storage is not part of the consensus, it's only accessible by
	/// offchain worker tasks running on the same machine. It IS persisted between runs.
	fn local_storage_compare_and_set(
		&mut self,
		kind: StorageKind,
		key: &[u8],
		old_value: Option<Vec<u8>>,
		new_value: &[u8],
	) -> bool {
		self.extension::<OffchainDbExt>()
			.expect(
				"local_storage_compare_and_set can be called only in the offchain call context
				with OffchainDb extension",
			)
			.local_storage_compare_and_set(kind, key, old_value.as_deref(), new_value)
	}
	/// Gets a value from the local storage.
	///
	/// If the value does not exist in the storage `None` will be returned.
	/// Note this storage is not part of the consensus, it's only accessible by
	/// offchain worker tasks running on the same machine. It IS persisted between runs.
	fn local_storage_get(&mut self, kind: StorageKind, key: &[u8]) -> Option<Vec<u8>> {
		self.extension::<OffchainDbExt>()
			.expect(
				"local_storage_get can be called only in the offchain call context with
				OffchainDb extension",
			)
			.local_storage_get(kind, key)
	}
	/// Initiates a http request given HTTP verb and the URL.
	///
	/// Meta is a future-reserved field containing additional, parity-scale-codec encoded
	/// parameters. Returns the id of newly started request.
	fn http_request_start(
		&mut self,
		method: &str,
		uri: &str,
		meta: &[u8],
	) -> Result<HttpRequestId, ()> {
		self.extension::<OffchainWorkerExt>()
			.expect("http_request_start can be called only in the offchain worker context")
			.http_request_start(method, uri, meta)
	}
	/// Append header to the request.
	fn http_request_add_header(
		&mut self,
		request_id: HttpRequestId,
		name: &str,
		value: &str,
	) -> Result<(), ()> {
		self.extension::<OffchainWorkerExt>()
			.expect("http_request_add_header can be called only in the offchain worker context")
			.http_request_add_header(request_id, name, value)
	}
	/// Write a chunk of request body.
	///
	/// Writing an empty chunks finalizes the request.
	/// Passing `None` as deadline blocks forever.
	///
	/// Returns an error in case deadline is reached or the chunk couldn't be written.
	fn http_request_write_body(
		&mut self,
		request_id: HttpRequestId,
		chunk: &[u8],
		deadline: Option<Timestamp>,
	) -> Result<(), HttpError> {
		self.extension::<OffchainWorkerExt>()
			.expect("http_request_write_body can be called only in the offchain worker context")
			.http_request_write_body(request_id, chunk, deadline)
	}
	/// Block and wait for the responses for given requests.
	///
	/// Returns a vector of request statuses (the len is the same as ids).
	/// Note that if deadline is not provided the method will block indefinitely,
	/// otherwise unready responses will produce `DeadlineReached` status.
	///
	/// Passing `None` as deadline blocks forever.
	fn http_response_wait(
		&mut self,
		ids: &[HttpRequestId],
		deadline: Option<Timestamp>,
	) -> Vec<HttpRequestStatus> {
		self.extension::<OffchainWorkerExt>()
			.expect("http_response_wait can be called only in the offchain worker context")
			.http_response_wait(ids, deadline)
	}
	/// Read all response headers.
	///
	/// Returns a vector of pairs `(HeaderKey, HeaderValue)`.
	/// NOTE: response headers have to be read before response body.
	fn http_response_headers(&mut self, request_id: HttpRequestId) -> Vec<(Vec<u8>, Vec<u8>)> {
		self.extension::<OffchainWorkerExt>()
			.expect("http_response_headers can be called only in the offchain worker context")
			.http_response_headers(request_id)
	}
	/// Read a chunk of body response to given buffer.
	///
	/// Returns the number of bytes written or an error in case a deadline
	/// is reached or server closed the connection.
	/// If `0` is returned it means that the response has been fully consumed
	/// and the `request_id` is now invalid.
	/// NOTE: this implies that response headers must be read before draining the body.
	/// Passing `None` as a deadline blocks forever.
	fn http_response_read_body(
		&mut self,
		request_id: HttpRequestId,
		buffer: &mut [u8],
		deadline: Option<Timestamp>,
	) -> Result<u32, HttpError> {
		self.extension::<OffchainWorkerExt>()
			.expect("http_response_read_body can be called only in the offchain worker context")
			.http_response_read_body(request_id, buffer, deadline)
			.map(|r| r as u32)
	}
	/// Set the authorized nodes and authorized_only flag.
	fn set_authorized_nodes(&mut self, nodes: Vec<OpaquePeerId>, authorized_only: bool) {
		self.extension::<OffchainWorkerExt>()
			.expect("set_authorized_nodes can be called only in the offchain worker context")
			.set_authorized_nodes(nodes, authorized_only)
	}
}
/// Wasm only interface that provides functions for calling into the allocator.
#[runtime_interface(wasm_only)]
pub trait Allocator {
	/// Malloc the given number of bytes and return the pointer to the allocated memory location.
	fn malloc(&mut self, size: u32) -> Pointer<u8> {
		self.allocate_memory(size).expect("Failed to allocate memory")
	}
	/// Free the given pointer.
	fn free(&mut self, ptr: Pointer<u8>) {
		self.deallocate_memory(ptr).expect("Failed to deallocate memory")
	}
}
/// WASM-only interface which allows for aborting the execution in case
/// of an unrecoverable error.
#[runtime_interface(wasm_only)]
pub trait PanicHandler {
	/// Aborts the current execution with the given error message.
	#[trap_on_return]
	fn abort_on_panic(&mut self, message: &str) {
		self.register_panic_error_message(message);
	}
}
/// Interface that provides functions for logging from within the runtime.
#[runtime_interface]
pub trait Logging {
	/// Request to print a log message on the host.
	///
	/// Note that this will be only displayed if the host is enabled to display log messages with
	/// given level and target.
	///
	/// Instead of using directly, prefer setting up `RuntimeLogger` and using `log` macros.
	fn log(level: LogLevel, target: &str, message: &[u8]) {
		if let Ok(message) = std::str::from_utf8(message) {
			log::log!(target: target, log::Level::from(level), "{}", message)
		}
	}
	/// Returns the max log level used by the host.
	fn max_level() -> LogLevelFilter {
		log::max_level().into()
	}
}
#[derive(Encode, Decode)]
/// Crossing is a helper wrapping any Encode-Decodeable type
/// for transferring over the wasm barrier.
pub struct Crossing<T: Encode + Decode>(T);
impl<T: Encode + Decode> PassBy for Crossing<T> {
	type PassBy = sp_runtime_interface::pass_by::Codec<Self>;
}
impl<T: Encode + Decode> Crossing<T> {
	/// Convert into the inner type
	pub fn into_inner(self) -> T {
		self.0
	}
}
// useful for testing
impl<T> core::default::Default for Crossing<T>
where
	T: core::default::Default + Encode + Decode,
{
	fn default() -> Self {
		Self(Default::default())
	}
}
/// Interface to provide tracing facilities for wasm. Modelled after tokios `tracing`-crate
/// interfaces. See `sp-tracing` for more information.
#[runtime_interface(wasm_only, no_tracing)]
pub trait WasmTracing {
	/// Whether the span described in `WasmMetadata` should be traced wasm-side
	/// On the host converts into a static Metadata and checks against the global `tracing`
	/// dispatcher.
	///
	/// When returning false the calling code should skip any tracing-related execution. In general
	/// within the same block execution this is not expected to change and it doesn't have to be
	/// checked more than once per metadata. This exists for optimisation purposes but is still not
	/// cheap as it will jump the wasm-native-barrier every time it is called. So an implementation
	/// might chose to cache the result for the execution of the entire block.
	fn enabled(&mut self, metadata: Crossing<sp_tracing::WasmMetadata>) -> bool {
		let metadata: &tracing_core::metadata::Metadata<'static> = (&metadata.into_inner()).into();
		tracing::dispatcher::get_default(|d| d.enabled(metadata))
	}
	/// Open a new span with the given attributes. Return the u64 Id of the span.
	///
	/// On the native side this goes through the default `tracing` dispatcher to register the span
	/// and then calls `clone_span` with the ID to signal that we are keeping it around on the wasm-
	/// side even after the local span is dropped. The resulting ID is then handed over to the wasm-
	/// side.
	fn enter_span(&mut self, span: Crossing<sp_tracing::WasmEntryAttributes>) -> u64 {
		let span: tracing::Span = span.into_inner().into();
		match span.id() {
			Some(id) => tracing::dispatcher::get_default(|d| {
				// inform dispatch that we'll keep the ID around
				// then enter it immediately
				let final_id = d.clone_span(&id);
				d.enter(&final_id);
				final_id.into_u64()
			}),
			_ => 0,
		}
	}
	/// Emit the given event to the global tracer on the native side
	fn event(&mut self, event: Crossing<sp_tracing::WasmEntryAttributes>) {
		event.into_inner().emit();
	}
	/// Signal that a given span-id has been exited. On native, this directly
	/// proxies the span to the global dispatcher.
	fn exit(&mut self, span: u64) {
		tracing::dispatcher::get_default(|d| {
			let id = tracing_core::span::Id::from_u64(span);
			d.exit(&id);
		});
	}
}
#[cfg(all(not(feature = "std"), feature = "with-tracing"))]
mod tracing_setup {
	use super::{wasm_tracing, Crossing};
	use core::sync::atomic::{AtomicBool, Ordering};
	use tracing_core::{
		dispatcher::{set_global_default, Dispatch},
		span::{Attributes, Id, Record},
		Event, Metadata,
	};
	static TRACING_SET: AtomicBool = AtomicBool::new(false);
	/// The PassingTracingSubscriber implements `tracing_core::Subscriber`
	/// and pushes the information across the runtime interface to the host
	struct PassingTracingSubscriber;
	impl tracing_core::Subscriber for PassingTracingSubscriber {
		fn enabled(&self, metadata: &Metadata<'_>) -> bool {
			wasm_tracing::enabled(Crossing(metadata.into()))
		}
		fn new_span(&self, attrs: &Attributes<'_>) -> Id {
			Id::from_u64(wasm_tracing::enter_span(Crossing(attrs.into())))
		}
		fn enter(&self, _: &Id) {
			// Do nothing, we already entered the span previously
		}
		/// Not implemented! We do not support recording values later
		/// Will panic when used.
		fn record(&self, _: &Id, _: &Record<'_>) {
			unimplemented! {} // this usage is not supported
		}
		/// Not implemented! We do not support recording values later
		/// Will panic when used.
		fn record_follows_from(&self, _: &Id, _: &Id) {
			unimplemented! {} // this usage is not supported
		}
		fn event(&self, event: &Event<'_>) {
			wasm_tracing::event(Crossing(event.into()))
		}
		fn exit(&self, span: &Id) {
			wasm_tracing::exit(span.into_u64())
		}
	}
	/// Initialize tracing of sp_tracing on wasm with `with-tracing` enabled.
	/// Can be called multiple times from within the same process and will only
	/// set the global bridging subscriber once.
	pub fn init_tracing() {
		if TRACING_SET.load(Ordering::Relaxed) == false {
			set_global_default(Dispatch::new(PassingTracingSubscriber {}))
				.expect("We only ever call this once");
			TRACING_SET.store(true, Ordering::Relaxed);
		}
	}
}
#[cfg(not(all(not(feature = "std"), feature = "with-tracing")))]
mod tracing_setup {
	/// Initialize tracing of sp_tracing not necessary – noop. To enable build
	/// without std and with the `with-tracing`-feature.
1168578
	pub fn init_tracing() {}
}
pub use tracing_setup::init_tracing;
/// Crashes the execution of the program.
///
/// Equivalent to the WASM `unreachable` instruction, RISC-V `unimp` instruction,
/// or just the `unreachable!()` macro everywhere else.
pub fn unreachable() -> ! {
	#[cfg(target_family = "wasm")]
	{
		core::arch::wasm32::unreachable();
	}
	#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
	unsafe {
		core::arch::asm!("unimp", options(noreturn));
	}
	#[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64", target_family = "wasm")))]
	unreachable!();
}
/// A default panic handler for the runtime environment.
#[cfg(all(not(feature = "disable_panic_handler"), substrate_runtime))]
#[panic_handler]
#[no_mangle]
pub fn panic(info: &core::panic::PanicInfo) -> ! {
	let message = alloc::format!("{}", info);
	#[cfg(feature = "improved_panic_error_reporting")]
	{
		panic_handler::abort_on_panic(&message);
	}
	#[cfg(not(feature = "improved_panic_error_reporting"))]
	{
		logging::log(LogLevel::Error, "runtime", message.as_bytes());
		unreachable();
	}
}
/// A default OOM handler for the runtime environment.
#[cfg(all(not(feature = "disable_oom"), enable_alloc_error_handler))]
#[alloc_error_handler]
pub fn oom(_: core::alloc::Layout) -> ! {
	#[cfg(feature = "improved_panic_error_reporting")]
	{
		panic_handler::abort_on_panic("Runtime memory exhausted.");
	}
	#[cfg(not(feature = "improved_panic_error_reporting"))]
	{
		logging::log(LogLevel::Error, "runtime", b"Runtime memory exhausted. Aborting");
		unreachable();
	}
}
/// Type alias for Externalities implementation used in tests.
#[cfg(feature = "std")]
pub type TestExternalities = sp_state_machine::TestExternalities<sp_core::Blake2Hasher>;
/// The host functions Substrate provides for the Wasm runtime environment.
///
/// All these host functions will be callable from inside the Wasm environment.
#[docify::export]
#[cfg(feature = "std")]
pub type SubstrateHostFunctions = (
	storage::HostFunctions,
	default_child_storage::HostFunctions,
	misc::HostFunctions,
	wasm_tracing::HostFunctions,
	offchain::HostFunctions,
	crypto::HostFunctions,
	hashing::HostFunctions,
	allocator::HostFunctions,
	panic_handler::HostFunctions,
	logging::HostFunctions,
	crate::trie::HostFunctions,
	offchain_index::HostFunctions,
	transaction_index::HostFunctions,
);
#[cfg(test)]
mod tests {
	use super::*;
	use sp_core::{crypto::UncheckedInto, map, storage::Storage};
	use sp_state_machine::BasicExternalities;
	#[test]
	fn storage_works() {
		let mut t = BasicExternalities::default();
		t.execute_with(|| {
			assert_eq!(storage::get(b"hello"), None);
			storage::set(b"hello", b"world");
			assert_eq!(storage::get(b"hello"), Some(b"world".to_vec().into()));
			assert_eq!(storage::get(b"foo"), None);
			storage::set(b"foo", &[1, 2, 3][..]);
		});
		t = BasicExternalities::new(Storage {
			top: map![b"foo".to_vec() => b"bar".to_vec()],
			children_default: map![],
		});
		t.execute_with(|| {
			assert_eq!(storage::get(b"hello"), None);
			assert_eq!(storage::get(b"foo"), Some(b"bar".to_vec().into()));
		});
		let value = vec![7u8; 35];
		let storage =
			Storage { top: map![b"foo00".to_vec() => value.clone()], children_default: map![] };
		t = BasicExternalities::new(storage);
		t.execute_with(|| {
			assert_eq!(storage::get(b"hello"), None);
			assert_eq!(storage::get(b"foo00"), Some(value.clone().into()));
		});
	}
	#[test]
	fn read_storage_works() {
		let value = b"\x0b\0\0\0Hello world".to_vec();
		let mut t = BasicExternalities::new(Storage {
			top: map![b":test".to_vec() => value.clone()],
			children_default: map![],
		});
		t.execute_with(|| {
			let mut v = [0u8; 4];
			assert_eq!(storage::read(b":test", &mut v[..], 0).unwrap(), value.len() as u32);
			assert_eq!(v, [11u8, 0, 0, 0]);
			let mut w = [0u8; 11];
			assert_eq!(storage::read(b":test", &mut w[..], 4).unwrap(), value.len() as u32 - 4);
			assert_eq!(&w, b"Hello world");
		});
	}
	#[test]
	fn clear_prefix_works() {
		let mut t = BasicExternalities::new(Storage {
			top: map![
				b":a".to_vec() => b"\x0b\0\0\0Hello world".to_vec(),
				b":abcd".to_vec() => b"\x0b\0\0\0Hello world".to_vec(),
				b":abc".to_vec() => b"\x0b\0\0\0Hello world".to_vec(),
				b":abdd".to_vec() => b"\x0b\0\0\0Hello world".to_vec()
			],
			children_default: map![],
		});
		t.execute_with(|| {
			// We can switch to this once we enable v3 of the `clear_prefix`.
			//assert!(matches!(
			//	storage::clear_prefix(b":abc", None),
			//	MultiRemovalResults::NoneLeft { db: 2, total: 2 }
			//));
			assert!(matches!(
				storage::clear_prefix(b":abc", None),
				KillStorageResult::AllRemoved(2),
			));
			assert!(storage::get(b":a").is_some());
			assert!(storage::get(b":abdd").is_some());
			assert!(storage::get(b":abcd").is_none());
			assert!(storage::get(b":abc").is_none());
			// We can switch to this once we enable v3 of the `clear_prefix`.
			//assert!(matches!(
			//	storage::clear_prefix(b":abc", None),
			//	MultiRemovalResults::NoneLeft { db: 0, total: 0 }
			//));
			assert!(matches!(
				storage::clear_prefix(b":abc", None),
				KillStorageResult::AllRemoved(0),
			));
		});
	}
	fn zero_ed_pub() -> ed25519::Public {
		[0u8; 32].unchecked_into()
	}
	fn zero_ed_sig() -> ed25519::Signature {
		ed25519::Signature::from_raw([0u8; 64])
	}
	#[test]
	fn use_dalek_ext_works() {
		let mut ext = BasicExternalities::default();
		ext.register_extension(UseDalekExt::default());
		// With dalek the zero signature should fail to verify.
		ext.execute_with(|| {
			assert!(!crypto::ed25519_verify(&zero_ed_sig(), &Vec::new(), &zero_ed_pub()));
		});
		// But with zebra it should work.
		BasicExternalities::default().execute_with(|| {
			assert!(crypto::ed25519_verify(&zero_ed_sig(), &Vec::new(), &zero_ed_pub()));
		})
	}
	#[test]
	fn dalek_should_not_panic_on_invalid_signature() {
		let mut ext = BasicExternalities::default();
		ext.register_extension(UseDalekExt::default());
		ext.execute_with(|| {
			let mut bytes = [0u8; 64];
			// Make it invalid
			bytes[63] = 0b1110_0000;
			assert!(!crypto::ed25519_verify(
				&ed25519::Signature::from_raw(bytes),
				&Vec::new(),
				&zero_ed_pub()
			));
		});
	}
}