referrerpolicy=no-referrer-when-downgrade

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