pezsp_application_crypto/
traits.rs

1// This file is part of Bizinikiwi.
2
3// Copyright (C) Parity Technologies (UK) Ltd. and Dijital Kurdistan Tech Institute
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 pezsp_core::crypto::{
24	CryptoType, CryptoTypeId, IsWrappedBy, KeyTypeId, Pair, Public, Signature,
25};
26
27/// Application-specific cryptographic object.
28///
29/// Combines all the core types and constants that are defined by a particular
30/// cryptographic scheme when it is used in a specific application domain.
31///
32/// Typically, the implementers of this trait are its associated types themselves.
33/// This provides a convenient way to access generic information about the scheme
34/// given any of the associated types.
35pub trait AppCrypto: 'static + Sized + CryptoType {
36	/// Identifier for application-specific key type.
37	const ID: KeyTypeId;
38
39	/// Identifier of the crypto type of this application-specific key type.
40	const CRYPTO_ID: CryptoTypeId;
41
42	/// The corresponding public key type in this application scheme.
43	type Public: AppPublic;
44
45	/// The corresponding signature type in this application scheme.
46	type Signature: AppSignature;
47
48	/// The corresponding proof of possession type in this application scheme.
49	type ProofOfPossession: AppSignature;
50
51	/// The corresponding key pair type in this application scheme.
52	type Pair: AppPair;
53}
54
55/// Type which implements Hash in std, not when no-std (std variant).
56pub trait MaybeHash: core::hash::Hash {}
57impl<T: core::hash::Hash> MaybeHash for T {}
58
59/// Application-specific key pair.
60pub trait AppPair:
61	AppCrypto + Pair<Public = <Self as AppCrypto>::Public, Signature = <Self as AppCrypto>::Signature>
62{
63	/// The wrapped type which is just a plain instance of `Pair`.
64	type Generic: IsWrappedBy<Self>
65		+ Pair<Public = <<Self as AppCrypto>::Public as AppPublic>::Generic>
66		+ Pair<Signature = <<Self as AppCrypto>::Signature as AppSignature>::Generic>;
67}
68
69/// Application-specific public key.
70pub trait AppPublic: AppCrypto + Public + Debug + MaybeHash + Codec {
71	/// The wrapped type which is just a plain instance of `Public`.
72	type Generic: IsWrappedBy<Self> + Public + Debug + MaybeHash + Codec;
73}
74
75/// Application-specific signature and Proof Of Possession
76pub trait AppSignature: AppCrypto + Signature + Eq + PartialEq + Debug + Clone {
77	/// The wrapped type which is just a plain instance of `Signature`.
78	type Generic: IsWrappedBy<Self> + Signature + Eq + PartialEq + Debug;
79}
80
81/// Runtime interface for a public key.
82pub trait RuntimePublic: Sized {
83	/// The signature that will be generated when signing with the corresponding private key.
84	type Signature: Debug + Eq + PartialEq + Clone;
85
86	/// The Proof Of Possession the corresponding private key.
87	type ProofOfPossession: Debug + Eq + PartialEq + Clone;
88
89	/// Returns all public keys for the given key type in the keystore.
90	fn all(key_type: KeyTypeId) -> crate::Vec<Self>;
91
92	/// Generate a public/private pair for the given key type with an optional `seed` and
93	/// store it in the keystore.
94	///
95	/// The `seed` needs to be valid utf8.
96	///
97	/// Returns the generated public key.
98	fn generate_pair(key_type: KeyTypeId, seed: Option<Vec<u8>>) -> Self;
99
100	/// Sign the given message with the corresponding private key of this public key.
101	///
102	/// The private key will be requested from the keystore using the given key type.
103	///
104	/// Returns the signature or `None` if the private key could not be found or some other error
105	/// occurred.
106	fn sign<M: AsRef<[u8]>>(&self, key_type: KeyTypeId, msg: &M) -> Option<Self::Signature>;
107
108	/// Verify that the given signature matches the given message using this public key.
109	fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool;
110
111	/// Generates the necessary proof(s) usually as a signature or list of signatures, for the
112	/// corresponding public key to be accepted as legitimate by the network.
113	///
114	/// This includes attestation of the owner of the public key in the form of signing the owner's
115	/// identity. It might also includes other signatures such as signature obtained by signing
116	/// the corresponding public in different context than normal signatures in case of BLS
117	/// key pair.
118	///
119	/// The `owner` is an arbitrary byte array representing the identity of the owner of
120	/// the key which has been signed by the private key in process of generating the proof.
121	///
122	/// The private key will be requested from the keystore using the given key type.
123	///
124	/// Returns the proof of possession or `None` if it failed or is not able to do
125	/// so.
126	fn generate_proof_of_possession(
127		&mut self,
128		key_type: KeyTypeId,
129		owner: &[u8],
130	) -> Option<Self::ProofOfPossession>;
131
132	/// Verifies that the given proof is valid for the corresponding public key.
133	/// The proof is usually a signature or list of signatures, for the corresponding
134	/// public key to be accepted by the network. It include attestation of the owner of
135	/// the public key in the form signing the owner's identity but might also includes
136	/// other signatures.
137	///
138	/// The `owner` is an arbitrary byte array representing the identity of the owner of
139	/// the key which has been signed by the private key in process of generating the proof.
140	///
141	/// Returns `true` if the proof is deemed correct by the cryto type.
142	fn verify_proof_of_possession(&self, owner: &[u8], pop: &Self::ProofOfPossession) -> bool;
143
144	/// Returns `Self` as raw vec.
145	fn to_raw_vec(&self) -> Vec<u8>;
146}
147
148/// Runtime interface for an application's public key.
149pub trait RuntimeAppPublic: Sized {
150	/// An identifier for this application-specific key type.
151	const ID: KeyTypeId;
152
153	/// The signature that will be generated when signing with the corresponding private key.
154	type Signature: Debug + Eq + PartialEq + Clone + TypeInfo + Codec;
155
156	/// The Proof Of Possession the corresponding private key.
157	type ProofOfPossession: Debug + Eq + PartialEq + TypeInfo + Clone;
158
159	/// Returns all public keys for this application in the keystore.
160	fn all() -> crate::Vec<Self>;
161
162	/// Generate a public/private pair with an optional `seed` and store it in the keystore.
163	///
164	/// The `seed` needs to be valid utf8.
165	///
166	/// Returns the generated public key.
167	fn generate_pair(seed: Option<Vec<u8>>) -> Self;
168
169	/// Sign the given message with the corresponding private key of this public key.
170	///
171	/// The private key will be requested from the keystore.
172	///
173	/// Returns the signature or `None` if the private key could not be found or some other error
174	/// occurred.
175	fn sign<M: AsRef<[u8]>>(&self, msg: &M) -> Option<Self::Signature>;
176
177	/// Verify that the given signature matches the given message using this public key.
178	fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool;
179
180	/// Generate proof of legitimacy for the corresponding public key
181	///
182	/// Returns the proof of possession, usually a signature or a list of signature,  or `None` if
183	/// it failed or is not able to do so.
184	fn generate_proof_of_possession(&mut self, owner: &[u8]) -> Option<Self::ProofOfPossession>;
185
186	/// Verify that the given proof of possession is valid for the corresponding public key.
187	fn verify_proof_of_possession(&self, owner: &[u8], pop: &Self::ProofOfPossession) -> bool;
188
189	/// Returns `Self` as raw vec.
190	fn to_raw_vec(&self) -> Vec<u8>;
191}
192
193impl<T> RuntimeAppPublic for T
194where
195	T: AppPublic + AsRef<<T as AppPublic>::Generic> + AsMut<<T as AppPublic>::Generic>,
196	<T as AppPublic>::Generic: RuntimePublic,
197	<T as AppCrypto>::Signature: TypeInfo
198		+ Codec
199		+ From<<<T as AppPublic>::Generic as RuntimePublic>::Signature>
200		+ AsRef<<<T as AppPublic>::Generic as RuntimePublic>::Signature>,
201	<T as AppCrypto>::ProofOfPossession: TypeInfo
202		+ Codec
203		+ From<<<T as AppPublic>::Generic as RuntimePublic>::ProofOfPossession>
204		+ AsRef<<<T as AppPublic>::Generic as RuntimePublic>::ProofOfPossession>,
205{
206	const ID: KeyTypeId = <T as AppCrypto>::ID;
207
208	type Signature = <T as AppCrypto>::Signature;
209	type ProofOfPossession = <T as AppCrypto>::ProofOfPossession;
210
211	fn all() -> crate::Vec<Self> {
212		<<T as AppPublic>::Generic as RuntimePublic>::all(Self::ID)
213			.into_iter()
214			.map(|p| p.into())
215			.collect()
216	}
217
218	fn generate_pair(seed: Option<Vec<u8>>) -> Self {
219		<<T as AppPublic>::Generic as RuntimePublic>::generate_pair(Self::ID, seed).into()
220	}
221
222	fn sign<M: AsRef<[u8]>>(&self, msg: &M) -> Option<Self::Signature> {
223		<<T as AppPublic>::Generic as RuntimePublic>::sign(self.as_ref(), Self::ID, msg)
224			.map(|s| s.into())
225	}
226
227	fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool {
228		<<T as AppPublic>::Generic as RuntimePublic>::verify(self.as_ref(), msg, signature.as_ref())
229	}
230
231	fn generate_proof_of_possession(&mut self, owner: &[u8]) -> Option<Self::ProofOfPossession> {
232		<<T as AppPublic>::Generic as RuntimePublic>::generate_proof_of_possession(
233			self.as_mut(),
234			Self::ID,
235			owner,
236		)
237		.map(|s| s.into())
238	}
239
240	fn verify_proof_of_possession(&self, owner: &[u8], pop: &Self::ProofOfPossession) -> bool {
241		<<T as AppPublic>::Generic as RuntimePublic>::verify_proof_of_possession(
242			self.as_ref(),
243			owner,
244			pop.as_ref(),
245		)
246	}
247
248	fn to_raw_vec(&self) -> Vec<u8> {
249		<<T as AppPublic>::Generic as RuntimePublic>::to_raw_vec(self.as_ref())
250	}
251}
252
253/// Something that is bound to a fixed [`RuntimeAppPublic`].
254pub trait BoundToRuntimeAppPublic {
255	/// The [`RuntimeAppPublic`] this type is bound to.
256	type Public: RuntimeAppPublic;
257}
258
259impl<T: RuntimeAppPublic> BoundToRuntimeAppPublic for T {
260	type Public = Self;
261}