tet_application_crypto/
lib.rs

1// This file is part of Tetcore.
2
3// Copyright (C) 2019-2021 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//! Traits and macros for constructing application specific strongly typed crypto wrappers.
19
20#![warn(missing_docs)]
21
22#![cfg_attr(not(feature = "std"), no_std)]
23
24#[doc(hidden)]
25pub use tet_core::{self, crypto::{CryptoType, CryptoTypePublicPair, Public, Derive, IsWrappedBy, Wraps}, RuntimeDebug};
26#[doc(hidden)]
27#[cfg(feature = "full_crypto")]
28pub use tet_core::crypto::{SecretStringError, DeriveJunction, Ss58Codec, Pair};
29pub use tet_core::crypto::{KeyTypeId, CryptoTypeId, key_types};
30
31#[doc(hidden)]
32pub use codec;
33#[doc(hidden)]
34#[cfg(feature = "std")]
35pub use serde;
36#[doc(hidden)]
37pub use tetcore_std::{
38	convert::TryFrom,
39	ops::Deref,
40	vec::Vec,
41};
42
43pub mod ed25519;
44pub mod sr25519;
45pub mod ecdsa;
46mod traits;
47
48pub use traits::*;
49
50/// Declares Public, Pair, Signature types which are functionally equivalent to `$pair`, but are new
51/// Application-specific types whose identifier is `$key_type`.
52///
53/// ```rust
54///# use tet_application_crypto::{app_crypto, wrap, ed25519, KeyTypeId};
55/// // Declare a new set of crypto types using Ed25519 logic that identifies as `KeyTypeId`
56/// // of value `b"fuba"`.
57/// app_crypto!(ed25519, KeyTypeId(*b"_uba"));
58/// ```
59#[cfg(feature = "full_crypto")]
60#[macro_export]
61macro_rules! app_crypto {
62	($module:ident, $key_type:expr) => {
63		$crate::app_crypto_public_full_crypto!($module::Public, $key_type, $module::CRYPTO_ID);
64		$crate::app_crypto_public_common!($module::Public, $module::Signature, $key_type, $module::CRYPTO_ID);
65		$crate::app_crypto_signature_full_crypto!($module::Signature, $key_type, $module::CRYPTO_ID);
66		$crate::app_crypto_signature_common!($module::Signature, $key_type);
67		$crate::app_crypto_pair!($module::Pair, $key_type, $module::CRYPTO_ID);
68	};
69}
70
71/// Declares Public, Pair, Signature types which are functionally equivalent to `$pair`, but are new
72/// Application-specific types whose identifier is `$key_type`.
73///
74/// ```rust
75///# use tet_application_crypto::{app_crypto, wrap, ed25519, KeyTypeId};
76/// // Declare a new set of crypto types using Ed25519 logic that identifies as `KeyTypeId`
77/// // of value `b"fuba"`.
78/// app_crypto!(ed25519, KeyTypeId(*b"_uba"));
79/// ```
80#[cfg(not(feature = "full_crypto"))]
81#[macro_export]
82macro_rules! app_crypto {
83	($module:ident, $key_type:expr) => {
84		$crate::app_crypto_public_not_full_crypto!($module::Public, $key_type, $module::CRYPTO_ID);
85		$crate::app_crypto_public_common!($module::Public, $module::Signature, $key_type, $module::CRYPTO_ID);
86		$crate::app_crypto_signature_not_full_crypto!($module::Signature, $key_type, $module::CRYPTO_ID);
87		$crate::app_crypto_signature_common!($module::Signature, $key_type);
88	};
89}
90
91/// Declares Pair type which is functionally equivalent to `$pair`, but is new
92/// Application-specific type whose identifier is `$key_type`.
93#[macro_export]
94macro_rules! app_crypto_pair {
95	($pair:ty, $key_type:expr, $crypto_type:expr) => {
96		$crate::wrap!{
97			/// A generic `AppPublic` wrapper type over $pair crypto; this has no specific App.
98			#[derive(Clone)]
99			pub struct Pair($pair);
100		}
101
102		impl $crate::CryptoType for Pair {
103			type Pair = Pair;
104		}
105
106		impl $crate::Pair for Pair {
107			type Public = Public;
108			type Seed = <$pair as $crate::Pair>::Seed;
109			type Signature = Signature;
110			type DeriveError = <$pair as $crate::Pair>::DeriveError;
111
112			$crate::app_crypto_pair_functions_if_std!($pair);
113
114			fn derive<
115				Iter: Iterator<Item=$crate::DeriveJunction>
116			>(&self, path: Iter, seed: Option<Self::Seed>) -> Result<(Self, Option<Self::Seed>), Self::DeriveError> {
117				self.0.derive(path, seed).map(|x| (Self(x.0), x.1))
118			}
119			fn from_seed(seed: &Self::Seed) -> Self { Self(<$pair>::from_seed(seed)) }
120			fn from_seed_slice(seed: &[u8]) -> Result<Self, $crate::SecretStringError> {
121				<$pair>::from_seed_slice(seed).map(Self)
122			}
123			fn sign(&self, msg: &[u8]) -> Self::Signature {
124				Signature(self.0.sign(msg))
125			}
126			fn verify<M: AsRef<[u8]>>(
127				sig: &Self::Signature,
128				message: M,
129				pubkey: &Self::Public,
130			) -> bool {
131				<$pair>::verify(&sig.0, message, pubkey.as_ref())
132			}
133			fn verify_weak<P: AsRef<[u8]>, M: AsRef<[u8]>>(
134				sig: &[u8],
135				message: M,
136				pubkey: P,
137			) -> bool {
138				<$pair>::verify_weak(sig, message, pubkey)
139			}
140			fn public(&self) -> Self::Public { Public(self.0.public()) }
141			fn to_raw_vec(&self) -> $crate::Vec<u8> { self.0.to_raw_vec() }
142		}
143
144		impl $crate::AppKey for Pair {
145			type UntypedGeneric = $pair;
146			type Public = Public;
147			type Pair = Pair;
148			type Signature = Signature;
149			const ID: $crate::KeyTypeId = $key_type;
150			const CRYPTO_ID: $crate::CryptoTypeId = $crypto_type;
151		}
152
153		impl $crate::AppPair for Pair {
154			type Generic = $pair;
155		}
156	};
157}
158
159/// Implements functions for the `Pair` trait when `feature = "std"` is enabled.
160#[doc(hidden)]
161#[cfg(feature = "std")]
162#[macro_export]
163macro_rules! app_crypto_pair_functions_if_std {
164	($pair:ty) => {
165		fn generate_with_phrase(password: Option<&str>) -> (Self, String, Self::Seed) {
166			let r = <$pair>::generate_with_phrase(password);
167			(Self(r.0), r.1, r.2)
168		}
169
170		fn from_phrase(phrase: &str, password: Option<&str>)
171			-> Result<(Self, Self::Seed), $crate::SecretStringError>
172		{
173			<$pair>::from_phrase(phrase, password).map(|r| (Self(r.0), r.1))
174		}
175	}
176}
177
178#[doc(hidden)]
179#[cfg(not(feature = "std"))]
180#[macro_export]
181macro_rules! app_crypto_pair_functions_if_std {
182	($pair:ty) => {}
183}
184
185
186/// Declares Public type which is functionally equivalent to `$public`, but is new
187/// Application-specific type whose identifier is `$key_type`.
188/// can only be used together with `full_crypto` feature
189/// For full functionality, app_crypto_public_common! must be called too.
190#[doc(hidden)]
191#[macro_export]
192macro_rules! app_crypto_public_full_crypto {
193	($public:ty, $key_type:expr, $crypto_type:expr) => {
194		$crate::wrap!{
195			/// A generic `AppPublic` wrapper type over $public crypto; this has no specific App.
196			#[derive(
197				Clone, Default, Eq, PartialEq, Ord, PartialOrd,
198				$crate::codec::Encode,
199				$crate::codec::Decode,
200				$crate::RuntimeDebug,
201			)]
202			#[derive(Hash)]
203			pub struct Public($public);
204		}
205
206		impl $crate::CryptoType for Public {
207			type Pair = Pair;
208		}
209
210		impl $crate::AppKey for Public {
211			type UntypedGeneric = $public;
212			type Public = Public;
213			type Pair = Pair;
214			type Signature = Signature;
215			const ID: $crate::KeyTypeId = $key_type;
216			const CRYPTO_ID: $crate::CryptoTypeId = $crypto_type;
217		}
218	}
219}
220
221/// Declares Public type which is functionally equivalent to `$public`, but is new
222/// Application-specific type whose identifier is `$key_type`.
223/// can only be used without `full_crypto` feature
224/// For full functionality, app_crypto_public_common! must be called too.
225#[doc(hidden)]
226#[macro_export]
227macro_rules! app_crypto_public_not_full_crypto {
228	($public:ty, $key_type:expr, $crypto_type:expr) => {
229		$crate::wrap!{
230			/// A generic `AppPublic` wrapper type over $public crypto; this has no specific App.
231			#[derive(
232				Clone, Default, Eq, PartialEq, Ord, PartialOrd,
233				$crate::codec::Encode,
234				$crate::codec::Decode,
235				$crate::RuntimeDebug,
236			)]
237			pub struct Public($public);
238		}
239
240		impl $crate::CryptoType for Public {}
241
242		impl $crate::AppKey for Public {
243			type UntypedGeneric = $public;
244			type Public = Public;
245			type Signature = Signature;
246			const ID: $crate::KeyTypeId = $key_type;
247			const CRYPTO_ID: $crate::CryptoTypeId = $crypto_type;
248		}
249	}
250}
251
252/// Declares Public type which is functionally equivalent to `$public`, but is new
253/// Application-specific type whose identifier is `$key_type`.
254/// For full functionality, app_crypto_public_(not)_full_crypto! must be called too.
255#[doc(hidden)]
256#[macro_export]
257macro_rules! app_crypto_public_common {
258	($public:ty, $sig:ty, $key_type:expr, $crypto_type:expr) => {
259		$crate::app_crypto_public_common_if_std!();
260
261		impl AsRef<[u8]> for Public {
262			fn as_ref(&self) -> &[u8] { self.0.as_ref() }
263		}
264
265		impl AsMut<[u8]> for Public {
266			fn as_mut(&mut self) -> &mut [u8] { self.0.as_mut() }
267		}
268
269		impl $crate::Public for Public {
270			fn from_slice(x: &[u8]) -> Self { Self(<$public>::from_slice(x)) }
271
272			fn to_public_crypto_pair(&self) -> $crate::CryptoTypePublicPair {
273				$crate::CryptoTypePublicPair($crypto_type, self.to_raw_vec())
274			}
275		}
276
277		impl $crate::AppPublic for Public {
278			type Generic = $public;
279		}
280
281		impl $crate::RuntimeAppPublic for Public where $public: $crate::RuntimePublic<Signature=$sig> {
282			const ID: $crate::KeyTypeId = $key_type;
283			const CRYPTO_ID: $crate::CryptoTypeId = $crypto_type;
284
285			type Signature = Signature;
286
287			fn all() -> $crate::Vec<Self> {
288				<$public as $crate::RuntimePublic>::all($key_type).into_iter().map(Self).collect()
289			}
290
291			fn generate_pair(seed: Option<$crate::Vec<u8>>) -> Self {
292				Self(<$public as $crate::RuntimePublic>::generate_pair($key_type, seed))
293			}
294
295			fn sign<M: AsRef<[u8]>>(&self, msg: &M) -> Option<Self::Signature> {
296				<$public as $crate::RuntimePublic>::sign(
297					self.as_ref(),
298					$key_type,
299					msg,
300				).map(Signature)
301			}
302
303			fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool {
304				<$public as $crate::RuntimePublic>::verify(self.as_ref(), msg, &signature.as_ref())
305			}
306
307			fn to_raw_vec(&self) -> $crate::Vec<u8> {
308				<$public as $crate::RuntimePublic>::to_raw_vec(&self.0)
309			}
310		}
311
312		impl From<Public> for $crate::CryptoTypePublicPair {
313			fn from(key: Public) -> Self {
314				(&key).into()
315			}
316		}
317
318		impl From<&Public> for $crate::CryptoTypePublicPair {
319			fn from(key: &Public) -> Self {
320				$crate::CryptoTypePublicPair(
321					$crypto_type,
322					$crate::Public::to_raw_vec(key),
323				)
324			}
325		}
326
327		impl<'a> $crate::TryFrom<&'a [u8]> for Public {
328			type Error = ();
329
330			fn try_from(data: &'a [u8]) -> Result<Self, Self::Error> {
331				<$public>::try_from(data).map(Into::into)
332			}
333		}
334	}
335}
336
337/// Implements traits for the public key type if `feature = "std"` is enabled.
338#[cfg(feature = "std")]
339#[doc(hidden)]
340#[macro_export]
341macro_rules! app_crypto_public_common_if_std {
342	() => {
343		impl $crate::Derive for Public {
344			fn derive<Iter: Iterator<Item=$crate::DeriveJunction>>(&self,
345				path: Iter
346			) -> Option<Self> {
347				self.0.derive(path).map(Self)
348			}
349		}
350
351		impl std::fmt::Display for Public {
352			fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
353				use $crate::Ss58Codec;
354				write!(f, "{}", self.0.to_ss58check())
355			}
356		}
357
358		impl $crate::serde::Serialize for Public {
359			fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where
360				S: $crate::serde::Serializer
361			{
362				use $crate::Ss58Codec;
363				serializer.serialize_str(&self.to_ss58check())
364			}
365		}
366
367		impl<'de> $crate::serde::Deserialize<'de> for Public {
368			fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error> where
369				D: $crate::serde::Deserializer<'de>
370			{
371				use $crate::Ss58Codec;
372				Public::from_ss58check(&String::deserialize(deserializer)?)
373					.map_err(|e| $crate::serde::de::Error::custom(format!("{:?}", e)))
374			}
375		}
376	}
377}
378
379#[cfg(not(feature = "std"))]
380#[doc(hidden)]
381#[macro_export]
382macro_rules! app_crypto_public_common_if_std {
383	() => {
384		impl $crate::Derive for Public {}
385	}
386}
387
388
389/// Declares Signature type which is functionally equivalent to `$sig`, but is new
390/// Application-specific type whose identifier is `$key_type`.
391/// can only be used together with `full_crypto` feature
392/// For full functionality, app_crypto_public_common! must be called too.
393#[doc(hidden)]
394#[macro_export]
395macro_rules! app_crypto_signature_full_crypto {
396	($sig:ty, $key_type:expr, $crypto_type:expr) => {
397		$crate::wrap! {
398			/// A generic `AppPublic` wrapper type over $public crypto; this has no specific App.
399			#[derive(Clone, Default, Eq, PartialEq,
400				$crate::codec::Encode,
401				$crate::codec::Decode,
402				$crate::RuntimeDebug,
403			)]
404			#[derive(Hash)]
405			pub struct Signature($sig);
406		}
407
408		impl $crate::CryptoType for Signature {
409			type Pair = Pair;
410		}
411
412		impl $crate::AppKey for Signature {
413			type UntypedGeneric = $sig;
414			type Public = Public;
415			type Pair = Pair;
416			type Signature = Signature;
417			const ID: $crate::KeyTypeId = $key_type;
418			const CRYPTO_ID: $crate::CryptoTypeId = $crypto_type;
419		}
420	}
421}
422
423/// Declares Signature type which is functionally equivalent to `$sig`, but is new
424/// Application-specific type whose identifier is `$key_type`.
425/// can only be used without `full_crypto` feature
426/// For full functionality, app_crypto_public_common! must be called too.
427#[doc(hidden)]
428#[macro_export]
429macro_rules! app_crypto_signature_not_full_crypto {
430	($sig:ty, $key_type:expr, $crypto_type:expr) => {
431		$crate::wrap! {
432			/// A generic `AppPublic` wrapper type over $public crypto; this has no specific App.
433			#[derive(Clone, Default, Eq, PartialEq,
434				$crate::codec::Encode,
435				$crate::codec::Decode,
436				$crate::RuntimeDebug,
437			)]
438			pub struct Signature($sig);
439		}
440
441		impl $crate::CryptoType for Signature {}
442
443		impl $crate::AppKey for Signature {
444			type UntypedGeneric = $sig;
445			type Public = Public;
446			type Signature = Signature;
447			const ID: $crate::KeyTypeId = $key_type;
448			const CRYPTO_ID: $crate::CryptoTypeId = $crypto_type;
449		}
450	}
451}
452
453/// Declares Signature type which is functionally equivalent to `$sig`, but is new
454/// Application-specific type whose identifier is `$key_type`.
455/// For full functionality, app_crypto_public_(not)_full_crypto! must be called too.
456#[doc(hidden)]
457#[macro_export]
458macro_rules! app_crypto_signature_common {
459	($sig:ty, $key_type:expr) => {
460		impl $crate::Deref for Signature {
461			type Target = [u8];
462
463			fn deref(&self) -> &Self::Target { self.0.as_ref() }
464		}
465
466		impl AsRef<[u8]> for Signature {
467			fn as_ref(&self) -> &[u8] { self.0.as_ref() }
468		}
469
470		impl $crate::AppSignature for Signature {
471			type Generic = $sig;
472		}
473
474		impl $crate::TryFrom<$crate::Vec<u8>> for Signature {
475			type Error = ();
476
477			fn try_from(data: $crate::Vec<u8>) -> Result<Self, Self::Error> {
478				Ok(<$sig>::try_from(data.as_slice())?.into())
479			}
480		}
481	}
482}
483
484/// Implement bidirectional `From` and on-way `AsRef`/`AsMut` for two types, `$inner` and `$outer`.
485///
486/// ```rust
487/// tet_application_crypto::wrap! {
488///     pub struct Wrapper(u32);
489/// }
490/// ```
491#[macro_export]
492macro_rules! wrap {
493	($( #[ $attr:meta ] )* struct $outer:ident($inner:ty);) => {
494		$( #[ $attr ] )*
495		struct $outer( $inner );
496		$crate::wrap!($inner, $outer);
497	};
498	($( #[ $attr:meta ] )* pub struct $outer:ident($inner:ty);) => {
499		$( #[ $attr ] )*
500		pub struct $outer( $inner );
501		$crate::wrap!($inner, $outer);
502	};
503	($inner:ty, $outer:ty) => {
504		impl $crate::Wraps for $outer {
505			type Inner = $inner;
506		}
507		impl From<$inner> for $outer {
508			fn from(inner: $inner) -> Self {
509				Self(inner)
510			}
511		}
512		impl From<$outer> for $inner {
513			fn from(outer: $outer) -> Self {
514				outer.0
515			}
516		}
517		impl AsRef<$inner> for $outer {
518			fn as_ref(&self) -> &$inner {
519				&self.0
520			}
521		}
522		impl AsMut<$inner> for $outer {
523			fn as_mut(&mut self) -> &mut $inner {
524				&mut self.0
525			}
526		}
527	}
528}
529
530/// Generate the given code if the pair type is available.
531///
532/// The pair type is available when `feature = "std"` || `feature = "full_crypto"`.
533///
534/// # Example
535///
536/// ```
537/// tet_application_crypto::with_pair! {
538///     pub type Pair = ();
539/// }
540/// ```
541#[macro_export]
542#[cfg(any(feature = "std", feature = "full_crypto"))]
543macro_rules! with_pair {
544	( $( $def:tt )* ) => {
545		$( $def )*
546	}
547}
548
549
550#[doc(hidden)]
551#[macro_export]
552#[cfg(all(not(feature = "std"), not(feature = "full_crypto")))]
553macro_rules! with_pair {
554	( $( $def:tt )* ) => {}
555}