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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
use crate::{
bls12381, bls12381::DST_BLS_SIG_IN_G2_WITH_POP, hash::CryptoHash, signing_message, traits,
CryptoMaterialError, Genesis, Length, Uniform, ValidCryptoMaterial,
ValidCryptoMaterialStringExt, VerifyingKey,
};
use anyhow::{anyhow, Result};
use aptos_crypto_derive::{DeserializeKey, SerializeKey, SilentDebug, SilentDisplay};
use serde::Serialize;
use std::{convert::TryFrom, fmt};
#[derive(Clone, Debug, Eq, SerializeKey, DeserializeKey)]
pub struct PublicKey {
pub(crate) pubkey: blst::min_pk::PublicKey,
}
#[derive(SerializeKey, DeserializeKey, SilentDebug, SilentDisplay)]
pub struct PrivateKey {
pub(crate) privkey: blst::min_pk::SecretKey,
}
impl PublicKey {
pub const LENGTH: usize = 48;
pub fn to_bytes(&self) -> [u8; Self::LENGTH] {
self.pubkey.to_bytes()
}
pub fn group_check(&self) -> Result<()> {
self.pubkey.validate().map_err(|e| anyhow!("{:?}", e))
}
pub fn aggregate(pubkeys: Vec<&Self>) -> Result<PublicKey> {
let blst_pubkeys: Vec<_> = pubkeys.iter().map(|pk| &pk.pubkey).collect();
let aggpk = blst::min_pk::AggregatePublicKey::aggregate(&blst_pubkeys[..], false)
.map_err(|e| anyhow!("{:?}", e))?;
Ok(PublicKey {
pubkey: aggpk.to_public_key(),
})
}
}
impl PrivateKey {
pub const LENGTH: usize = 32;
pub fn to_bytes(&self) -> [u8; Self::LENGTH] {
self.privkey.to_bytes()
}
}
impl traits::PrivateKey for PrivateKey {
type PublicKeyMaterial = PublicKey;
}
impl traits::SigningKey for PrivateKey {
type VerifyingKeyMaterial = PublicKey;
type SignatureMaterial = bls12381::Signature;
fn sign<T: CryptoHash + Serialize>(&self, message: &T) -> bls12381::Signature {
bls12381::Signature {
sig: self
.privkey
.sign(&signing_message(message), DST_BLS_SIG_IN_G2_WITH_POP, &[]),
}
}
#[cfg(any(test, feature = "fuzzing"))]
fn sign_arbitrary_message(&self, message: &[u8]) -> bls12381::Signature {
bls12381::Signature {
sig: self.privkey.sign(message, DST_BLS_SIG_IN_G2_WITH_POP, &[]),
}
}
}
impl traits::ValidCryptoMaterial for PrivateKey {
fn to_bytes(&self) -> Vec<u8> {
self.to_bytes().to_vec()
}
}
impl Length for PrivateKey {
fn length(&self) -> usize {
Self::LENGTH
}
}
impl TryFrom<&[u8]> for PrivateKey {
type Error = CryptoMaterialError;
fn try_from(bytes: &[u8]) -> std::result::Result<Self, CryptoMaterialError> {
Ok(Self {
privkey: blst::min_pk::SecretKey::from_bytes(bytes)
.map_err(|_| CryptoMaterialError::DeserializationError)?,
})
}
}
impl Uniform for PrivateKey {
fn generate<R>(rng: &mut R) -> Self
where
R: ::rand::RngCore + ::rand::CryptoRng,
{
let mut ikm = [0u8; 32];
rng.fill_bytes(&mut ikm);
let privkey =
blst::min_pk::SecretKey::key_gen(&ikm, &[]).expect("ikm length should be higher");
Self { privkey }
}
}
impl Genesis for PrivateKey {
fn genesis() -> Self {
let mut buf = [0u8; Self::LENGTH];
buf[Self::LENGTH - 1] = 1;
Self::try_from(buf.as_ref()).unwrap()
}
}
#[cfg(feature = "assert-private-keys-not-cloneable")]
static_assertions::assert_not_impl_any!(PrivateKey: Clone);
#[cfg(any(test, feature = "cloneable-private-keys"))]
impl Clone for PrivateKey {
fn clone(&self) -> Self {
let serialized: &[u8] = &(self.to_bytes());
PrivateKey::try_from(serialized).unwrap()
}
}
impl From<&PrivateKey> for PublicKey {
fn from(private_key: &PrivateKey) -> Self {
Self {
pubkey: private_key.privkey.sk_to_pk(),
}
}
}
impl traits::PublicKey for PublicKey {
type PrivateKeyMaterial = PrivateKey;
}
impl VerifyingKey for PublicKey {
type SigningKeyMaterial = PrivateKey;
type SignatureMaterial = bls12381::Signature;
}
impl ValidCryptoMaterial for PublicKey {
fn to_bytes(&self) -> Vec<u8> {
self.to_bytes().to_vec()
}
}
impl Length for PublicKey {
fn length(&self) -> usize {
Self::LENGTH
}
}
impl TryFrom<&[u8]> for PublicKey {
type Error = CryptoMaterialError;
fn try_from(bytes: &[u8]) -> std::result::Result<Self, CryptoMaterialError> {
Ok(Self {
pubkey: blst::min_pk::PublicKey::from_bytes(bytes)
.map_err(|_| CryptoMaterialError::DeserializationError)?,
})
}
}
impl std::hash::Hash for PublicKey {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
let encoded_pubkey = self.to_bytes();
state.write(&encoded_pubkey);
}
}
impl PartialEq for PublicKey {
fn eq(&self, other: &Self) -> bool {
self.to_bytes()[..] == other.to_bytes()[..]
}
}
impl fmt::Display for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", hex::encode(&self.to_bytes()))
}
}
#[cfg(any(test, feature = "fuzzing"))]
use crate::test_utils::KeyPair;
#[cfg(any(test, feature = "fuzzing"))]
use proptest::prelude::*;
#[cfg(any(test, feature = "fuzzing"))]
pub fn keypair_strategy() -> impl Strategy<Value = KeyPair<PrivateKey, PublicKey>> {
crate::test_utils::uniform_keypair_strategy::<PrivateKey, PublicKey>()
}
#[cfg(any(test, feature = "fuzzing"))]
impl proptest::arbitrary::Arbitrary for PublicKey {
type Parameters = ();
type Strategy = BoxedStrategy<Self>;
fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
crate::test_utils::uniform_keypair_strategy::<PrivateKey, PublicKey>()
.prop_map(|v| v.public_key)
.boxed()
}
}