Skip to main content

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, DecodeWithMemTracking, Encode, EncodeLike, MaxEncodedLen},
22	generic::{self, LazyBlock, UncheckedExtrinsic},
23	scale_info::TypeInfo,
24	traits::{self, BlakeTwo256, Dispatchable, LazyExtrinsic, Lookup, OpaqueKeys, StaticLookup},
25	DispatchResultWithInfo, KeyTypeId, OpaqueExtrinsic,
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	DecodeWithMemTracking,
46	Debug,
47	Hash,
48	Serialize,
49	Deserialize,
50	PartialOrd,
51	Ord,
52	MaxEncodedLen,
53	TypeInfo,
54)]
55pub struct UintAuthorityId(pub u64);
56
57impl core::fmt::Display for UintAuthorityId {
58	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
59		core::fmt::Display::fmt(&self.0, f)
60	}
61}
62
63impl From<u64> for UintAuthorityId {
64	fn from(id: u64) -> Self {
65		UintAuthorityId(id)
66	}
67}
68
69impl From<UintAuthorityId> for u64 {
70	fn from(id: UintAuthorityId) -> u64 {
71		id.0
72	}
73}
74
75impl UintAuthorityId {
76	/// Convert this authority ID into a public key.
77	pub fn to_public_key<T: ByteArray>(&self) -> T {
78		let mut bytes = [0u8; 32];
79		bytes[0..8].copy_from_slice(&self.0.to_le_bytes());
80		T::from_slice(&bytes).unwrap()
81	}
82
83	/// Set the list of keys returned by the runtime call for all keys of that type.
84	pub fn set_all_keys<T: Into<UintAuthorityId>>(keys: impl IntoIterator<Item = T>) {
85		ALL_KEYS.with(|l| *l.borrow_mut() = keys.into_iter().map(Into::into).collect())
86	}
87}
88
89impl CryptoType for UintAuthorityId {
90	type Pair = Dummy;
91}
92
93impl AsRef<[u8]> for UintAuthorityId {
94	fn as_ref(&self) -> &[u8] {
95		// Unsafe, i know, but it's test code and it's just there because it's really convenient to
96		// keep `UintAuthorityId` as a u64 under the hood.
97		unsafe {
98			std::slice::from_raw_parts(
99				&self.0 as *const u64 as *const _,
100				std::mem::size_of::<u64>(),
101			)
102		}
103	}
104}
105
106thread_local! {
107	/// A list of all UintAuthorityId keys returned to the runtime.
108	static ALL_KEYS: RefCell<Vec<UintAuthorityId>> = RefCell::new(vec![]);
109}
110
111impl sp_application_crypto::RuntimeAppPublic for UintAuthorityId {
112	const ID: KeyTypeId = key_types::DUMMY;
113
114	type Signature = TestSignature;
115	type ProofOfPossession = TestSignature;
116
117	fn all() -> Vec<Self> {
118		ALL_KEYS.with(|l| l.borrow().clone())
119	}
120
121	fn generate_pair(_: Option<Vec<u8>>) -> Self {
122		use rand::RngCore;
123		UintAuthorityId(rand::thread_rng().next_u64())
124	}
125
126	fn sign<M: AsRef<[u8]>>(&self, msg: &M) -> Option<Self::Signature> {
127		Some(TestSignature(self.0, msg.as_ref().to_vec()))
128	}
129
130	fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool {
131		traits::Verify::verify(signature, msg.as_ref(), &self.0)
132	}
133
134	fn generate_proof_of_possession(&mut self, owner: &[u8]) -> Option<Self::Signature> {
135		Some(TestSignature(self.0, owner.to_vec()))
136	}
137
138	fn verify_proof_of_possession(&self, owner: &[u8], pop: &Self::Signature) -> bool {
139		traits::Verify::verify(pop, owner, &self.0)
140	}
141
142	fn to_raw_vec(&self) -> Vec<u8> {
143		AsRef::<[u8]>::as_ref(self).to_vec()
144	}
145}
146
147impl OpaqueKeys for UintAuthorityId {
148	type KeyTypeIdProviders = ();
149
150	fn key_ids() -> &'static [KeyTypeId] {
151		&[key_types::DUMMY]
152	}
153
154	fn get_raw(&self, _: KeyTypeId) -> &[u8] {
155		self.as_ref()
156	}
157
158	fn get<T: Decode>(&self, _: KeyTypeId) -> Option<T> {
159		self.using_encoded(|mut x| T::decode(&mut x)).ok()
160	}
161
162	fn ownership_proof_is_valid(&self, _: &[u8], _: &[u8]) -> bool {
163		true
164	}
165}
166
167impl traits::IdentifyAccount for UintAuthorityId {
168	type AccountId = u64;
169
170	fn into_account(self) -> Self::AccountId {
171		self.0
172	}
173}
174
175impl StaticLookup for UintAuthorityId {
176	type Source = Self;
177	type Target = u64;
178
179	fn lookup(s: Self::Source) -> Result<Self::Target, traits::LookupError> {
180		Ok(s.0)
181	}
182
183	fn unlookup(t: Self::Target) -> Self::Source {
184		Self(t)
185	}
186}
187
188impl Lookup for UintAuthorityId {
189	type Source = Self;
190	type Target = u64;
191
192	fn lookup(&self, s: Self::Source) -> Result<Self::Target, traits::LookupError> {
193		Ok(s.0)
194	}
195}
196
197impl traits::Verify for UintAuthorityId {
198	type Signer = Self;
199
200	fn verify<L: traits::Lazy<[u8]>>(
201		&self,
202		_msg: L,
203		signer: &<Self::Signer as traits::IdentifyAccount>::AccountId,
204	) -> bool {
205		self.0 == *signer
206	}
207}
208
209/// A dummy signature type, to match `UintAuthorityId`.
210#[derive(
211	Eq,
212	PartialEq,
213	Clone,
214	Debug,
215	Hash,
216	Serialize,
217	Deserialize,
218	Encode,
219	Decode,
220	DecodeWithMemTracking,
221	TypeInfo,
222)]
223pub struct TestSignature(pub u64, pub Vec<u8>);
224
225impl traits::Verify for TestSignature {
226	type Signer = UintAuthorityId;
227
228	fn verify<L: traits::Lazy<[u8]>>(&self, mut msg: L, signer: &u64) -> bool {
229		signer == &self.0 && msg.get() == &self.1[..]
230	}
231}
232
233/// Digest item
234pub type DigestItem = generic::DigestItem;
235
236/// Header Digest
237pub type Digest = generic::Digest;
238
239/// Block Header
240pub type Header = generic::Header<u64, BlakeTwo256>;
241
242impl Header {
243	/// A new header with the given number and default hash for all other fields.
244	pub fn new_from_number(number: <Self as traits::Header>::Number) -> Self {
245		Self {
246			number,
247			extrinsics_root: Default::default(),
248			state_root: Default::default(),
249			parent_hash: Default::default(),
250			digest: Default::default(),
251		}
252	}
253}
254
255/// Testing block
256#[derive(
257	PartialEq, Eq, Clone, Serialize, Debug, Encode, Decode, DecodeWithMemTracking, TypeInfo,
258)]
259pub struct Block<Xt> {
260	/// Block header
261	pub header: Header,
262	/// List of extrinsics
263	pub extrinsics: Vec<Xt>,
264}
265
266impl<Xt> traits::HeaderProvider for Block<Xt> {
267	type HeaderT = Header;
268}
269
270impl<Xt: Into<OpaqueExtrinsic>> From<Block<Xt>> for LazyBlock<Header, Xt> {
271	fn from(block: Block<Xt>) -> Self {
272		LazyBlock::new(block.header, block.extrinsics)
273	}
274}
275
276impl<Xt> EncodeLike<LazyBlock<Header, Xt>> for Block<Xt>
277where
278	Block<Xt>: Encode,
279	LazyBlock<Header, Xt>: Encode,
280{
281}
282
283impl<Xt> EncodeLike<Block<Xt>> for LazyBlock<Header, Xt>
284where
285	Block<Xt>: Encode,
286	LazyBlock<Header, Xt>: Encode,
287{
288}
289
290impl<
291		Xt: 'static
292			+ Codec
293			+ DecodeWithMemTracking
294			+ Sized
295			+ Send
296			+ Sync
297			+ Serialize
298			+ Clone
299			+ Eq
300			+ Debug
301			+ traits::ExtrinsicLike
302			+ Into<OpaqueExtrinsic>
303			+ LazyExtrinsic,
304	> traits::Block for Block<Xt>
305{
306	type Extrinsic = Xt;
307	type Header = Header;
308	type Hash = <Header as traits::Header>::Hash;
309	type LazyBlock = LazyBlock<Header, Xt>;
310
311	fn header(&self) -> &Self::Header {
312		&self.header
313	}
314	fn extrinsics(&self) -> &[Self::Extrinsic] {
315		&self.extrinsics[..]
316	}
317	fn deconstruct(self) -> (Self::Header, Vec<Self::Extrinsic>) {
318		(self.header, self.extrinsics)
319	}
320	fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self {
321		Block { header, extrinsics }
322	}
323}
324
325impl<'a, Xt> Deserialize<'a> for Block<Xt>
326where
327	Block<Xt>: Decode,
328{
329	fn deserialize<D: Deserializer<'a>>(de: D) -> Result<Self, D::Error> {
330		let r = <Vec<u8>>::deserialize(de)?;
331		Decode::decode(&mut &r[..])
332			.map_err(|e| DeError::custom(format!("Invalid value passed into decode: {}", e)))
333	}
334}
335
336/// Extrinsic type with `u64` accounts and mocked signatures, used in testing.
337pub type TestXt<Call, Extra> = UncheckedExtrinsic<u64, Call, (), Extra>;
338
339/// Wrapper over a `u64` that can be used as a `RuntimeCall`.
340#[derive(PartialEq, Eq, Debug, Clone, Encode, Decode, DecodeWithMemTracking, TypeInfo)]
341pub struct MockCallU64(pub u64);
342
343impl Dispatchable for MockCallU64 {
344	type RuntimeOrigin = u64;
345	type Config = ();
346	type Info = ();
347	type PostInfo = ();
348	fn dispatch(self, _origin: Self::RuntimeOrigin) -> DispatchResultWithInfo<Self::PostInfo> {
349		Ok(())
350	}
351}
352
353impl From<u64> for MockCallU64 {
354	fn from(value: u64) -> Self {
355		Self(value)
356	}
357}