sp_runtime/
testing.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Testing utilities.
19
20use crate::{
21	codec::{Codec, Decode, Encode, MaxEncodedLen},
22	generic::{self, UncheckedExtrinsic},
23	scale_info::TypeInfo,
24	traits::{self, BlakeTwo256, Dispatchable, OpaqueKeys},
25	DispatchResultWithInfo, KeyTypeId,
26};
27use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize};
28use sp_core::crypto::{key_types, ByteArray, CryptoType, Dummy};
29pub use sp_core::{sr25519, H256};
30use std::{cell::RefCell, fmt::Debug};
31
32/// A dummy type which can be used instead of regular cryptographic primitives.
33///
34/// 1. Wraps a `u64` `AccountId` and is able to `IdentifyAccount`.
35/// 2. Can be converted to any `Public` key.
36/// 3. Implements `RuntimeAppPublic` so it can be used instead of regular application-specific
37///    crypto.
38#[derive(
39	Default,
40	PartialEq,
41	Eq,
42	Clone,
43	Encode,
44	Decode,
45	Debug,
46	Hash,
47	Serialize,
48	Deserialize,
49	PartialOrd,
50	Ord,
51	MaxEncodedLen,
52	TypeInfo,
53)]
54pub struct UintAuthorityId(pub u64);
55
56impl From<u64> for UintAuthorityId {
57	fn from(id: u64) -> Self {
58		UintAuthorityId(id)
59	}
60}
61
62impl From<UintAuthorityId> for u64 {
63	fn from(id: UintAuthorityId) -> u64 {
64		id.0
65	}
66}
67
68impl UintAuthorityId {
69	/// Convert this authority ID into a public key.
70	pub fn to_public_key<T: ByteArray>(&self) -> T {
71		let mut bytes = [0u8; 32];
72		bytes[0..8].copy_from_slice(&self.0.to_le_bytes());
73		T::from_slice(&bytes).unwrap()
74	}
75
76	/// Set the list of keys returned by the runtime call for all keys of that type.
77	pub fn set_all_keys<T: Into<UintAuthorityId>>(keys: impl IntoIterator<Item = T>) {
78		ALL_KEYS.with(|l| *l.borrow_mut() = keys.into_iter().map(Into::into).collect())
79	}
80}
81
82impl CryptoType for UintAuthorityId {
83	type Pair = Dummy;
84}
85
86impl AsRef<[u8]> for UintAuthorityId {
87	fn as_ref(&self) -> &[u8] {
88		// Unsafe, i know, but it's test code and it's just there because it's really convenient to
89		// keep `UintAuthorityId` as a u64 under the hood.
90		unsafe {
91			std::slice::from_raw_parts(
92				&self.0 as *const u64 as *const _,
93				std::mem::size_of::<u64>(),
94			)
95		}
96	}
97}
98
99thread_local! {
100	/// A list of all UintAuthorityId keys returned to the runtime.
101	static ALL_KEYS: RefCell<Vec<UintAuthorityId>> = RefCell::new(vec![]);
102}
103
104impl sp_application_crypto::RuntimeAppPublic for UintAuthorityId {
105	const ID: KeyTypeId = key_types::DUMMY;
106
107	type Signature = TestSignature;
108
109	fn all() -> Vec<Self> {
110		ALL_KEYS.with(|l| l.borrow().clone())
111	}
112
113	fn generate_pair(_: Option<Vec<u8>>) -> Self {
114		use rand::RngCore;
115		UintAuthorityId(rand::thread_rng().next_u64())
116	}
117
118	fn sign<M: AsRef<[u8]>>(&self, msg: &M) -> Option<Self::Signature> {
119		Some(TestSignature(self.0, msg.as_ref().to_vec()))
120	}
121
122	fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool {
123		traits::Verify::verify(signature, msg.as_ref(), &self.0)
124	}
125
126	fn to_raw_vec(&self) -> Vec<u8> {
127		AsRef::<[u8]>::as_ref(self).to_vec()
128	}
129}
130
131impl OpaqueKeys for UintAuthorityId {
132	type KeyTypeIdProviders = ();
133
134	fn key_ids() -> &'static [KeyTypeId] {
135		&[key_types::DUMMY]
136	}
137
138	fn get_raw(&self, _: KeyTypeId) -> &[u8] {
139		self.as_ref()
140	}
141
142	fn get<T: Decode>(&self, _: KeyTypeId) -> Option<T> {
143		self.using_encoded(|mut x| T::decode(&mut x)).ok()
144	}
145}
146
147impl traits::IdentifyAccount for UintAuthorityId {
148	type AccountId = u64;
149
150	fn into_account(self) -> Self::AccountId {
151		self.0
152	}
153}
154
155impl traits::Verify for UintAuthorityId {
156	type Signer = Self;
157
158	fn verify<L: traits::Lazy<[u8]>>(
159		&self,
160		_msg: L,
161		signer: &<Self::Signer as traits::IdentifyAccount>::AccountId,
162	) -> bool {
163		self.0 == *signer
164	}
165}
166
167/// A dummy signature type, to match `UintAuthorityId`.
168#[derive(Eq, PartialEq, Clone, Debug, Hash, Serialize, Deserialize, Encode, Decode, TypeInfo)]
169pub struct TestSignature(pub u64, pub Vec<u8>);
170
171impl traits::Verify for TestSignature {
172	type Signer = UintAuthorityId;
173
174	fn verify<L: traits::Lazy<[u8]>>(&self, mut msg: L, signer: &u64) -> bool {
175		signer == &self.0 && msg.get() == &self.1[..]
176	}
177}
178
179/// Digest item
180pub type DigestItem = generic::DigestItem;
181
182/// Header Digest
183pub type Digest = generic::Digest;
184
185/// Block Header
186pub type Header = generic::Header<u64, BlakeTwo256>;
187
188impl Header {
189	/// A new header with the given number and default hash for all other fields.
190	pub fn new_from_number(number: <Self as traits::Header>::Number) -> Self {
191		Self {
192			number,
193			extrinsics_root: Default::default(),
194			state_root: Default::default(),
195			parent_hash: Default::default(),
196			digest: Default::default(),
197		}
198	}
199}
200
201/// Testing block
202#[derive(PartialEq, Eq, Clone, Serialize, Debug, Encode, Decode, TypeInfo)]
203pub struct Block<Xt> {
204	/// Block header
205	pub header: Header,
206	/// List of extrinsics
207	pub extrinsics: Vec<Xt>,
208}
209
210impl<Xt> traits::HeaderProvider for Block<Xt> {
211	type HeaderT = Header;
212}
213
214impl<
215		Xt: 'static
216			+ Codec
217			+ Sized
218			+ Send
219			+ Sync
220			+ Serialize
221			+ Clone
222			+ Eq
223			+ Debug
224			+ traits::ExtrinsicLike,
225	> traits::Block for Block<Xt>
226{
227	type Extrinsic = Xt;
228	type Header = Header;
229	type Hash = <Header as traits::Header>::Hash;
230
231	fn header(&self) -> &Self::Header {
232		&self.header
233	}
234	fn extrinsics(&self) -> &[Self::Extrinsic] {
235		&self.extrinsics[..]
236	}
237	fn deconstruct(self) -> (Self::Header, Vec<Self::Extrinsic>) {
238		(self.header, self.extrinsics)
239	}
240	fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self {
241		Block { header, extrinsics }
242	}
243	fn encode_from(header: &Self::Header, extrinsics: &[Self::Extrinsic]) -> Vec<u8> {
244		(header, extrinsics).encode()
245	}
246}
247
248impl<'a, Xt> Deserialize<'a> for Block<Xt>
249where
250	Block<Xt>: Decode,
251{
252	fn deserialize<D: Deserializer<'a>>(de: D) -> Result<Self, D::Error> {
253		let r = <Vec<u8>>::deserialize(de)?;
254		Decode::decode(&mut &r[..])
255			.map_err(|e| DeError::custom(format!("Invalid value passed into decode: {}", e)))
256	}
257}
258
259/// Extrinsic type with `u64` accounts and mocked signatures, used in testing.
260pub type TestXt<Call, Extra> = UncheckedExtrinsic<u64, Call, (), Extra>;
261
262/// Wrapper over a `u64` that can be used as a `RuntimeCall`.
263#[derive(PartialEq, Eq, Debug, Clone, Encode, Decode, TypeInfo)]
264pub struct MockCallU64(pub u64);
265
266impl Dispatchable for MockCallU64 {
267	type RuntimeOrigin = u64;
268	type Config = ();
269	type Info = ();
270	type PostInfo = ();
271	fn dispatch(self, _origin: Self::RuntimeOrigin) -> DispatchResultWithInfo<Self::PostInfo> {
272		Ok(())
273	}
274}
275
276impl From<u64> for MockCallU64 {
277	fn from(value: u64) -> Self {
278		Self(value)
279	}
280}