This repository has been archived by the owner on Jun 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 75
/
key.rs
251 lines (210 loc) · 7.09 KB
/
key.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
use crate::bech32::{self, Bech32};
use crate::hex;
use rand::{CryptoRng, RngCore};
use std::fmt;
use std::hash::Hash;
use std::str::FromStr;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum SecretKeyError {
SizeInvalid,
StructureInvalid,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum PublicKeyError {
SizeInvalid,
StructureInvalid,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PublicKeyFromStrError {
HexMalformed(hex::DecodeError),
KeyInvalid(PublicKeyError),
}
pub trait AsymmetricKey {
type Secret: AsRef<[u8]> + Clone;
type Public: AsRef<[u8]> + Clone + PartialEq + Eq + Hash;
const SECRET_BECH32_HRP: &'static str;
const PUBLIC_BECH32_HRP: &'static str;
const PUBLIC_KEY_SIZE: usize;
fn generate<T: RngCore + CryptoRng>(rng: T) -> Self::Secret;
fn compute_public(secret: &Self::Secret) -> Self::Public;
fn secret_from_binary(data: &[u8]) -> Result<Self::Secret, SecretKeyError>;
fn public_from_binary(data: &[u8]) -> Result<Self::Public, PublicKeyError>;
}
pub trait SecretKeySizeStatic: AsymmetricKey {
const SECRET_KEY_SIZE: usize;
}
pub struct SecretKey<A: AsymmetricKey>(pub(crate) A::Secret);
pub struct PublicKey<A: AsymmetricKey>(pub(crate) A::Public);
pub struct KeyPair<A: AsymmetricKey>(SecretKey<A>, PublicKey<A>);
impl<A: AsymmetricKey> KeyPair<A> {
pub fn private_key(&self) -> &SecretKey<A> {
&self.0
}
pub fn public_key(&self) -> &PublicKey<A> {
&self.1
}
pub fn into_keys(self) -> (SecretKey<A>, PublicKey<A>) {
(self.0, self.1)
}
}
impl<A: AsymmetricKey> std::fmt::Debug for KeyPair<A> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "KeyPair(<secret key>, {:?})", self.public_key())
}
}
impl<A: AsymmetricKey> std::fmt::Display for KeyPair<A> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "KeyPair(<secret key>, {})", self.public_key())
}
}
impl<A: AsymmetricKey> fmt::Debug for PublicKey<A> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", hex::encode(self.0.as_ref()))
}
}
impl<A: AsymmetricKey> fmt::Display for PublicKey<A> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", hex::encode(self.0.as_ref()))
}
}
impl<A: AsymmetricKey> FromStr for PublicKey<A> {
type Err = PublicKeyFromStrError;
fn from_str(hex: &str) -> Result<Self, Self::Err> {
let bytes = hex::decode(hex).map_err(PublicKeyFromStrError::HexMalformed)?;
Self::from_binary(&bytes).map_err(PublicKeyFromStrError::KeyInvalid)
}
}
impl fmt::Display for SecretKeyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
SecretKeyError::SizeInvalid => write!(f, "Invalid Secret Key size"),
SecretKeyError::StructureInvalid => write!(f, "Invalid Secret Key structure"),
}
}
}
impl fmt::Display for PublicKeyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
PublicKeyError::SizeInvalid => write!(f, "Invalid Public Key size"),
PublicKeyError::StructureInvalid => write!(f, "Invalid Public Key structure"),
}
}
}
impl fmt::Display for PublicKeyFromStrError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
PublicKeyFromStrError::HexMalformed(_) => "hex encoding malformed",
PublicKeyFromStrError::KeyInvalid(_) => "invalid public key data",
}
.fmt(f)
}
}
impl std::error::Error for SecretKeyError {}
impl std::error::Error for PublicKeyError {}
impl std::error::Error for PublicKeyFromStrError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
PublicKeyFromStrError::HexMalformed(e) => Some(e),
PublicKeyFromStrError::KeyInvalid(e) => Some(e),
}
}
}
impl<A: AsymmetricKey> AsRef<[u8]> for PublicKey<A> {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl<A: AsymmetricKey> From<SecretKey<A>> for KeyPair<A> {
fn from(secret_key: SecretKey<A>) -> Self {
let public_key = secret_key.to_public();
KeyPair(secret_key, public_key)
}
}
impl<A: AsymmetricKey> SecretKey<A> {
pub fn generate<T: RngCore + CryptoRng>(rng: T) -> Self {
SecretKey(A::generate(rng))
}
pub fn to_public(&self) -> PublicKey<A> {
PublicKey(<A as AsymmetricKey>::compute_public(&self.0))
}
pub fn from_binary(data: &[u8]) -> Result<Self, SecretKeyError> {
Ok(SecretKey(<A as AsymmetricKey>::secret_from_binary(data)?))
}
}
impl<A: AsymmetricKey> PublicKey<A> {
pub fn from_binary(data: &[u8]) -> Result<Self, PublicKeyError> {
Ok(PublicKey(<A as AsymmetricKey>::public_from_binary(data)?))
}
}
impl<A: AsymmetricKey> Clone for SecretKey<A> {
fn clone(&self) -> Self {
SecretKey(self.0.clone())
}
}
impl<A: AsymmetricKey> Clone for PublicKey<A> {
fn clone(&self) -> Self {
PublicKey(self.0.clone())
}
}
impl<A: AsymmetricKey> Clone for KeyPair<A> {
fn clone(&self) -> Self {
KeyPair(self.0.clone(), self.1.clone())
}
}
impl<A: AsymmetricKey> std::cmp::PartialEq<Self> for PublicKey<A> {
fn eq(&self, other: &Self) -> bool {
self.0.as_ref().eq(other.0.as_ref())
}
}
impl<A: AsymmetricKey> std::cmp::Eq for PublicKey<A> {}
impl<A: AsymmetricKey> std::cmp::PartialOrd<Self> for PublicKey<A> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.0.as_ref().partial_cmp(other.0.as_ref())
}
}
impl<A: AsymmetricKey> std::cmp::Ord for PublicKey<A> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0.as_ref().cmp(other.0.as_ref())
}
}
impl<A: AsymmetricKey> Hash for PublicKey<A> {
fn hash<H>(&self, state: &mut H)
where
H: std::hash::Hasher,
{
self.0.as_ref().hash(state)
}
}
impl<A: AsymmetricKey> Bech32 for PublicKey<A> {
const BECH32_HRP: &'static str = A::PUBLIC_BECH32_HRP;
fn try_from_bech32_str(bech32_str: &str) -> Result<Self, bech32::Error> {
let bytes = bech32::try_from_bech32_to_bytes::<Self>(bech32_str)?;
Self::from_binary(&bytes).map_err(bech32::Error::data_invalid)
}
fn to_bech32_str(&self) -> String {
bech32::to_bech32_from_bytes::<Self>(self.as_ref())
}
}
impl<A: AsymmetricKey> Bech32 for SecretKey<A> {
const BECH32_HRP: &'static str = A::SECRET_BECH32_HRP;
fn try_from_bech32_str(bech32_str: &str) -> Result<Self, bech32::Error> {
let bytes = bech32::try_from_bech32_to_bytes::<Self>(bech32_str)?;
Self::from_binary(&bytes).map_err(bech32::Error::data_invalid)
}
fn to_bech32_str(&self) -> String {
bech32::to_bech32_from_bytes::<Self>(self.0.as_ref())
}
}
#[cfg(test)]
mod test {
use super::*;
// ONLY ALLOWED WHEN TESTING
impl<A> std::fmt::Debug for SecretKey<A>
where
A: AsymmetricKey,
{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "SecretKey ({:?})", self.0.as_ref())
}
}
}