referrerpolicy=no-referrer-when-downgrade

sp_application_crypto/
traits.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
18use codec::Codec;
19use scale_info::TypeInfo;
20
21use alloc::vec::Vec;
22use core::fmt::Debug;
23use sp_core::crypto::{CryptoType, CryptoTypeId, IsWrappedBy, KeyTypeId, Pair, Public};
24
25/// Application-specific cryptographic object.
26///
27/// Combines all the core types and constants that are defined by a particular
28/// cryptographic scheme when it is used in a specific application domain.
29///
30/// Typically, the implementers of this trait are its associated types themselves.
31/// This provides a convenient way to access generic information about the scheme
32/// given any of the associated types.
33pub trait AppCrypto: 'static + Sized + CryptoType {
34	/// Identifier for application-specific key type.
35	const ID: KeyTypeId;
36
37	/// Identifier of the crypto type of this application-specific key type.
38	const CRYPTO_ID: CryptoTypeId;
39
40	/// The corresponding public key type in this application scheme.
41	type Public: AppPublic;
42
43	/// The corresponding signature type in this application scheme.
44	type Signature: AppSignature;
45
46	/// The corresponding key pair type in this application scheme.
47	type Pair: AppPair;
48}
49
50/// Type which implements Hash in std, not when no-std (std variant).
51pub trait MaybeHash: core::hash::Hash {}
52impl<T: core::hash::Hash> MaybeHash for T {}
53
54/// Application-specific key pair.
55pub trait AppPair:
56	AppCrypto + Pair<Public = <Self as AppCrypto>::Public, Signature = <Self as AppCrypto>::Signature>
57{
58	/// The wrapped type which is just a plain instance of `Pair`.
59	type Generic: IsWrappedBy<Self>
60		+ Pair<Public = <<Self as AppCrypto>::Public as AppPublic>::Generic>
61		+ Pair<Signature = <<Self as AppCrypto>::Signature as AppSignature>::Generic>;
62}
63
64/// Application-specific public key.
65pub trait AppPublic: AppCrypto + Public + Debug + MaybeHash + Codec {
66	/// The wrapped type which is just a plain instance of `Public`.
67	type Generic: IsWrappedBy<Self> + Public + Debug + MaybeHash + Codec;
68}
69
70/// Application-specific signature.
71pub trait AppSignature: AppCrypto + Eq + PartialEq + Debug + Clone {
72	/// The wrapped type which is just a plain instance of `Signature`.
73	type Generic: IsWrappedBy<Self> + Eq + PartialEq + Debug;
74}
75
76/// Runtime interface for a public key.
77pub trait RuntimePublic: Sized {
78	/// The signature that will be generated when signing with the corresponding private key.
79	type Signature: Debug + Eq + PartialEq + Clone;
80
81	/// Returns all public keys for the given key type in the keystore.
82	fn all(key_type: KeyTypeId) -> crate::Vec<Self>;
83
84	/// Generate a public/private pair for the given key type with an optional `seed` and
85	/// store it in the keystore.
86	///
87	/// The `seed` needs to be valid utf8.
88	///
89	/// Returns the generated public key.
90	fn generate_pair(key_type: KeyTypeId, seed: Option<Vec<u8>>) -> Self;
91
92	/// Sign the given message with the corresponding private key of this public key.
93	///
94	/// The private key will be requested from the keystore using the given key type.
95	///
96	/// Returns the signature or `None` if the private key could not be found or some other error
97	/// occurred.
98	fn sign<M: AsRef<[u8]>>(&self, key_type: KeyTypeId, msg: &M) -> Option<Self::Signature>;
99
100	/// Verify that the given signature matches the given message using this public key.
101	fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool;
102
103	/// Generate proof of possession of the corresponding public key
104	///
105	/// The private key will be requested from the keystore using the given key type.
106	///
107	/// Returns the proof of possession as a signature or `None` if it failed or is not able to do
108	/// so.
109	fn generate_proof_of_possession(&mut self, key_type: KeyTypeId) -> Option<Self::Signature>;
110
111	/// Verify that the given proof of possession is valid for the corresponding public key.
112	fn verify_proof_of_possession(&self, pop: &Self::Signature) -> bool;
113
114	/// Returns `Self` as raw vec.
115	fn to_raw_vec(&self) -> Vec<u8>;
116}
117
118/// Runtime interface for an application's public key.
119pub trait RuntimeAppPublic: Sized {
120	/// An identifier for this application-specific key type.
121	const ID: KeyTypeId;
122
123	/// The signature that will be generated when signing with the corresponding private key.
124	type Signature: Debug + Eq + PartialEq + Clone + TypeInfo + Codec;
125
126	/// Returns all public keys for this application in the keystore.
127	fn all() -> crate::Vec<Self>;
128
129	/// Generate a public/private pair with an optional `seed` and store it in the keystore.
130	///
131	/// The `seed` needs to be valid utf8.
132	///
133	/// Returns the generated public key.
134	fn generate_pair(seed: Option<Vec<u8>>) -> Self;
135
136	/// Sign the given message with the corresponding private key of this public key.
137	///
138	/// The private key will be requested from the keystore.
139	///
140	/// Returns the signature or `None` if the private key could not be found or some other error
141	/// occurred.
142	fn sign<M: AsRef<[u8]>>(&self, msg: &M) -> Option<Self::Signature>;
143
144	/// Verify that the given signature matches the given message using this public key.
145	fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool;
146
147	/// Generate proof of possession of the corresponding public key
148	///
149	/// The private key will be requested from the keystore using the given key type.
150	///
151	/// Returns the proof of possession as a signature or `None` if it failed or is not able to do
152	/// so.
153	fn generate_proof_of_possession(&mut self) -> Option<Self::Signature>;
154
155	/// Verify that the given proof of possession is valid for the corresponding public key.
156	fn verify_proof_of_possession(&self, pop: &Self::Signature) -> bool;
157
158	/// Returns `Self` as raw vec.
159	fn to_raw_vec(&self) -> Vec<u8>;
160}
161
162impl<T> RuntimeAppPublic for T
163where
164	T: AppPublic + AsRef<<T as AppPublic>::Generic> + AsMut<<T as AppPublic>::Generic>,
165	<T as AppPublic>::Generic: RuntimePublic,
166	<T as AppCrypto>::Signature: TypeInfo
167		+ Codec
168		+ From<<<T as AppPublic>::Generic as RuntimePublic>::Signature>
169		+ AsRef<<<T as AppPublic>::Generic as RuntimePublic>::Signature>,
170{
171	const ID: KeyTypeId = <T as AppCrypto>::ID;
172
173	type Signature = <T as AppCrypto>::Signature;
174
175	fn all() -> crate::Vec<Self> {
176		<<T as AppPublic>::Generic as RuntimePublic>::all(Self::ID)
177			.into_iter()
178			.map(|p| p.into())
179			.collect()
180	}
181
182	fn generate_pair(seed: Option<Vec<u8>>) -> Self {
183		<<T as AppPublic>::Generic as RuntimePublic>::generate_pair(Self::ID, seed).into()
184	}
185
186	fn sign<M: AsRef<[u8]>>(&self, msg: &M) -> Option<Self::Signature> {
187		<<T as AppPublic>::Generic as RuntimePublic>::sign(self.as_ref(), Self::ID, msg)
188			.map(|s| s.into())
189	}
190
191	fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool {
192		<<T as AppPublic>::Generic as RuntimePublic>::verify(self.as_ref(), msg, signature.as_ref())
193	}
194
195	fn generate_proof_of_possession(&mut self) -> Option<Self::Signature> {
196		<<T as AppPublic>::Generic as RuntimePublic>::generate_proof_of_possession(
197			self.as_mut(),
198			Self::ID,
199		)
200		.map(|s| s.into())
201	}
202
203	fn verify_proof_of_possession(&self, pop: &Self::Signature) -> bool {
204		<<T as AppPublic>::Generic as RuntimePublic>::verify_proof_of_possession(
205			self.as_ref(),
206			pop.as_ref(),
207		)
208	}
209
210	fn to_raw_vec(&self) -> Vec<u8> {
211		<<T as AppPublic>::Generic as RuntimePublic>::to_raw_vec(self.as_ref())
212	}
213}
214
215/// Something that is bound to a fixed [`RuntimeAppPublic`].
216pub trait BoundToRuntimeAppPublic {
217	/// The [`RuntimeAppPublic`] this type is bound to.
218	type Public: RuntimeAppPublic;
219}
220
221impl<T: RuntimeAppPublic> BoundToRuntimeAppPublic for T {
222	type Public = Self;
223}