sp_core/
crypto_bytes.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//! Generic byte array which can be specialized with a marker type.
19
20use crate::{
21	crypto::{CryptoType, Derive, FromEntropy, Public, Signature, UncheckedFrom},
22	hash::{H256, H512},
23};
24
25use codec::{Decode, Encode, MaxEncodedLen};
26use core::marker::PhantomData;
27use scale_info::TypeInfo;
28
29use sp_runtime_interface::pass_by::{self, PassBy, PassByInner};
30
31#[cfg(feature = "serde")]
32use crate::crypto::Ss58Codec;
33#[cfg(feature = "serde")]
34use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
35
36#[cfg(all(not(feature = "std"), feature = "serde"))]
37use alloc::{format, string::String};
38
39pub use public_bytes::*;
40pub use signature_bytes::*;
41
42/// Generic byte array holding some crypto-related raw data.
43///
44/// The type is generic over a constant length `N` and a "tag" `T` which
45/// can be used to specialize the byte array without requiring newtypes.
46///
47/// The tag `T` is held in a `PhantomData<fn() ->T>`, a trick allowing
48/// `CryptoBytes` to be `Send` and `Sync` regardless of `T` properties
49/// ([ref](https://doc.rust-lang.org/nomicon/phantom-data.html#table-of-phantomdata-patterns)).
50#[derive(Encode, Decode, MaxEncodedLen)]
51#[repr(transparent)]
52pub struct CryptoBytes<const N: usize, T = ()>(pub [u8; N], PhantomData<fn() -> T>);
53
54impl<const N: usize, T> Copy for CryptoBytes<N, T> {}
55
56impl<const N: usize, T> Clone for CryptoBytes<N, T> {
57	fn clone(&self) -> Self {
58		Self(self.0, PhantomData)
59	}
60}
61
62impl<const N: usize, T> TypeInfo for CryptoBytes<N, T> {
63	type Identity = [u8; N];
64
65	fn type_info() -> scale_info::Type {
66		Self::Identity::type_info()
67	}
68}
69
70impl<const N: usize, T> PartialOrd for CryptoBytes<N, T> {
71	fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
72		self.0.partial_cmp(&other.0)
73	}
74}
75
76impl<const N: usize, T> Ord for CryptoBytes<N, T> {
77	fn cmp(&self, other: &Self) -> core::cmp::Ordering {
78		self.0.cmp(&other.0)
79	}
80}
81
82impl<const N: usize, T> PartialEq for CryptoBytes<N, T> {
83	fn eq(&self, other: &Self) -> bool {
84		self.0.eq(&other.0)
85	}
86}
87
88impl<const N: usize, T> core::hash::Hash for CryptoBytes<N, T> {
89	fn hash<H: scale_info::prelude::hash::Hasher>(&self, state: &mut H) {
90		self.0.hash(state)
91	}
92}
93
94impl<const N: usize, T> Eq for CryptoBytes<N, T> {}
95
96impl<const N: usize, T> Default for CryptoBytes<N, T> {
97	fn default() -> Self {
98		Self([0_u8; N], PhantomData)
99	}
100}
101
102impl<const N: usize, T> PassByInner for CryptoBytes<N, T> {
103	type Inner = [u8; N];
104
105	fn into_inner(self) -> Self::Inner {
106		self.0
107	}
108
109	fn inner(&self) -> &Self::Inner {
110		&self.0
111	}
112
113	fn from_inner(inner: Self::Inner) -> Self {
114		Self(inner, PhantomData)
115	}
116}
117
118impl<const N: usize, T> PassBy for CryptoBytes<N, T> {
119	type PassBy = pass_by::Inner<Self, [u8; N]>;
120}
121
122impl<const N: usize, T> AsRef<[u8]> for CryptoBytes<N, T> {
123	fn as_ref(&self) -> &[u8] {
124		&self.0[..]
125	}
126}
127
128impl<const N: usize, T> AsMut<[u8]> for CryptoBytes<N, T> {
129	fn as_mut(&mut self) -> &mut [u8] {
130		&mut self.0[..]
131	}
132}
133
134impl<const N: usize, T> From<CryptoBytes<N, T>> for [u8; N] {
135	fn from(v: CryptoBytes<N, T>) -> [u8; N] {
136		v.0
137	}
138}
139
140impl<const N: usize, T> AsRef<[u8; N]> for CryptoBytes<N, T> {
141	fn as_ref(&self) -> &[u8; N] {
142		&self.0
143	}
144}
145
146impl<const N: usize, T> AsMut<[u8; N]> for CryptoBytes<N, T> {
147	fn as_mut(&mut self) -> &mut [u8; N] {
148		&mut self.0
149	}
150}
151
152impl<const N: usize, T> From<[u8; N]> for CryptoBytes<N, T> {
153	fn from(value: [u8; N]) -> Self {
154		Self::from_raw(value)
155	}
156}
157
158impl<const N: usize, T> TryFrom<&[u8]> for CryptoBytes<N, T> {
159	type Error = ();
160
161	fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
162		if data.len() != N {
163			return Err(())
164		}
165		let mut r = [0u8; N];
166		r.copy_from_slice(data);
167		Ok(Self::from_raw(r))
168	}
169}
170
171impl<const N: usize, T> UncheckedFrom<[u8; N]> for CryptoBytes<N, T> {
172	fn unchecked_from(data: [u8; N]) -> Self {
173		Self::from_raw(data)
174	}
175}
176
177impl<const N: usize, T> core::ops::Deref for CryptoBytes<N, T> {
178	type Target = [u8];
179
180	fn deref(&self) -> &Self::Target {
181		&self.0
182	}
183}
184
185impl<const N: usize, T> CryptoBytes<N, T> {
186	/// Construct from raw array.
187	pub fn from_raw(inner: [u8; N]) -> Self {
188		Self(inner, PhantomData)
189	}
190
191	/// Construct from raw array.
192	pub fn to_raw(self) -> [u8; N] {
193		self.0
194	}
195
196	/// Return a slice filled with raw data.
197	pub fn as_array_ref(&self) -> &[u8; N] {
198		&self.0
199	}
200}
201
202impl<const N: usize, T> crate::ByteArray for CryptoBytes<N, T> {
203	const LEN: usize = N;
204}
205
206impl<const N: usize, T> FromEntropy for CryptoBytes<N, T> {
207	fn from_entropy(input: &mut impl codec::Input) -> Result<Self, codec::Error> {
208		let mut result = Self::default();
209		input.read(result.as_mut())?;
210		Ok(result)
211	}
212}
213
214impl<T> From<CryptoBytes<32, T>> for H256 {
215	fn from(x: CryptoBytes<32, T>) -> H256 {
216		H256::from(x.0)
217	}
218}
219
220impl<T> From<CryptoBytes<64, T>> for H512 {
221	fn from(x: CryptoBytes<64, T>) -> H512 {
222		H512::from(x.0)
223	}
224}
225
226impl<T> UncheckedFrom<H256> for CryptoBytes<32, T> {
227	fn unchecked_from(x: H256) -> Self {
228		Self::from_h256(x)
229	}
230}
231
232impl<T> CryptoBytes<32, T> {
233	/// A new instance from an H256.
234	pub fn from_h256(x: H256) -> Self {
235		Self::from_raw(x.into())
236	}
237}
238
239impl<T> CryptoBytes<64, T> {
240	/// A new instance from an H512.
241	pub fn from_h512(x: H512) -> Self {
242		Self::from_raw(x.into())
243	}
244}
245
246mod public_bytes {
247	use super::*;
248
249	/// Tag used for generic public key bytes.
250	pub struct PublicTag;
251
252	/// Generic encoded public key.
253	pub type PublicBytes<const N: usize, SubTag> = CryptoBytes<N, (PublicTag, SubTag)>;
254
255	impl<const N: usize, SubTag> Derive for PublicBytes<N, SubTag> where Self: CryptoType {}
256
257	impl<const N: usize, SubTag> Public for PublicBytes<N, SubTag> where Self: CryptoType {}
258
259	impl<const N: usize, SubTag> core::fmt::Debug for PublicBytes<N, SubTag>
260	where
261		Self: CryptoType,
262	{
263		#[cfg(feature = "std")]
264		fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
265			let s = self.to_ss58check();
266			write!(f, "{} ({}...)", crate::hexdisplay::HexDisplay::from(&self.as_ref()), &s[0..8])
267		}
268
269		#[cfg(not(feature = "std"))]
270		fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result {
271			Ok(())
272		}
273	}
274
275	#[cfg(feature = "std")]
276	impl<const N: usize, SubTag> std::fmt::Display for PublicBytes<N, SubTag>
277	where
278		Self: CryptoType,
279	{
280		fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
281			write!(f, "{}", self.to_ss58check())
282		}
283	}
284
285	#[cfg(feature = "std")]
286	impl<const N: usize, SubTag> std::str::FromStr for PublicBytes<N, SubTag>
287	where
288		Self: CryptoType,
289	{
290		type Err = crate::crypto::PublicError;
291
292		fn from_str(s: &str) -> Result<Self, Self::Err> {
293			Self::from_ss58check(s)
294		}
295	}
296
297	#[cfg(feature = "serde")]
298	impl<const N: usize, SubTag> Serialize for PublicBytes<N, SubTag>
299	where
300		Self: CryptoType,
301	{
302		fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
303		where
304			S: Serializer,
305		{
306			serializer.serialize_str(&self.to_ss58check())
307		}
308	}
309
310	#[cfg(feature = "serde")]
311	impl<'de, const N: usize, SubTag> Deserialize<'de> for PublicBytes<N, SubTag>
312	where
313		Self: CryptoType,
314	{
315		fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
316		where
317			D: Deserializer<'de>,
318		{
319			Self::from_ss58check(&String::deserialize(deserializer)?)
320				.map_err(|e| de::Error::custom(format!("{:?}", e)))
321		}
322	}
323}
324
325mod signature_bytes {
326	use super::*;
327
328	/// Tag used for generic signature bytes.
329	pub struct SignatureTag;
330
331	/// Generic encoded signature.
332	pub type SignatureBytes<const N: usize, SubTag> = CryptoBytes<N, (SignatureTag, SubTag)>;
333
334	impl<const N: usize, SubTag> Signature for SignatureBytes<N, SubTag> where Self: CryptoType {}
335
336	#[cfg(feature = "serde")]
337	impl<const N: usize, SubTag> Serialize for SignatureBytes<N, SubTag>
338	where
339		Self: CryptoType,
340	{
341		fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
342		where
343			S: Serializer,
344		{
345			serializer.serialize_str(&array_bytes::bytes2hex("", self))
346		}
347	}
348
349	#[cfg(feature = "serde")]
350	impl<'de, const N: usize, SubTag> Deserialize<'de> for SignatureBytes<N, SubTag>
351	where
352		Self: CryptoType,
353	{
354		fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
355		where
356			D: Deserializer<'de>,
357		{
358			let signature_hex = array_bytes::hex2bytes(&String::deserialize(deserializer)?)
359				.map_err(|e| de::Error::custom(format!("{:?}", e)))?;
360			Self::try_from(signature_hex.as_ref())
361				.map_err(|e| de::Error::custom(format!("{:?}", e)))
362		}
363	}
364
365	impl<const N: usize, SubTag> core::fmt::Debug for SignatureBytes<N, SubTag>
366	where
367		Self: CryptoType,
368	{
369		#[cfg(feature = "std")]
370		fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
371			write!(f, "{}", crate::hexdisplay::HexDisplay::from(&&self.0[..]))
372		}
373
374		#[cfg(not(feature = "std"))]
375		fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result {
376			Ok(())
377		}
378	}
379}