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, OpaqueKeys},
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 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	type ProofOfPossession = TestSignature;
110
111	fn all() -> Vec<Self> {
112		ALL_KEYS.with(|l| l.borrow().clone())
113	}
114
115	fn generate_pair(_: Option<Vec<u8>>) -> Self {
116		use rand::RngCore;
117		UintAuthorityId(rand::thread_rng().next_u64())
118	}
119
120	fn sign<M: AsRef<[u8]>>(&self, msg: &M) -> Option<Self::Signature> {
121		Some(TestSignature(self.0, msg.as_ref().to_vec()))
122	}
123
124	fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool {
125		traits::Verify::verify(signature, msg.as_ref(), &self.0)
126	}
127
128	fn generate_proof_of_possession(&mut self, _owner: &[u8]) -> Option<Self::Signature> {
129		None
130	}
131
132	fn verify_proof_of_possession(&self, _owner: &[u8], _pop: &Self::Signature) -> bool {
133		false
134	}
135
136	fn to_raw_vec(&self) -> Vec<u8> {
137		AsRef::<[u8]>::as_ref(self).to_vec()
138	}
139}
140
141impl OpaqueKeys for UintAuthorityId {
142	type KeyTypeIdProviders = ();
143
144	fn key_ids() -> &'static [KeyTypeId] {
145		&[key_types::DUMMY]
146	}
147
148	fn get_raw(&self, _: KeyTypeId) -> &[u8] {
149		self.as_ref()
150	}
151
152	fn get<T: Decode>(&self, _: KeyTypeId) -> Option<T> {
153		self.using_encoded(|mut x| T::decode(&mut x)).ok()
154	}
155}
156
157impl traits::IdentifyAccount for UintAuthorityId {
158	type AccountId = u64;
159
160	fn into_account(self) -> Self::AccountId {
161		self.0
162	}
163}
164
165impl traits::Verify for UintAuthorityId {
166	type Signer = Self;
167
168	fn verify<L: traits::Lazy<[u8]>>(
169		&self,
170		_msg: L,
171		signer: &<Self::Signer as traits::IdentifyAccount>::AccountId,
172	) -> bool {
173		self.0 == *signer
174	}
175}
176
177/// A dummy signature type, to match `UintAuthorityId`.
178#[derive(
179	Eq,
180	PartialEq,
181	Clone,
182	Debug,
183	Hash,
184	Serialize,
185	Deserialize,
186	Encode,
187	Decode,
188	DecodeWithMemTracking,
189	TypeInfo,
190)]
191pub struct TestSignature(pub u64, pub Vec<u8>);
192
193impl traits::Verify for TestSignature {
194	type Signer = UintAuthorityId;
195
196	fn verify<L: traits::Lazy<[u8]>>(&self, mut msg: L, signer: &u64) -> bool {
197		signer == &self.0 && msg.get() == &self.1[..]
198	}
199}
200
201/// Digest item
202pub type DigestItem = generic::DigestItem;
203
204/// Header Digest
205pub type Digest = generic::Digest;
206
207/// Block Header
208pub type Header = generic::Header<u64, BlakeTwo256>;
209
210impl Header {
211	/// A new header with the given number and default hash for all other fields.
212	pub fn new_from_number(number: <Self as traits::Header>::Number) -> Self {
213		Self {
214			number,
215			extrinsics_root: Default::default(),
216			state_root: Default::default(),
217			parent_hash: Default::default(),
218			digest: Default::default(),
219		}
220	}
221}
222
223/// Testing block
224#[derive(
225	PartialEq, Eq, Clone, Serialize, Debug, Encode, Decode, DecodeWithMemTracking, TypeInfo,
226)]
227pub struct Block<Xt> {
228	/// Block header
229	pub header: Header,
230	/// List of extrinsics
231	pub extrinsics: Vec<Xt>,
232}
233
234impl<Xt> traits::HeaderProvider for Block<Xt> {
235	type HeaderT = Header;
236}
237
238impl<Xt: Into<OpaqueExtrinsic>> From<Block<Xt>> for LazyBlock<Header, Xt> {
239	fn from(block: Block<Xt>) -> Self {
240		LazyBlock::new(block.header, block.extrinsics)
241	}
242}
243
244impl<Xt> EncodeLike<LazyBlock<Header, Xt>> for Block<Xt>
245where
246	Block<Xt>: Encode,
247	LazyBlock<Header, Xt>: Encode,
248{
249}
250
251impl<Xt> EncodeLike<Block<Xt>> for LazyBlock<Header, Xt>
252where
253	Block<Xt>: Encode,
254	LazyBlock<Header, Xt>: Encode,
255{
256}
257
258impl<
259		Xt: 'static
260			+ Codec
261			+ DecodeWithMemTracking
262			+ Sized
263			+ Send
264			+ Sync
265			+ Serialize
266			+ Clone
267			+ Eq
268			+ Debug
269			+ traits::ExtrinsicLike
270			+ Into<OpaqueExtrinsic>
271			+ LazyExtrinsic,
272	> traits::Block for Block<Xt>
273{
274	type Extrinsic = Xt;
275	type Header = Header;
276	type Hash = <Header as traits::Header>::Hash;
277	type LazyBlock = LazyBlock<Header, Xt>;
278
279	fn header(&self) -> &Self::Header {
280		&self.header
281	}
282	fn extrinsics(&self) -> &[Self::Extrinsic] {
283		&self.extrinsics[..]
284	}
285	fn deconstruct(self) -> (Self::Header, Vec<Self::Extrinsic>) {
286		(self.header, self.extrinsics)
287	}
288	fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self {
289		Block { header, extrinsics }
290	}
291}
292
293impl<'a, Xt> Deserialize<'a> for Block<Xt>
294where
295	Block<Xt>: Decode,
296{
297	fn deserialize<D: Deserializer<'a>>(de: D) -> Result<Self, D::Error> {
298		let r = <Vec<u8>>::deserialize(de)?;
299		Decode::decode(&mut &r[..])
300			.map_err(|e| DeError::custom(format!("Invalid value passed into decode: {}", e)))
301	}
302}
303
304/// Extrinsic type with `u64` accounts and mocked signatures, used in testing.
305pub type TestXt<Call, Extra> = UncheckedExtrinsic<u64, Call, (), Extra>;
306
307/// Wrapper over a `u64` that can be used as a `RuntimeCall`.
308#[derive(PartialEq, Eq, Debug, Clone, Encode, Decode, DecodeWithMemTracking, TypeInfo)]
309pub struct MockCallU64(pub u64);
310
311impl Dispatchable for MockCallU64 {
312	type RuntimeOrigin = u64;
313	type Config = ();
314	type Info = ();
315	type PostInfo = ();
316	fn dispatch(self, _origin: Self::RuntimeOrigin) -> DispatchResultWithInfo<Self::PostInfo> {
317		Ok(())
318	}
319}
320
321impl From<u64> for MockCallU64 {
322	fn from(value: u64) -> Self {
323		Self(value)
324	}
325}