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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
use ed25519_dalek as ed25519;
use rand::RngCore;
use rlp::DecoderError;
use sha3::{Digest, Keccak256};
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;
#[cfg(feature = "libp2p")]
use libp2p_core::{
identity::{Keypair as Libp2pKeypair, PublicKey as Libp2pPublicKey},
PeerId,
};
#[cfg(feature = "libp2p")]
use std::convert::TryFrom;
pub trait EnrKey {
type PublicKey: EnrPublicKey + Clone + Into<String>;
fn sign_v4(&self, msg: &[u8]) -> Result<Vec<u8>, SigningError>;
fn public(&self) -> Self::PublicKey;
fn enr_to_public(content: &BTreeMap<String, Vec<u8>>) -> Result<Self::PublicKey, DecoderError>;
}
pub trait EnrPublicKey {
fn verify_v4(&self, msg: &[u8], sig: &[u8]) -> bool;
fn encode(&self) -> Vec<u8>;
fn encode_uncompressed(&self) -> Vec<u8>;
#[cfg(feature = "libp2p")]
fn into_peer_id(&self) -> PeerId;
}
pub enum DefaultKey {
Secp256k1(secp256k1::SecretKey),
Ed25519(ed25519::Keypair),
}
impl From<secp256k1::SecretKey> for DefaultKey {
fn from(secret_key: secp256k1::SecretKey) -> DefaultKey {
DefaultKey::Secp256k1(secret_key)
}
}
impl From<ed25519_dalek::Keypair> for DefaultKey {
fn from(keypair: ed25519_dalek::Keypair) -> DefaultKey {
DefaultKey::Ed25519(keypair)
}
}
impl From<ed25519_dalek::SecretKey> for DefaultKey {
fn from(sk: ed25519_dalek::SecretKey) -> DefaultKey {
let secret: ed25519::ExpandedSecretKey = (&sk).into();
let public = ed25519::PublicKey::from(&secret);
DefaultKey::Ed25519(ed25519::Keypair { secret: sk, public })
}
}
#[cfg(feature = "libp2p")]
impl TryFrom<Libp2pKeypair> for DefaultKey {
type Error = &'static str;
fn try_from(keypair: Libp2pKeypair) -> Result<Self, Self::Error> {
match keypair {
Libp2pKeypair::Secp256k1(key) => {
let secret = secp256k1::SecretKey::parse(&key.secret().to_bytes())
.expect("libp2p key must be valid");
Ok(DefaultKey::Secp256k1(secret))
}
Libp2pKeypair::Ed25519(key) => {
let a = key.encode();
dbg!(a.len());
let ed_keypair = ed25519::SecretKey::from_bytes(&key.encode()[..32])
.expect("libp2p key must be valid");
Ok(DefaultKey::from(ed_keypair))
}
_ => Err("Unsupported key type"),
}
}
}
impl EnrKey for DefaultKey {
type PublicKey = DefaultPublicKey;
fn sign_v4(&self, msg: &[u8]) -> Result<Vec<u8>, SigningError> {
match self {
DefaultKey::Secp256k1(ref key) => {
let hash = Keccak256::digest(msg);
let m = secp256k1::Message::parse_slice(&hash)
.map_err(|_| SigningError::new("failed to parse secp256k1 digest"))?;
Ok(secp256k1::sign(&m, &key).0.serialize().to_vec())
}
DefaultKey::Ed25519(ref keypair) => Ok(keypair.sign(msg).to_bytes().to_vec()),
}
}
fn public(&self) -> Self::PublicKey {
match self {
DefaultKey::Secp256k1(secret_key) => {
DefaultPublicKey::Secp256k1(secp256k1::PublicKey::from_secret_key(&secret_key))
}
DefaultKey::Ed25519(keypair) => DefaultPublicKey::Ed25519(keypair.public),
}
}
fn enr_to_public(content: &BTreeMap<String, Vec<u8>>) -> Result<Self::PublicKey, DecoderError> {
if let Some(pubkey_bytes) = content.get("secp256k1") {
secp256k1::PublicKey::parse_slice(
pubkey_bytes,
Some(secp256k1::PublicKeyFormat::Compressed),
)
.map(DefaultPublicKey::Secp256k1)
.map_err(|_| DecoderError::Custom("Invalid Secp256k1 Signature"))
} else if let Some(pubkey_bytes) = content.get("ed25519") {
ed25519::PublicKey::from_bytes(pubkey_bytes)
.map(DefaultPublicKey::Ed25519)
.map_err(|_| DecoderError::Custom("Invalid ed25519 Signature"))
} else {
Err(DecoderError::Custom("Unknown signature"))
}
}
}
impl DefaultKey {
pub fn generate_secp256k1() -> Self {
let mut r = rand::thread_rng();
let mut b = [0; secp256k1::util::SECRET_KEY_SIZE];
loop {
r.fill_bytes(&mut b);
if let Ok(k) = secp256k1::SecretKey::parse(&b) {
return DefaultKey::Secp256k1(k);
}
}
}
pub fn generate_ed25519() -> Self {
let mut bytes = [0u8; 32];
rand::thread_rng().fill_bytes(&mut bytes);
DefaultKey::from(
ed25519::SecretKey::from_bytes(&bytes).expect(
"this returns `Err` only if the length is wrong; the length is correct; qed",
),
)
}
pub fn secp256k1_from_bytes(bytes: &[u8]) -> Result<Self, DecoderError> {
secp256k1::SecretKey::parse_slice(bytes)
.map_err(|_| DecoderError::Custom("Invalid secp256k1 secret key"))
.map(DefaultKey::from)
}
pub fn ed25519_from_bytes(bytes: &[u8]) -> Result<Self, DecoderError> {
ed25519::SecretKey::from_bytes(bytes)
.map_err(|_| DecoderError::Custom("Invalid ed25519 secret key"))
.map(DefaultKey::from)
}
pub fn encode(&self) -> Vec<u8> {
match self {
DefaultKey::Secp256k1(key) => key.serialize().to_vec(),
DefaultKey::Ed25519(key) => key.secret.as_bytes().to_vec(),
}
}
}
#[derive(Clone, Debug)]
pub enum DefaultPublicKey {
Secp256k1(secp256k1::PublicKey),
Ed25519(ed25519::PublicKey),
}
impl From<secp256k1::PublicKey> for DefaultPublicKey {
fn from(public_key: secp256k1::PublicKey) -> DefaultPublicKey {
DefaultPublicKey::Secp256k1(public_key)
}
}
impl From<ed25519::PublicKey> for DefaultPublicKey {
fn from(public_key: ed25519::PublicKey) -> DefaultPublicKey {
DefaultPublicKey::Ed25519(public_key)
}
}
impl Into<String> for DefaultPublicKey {
fn into(self) -> String {
match self {
DefaultPublicKey::Secp256k1(_) => String::from("secp256k1"),
DefaultPublicKey::Ed25519(_) => String::from("ed25519"),
}
}
}
impl EnrPublicKey for DefaultPublicKey {
fn verify_v4(&self, msg: &[u8], sig: &[u8]) -> bool {
match self {
DefaultPublicKey::Secp256k1(pk) => {
let msg = Keccak256::digest(msg);
secp256k1::Signature::parse_slice(sig)
.and_then(|sig| {
secp256k1::Message::parse_slice(&msg)
.map(|m| secp256k1::verify(&m, &sig, pk))
})
.is_ok()
}
DefaultPublicKey::Ed25519(pk) => ed25519::Signature::from_bytes(sig)
.and_then(|s| pk.verify(msg, &s))
.is_ok(),
}
}
fn encode(&self) -> Vec<u8> {
match self {
DefaultPublicKey::Secp256k1(pk) => pk.serialize_compressed().to_vec(),
DefaultPublicKey::Ed25519(pk) => pk.to_bytes().to_vec(),
}
}
fn encode_uncompressed(&self) -> Vec<u8> {
match self {
DefaultPublicKey::Secp256k1(pk) => pk.serialize()[1..].to_vec(),
DefaultPublicKey::Ed25519(pk) => pk.to_bytes().to_vec(),
}
}
#[cfg(feature = "libp2p")]
fn into_peer_id(&self) -> PeerId {
match self {
DefaultPublicKey::Secp256k1(pk) => {
let pk_bytes = pk.serialize_compressed();
let libp2p_pk = Libp2pPublicKey::Secp256k1(
libp2p_core::identity::secp256k1::PublicKey::decode(&pk_bytes)
.expect("valid public key"),
);
PeerId::from_public_key(libp2p_pk)
}
DefaultPublicKey::Ed25519(pk) => {
let pk_bytes = pk.to_bytes();
let libp2p_pk = Libp2pPublicKey::Ed25519(
libp2p_core::identity::ed25519::PublicKey::decode(&pk_bytes)
.expect("valid public key"),
);
PeerId::from_public_key(libp2p_pk)
}
}
}
}
#[derive(Debug)]
pub struct SigningError {
msg: String,
source: Option<Box<dyn Error + Send + Sync>>,
}
impl SigningError {
pub(crate) fn new<S: ToString>(msg: S) -> Self {
Self {
msg: msg.to_string(),
source: None,
}
}
}
impl fmt::Display for SigningError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Key signing error: {}", self.msg)
}
}
impl Error for SigningError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.as_ref().map(|s| &**s as &dyn Error)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "libp2p")]
use std::convert::TryInto;
#[cfg(feature = "libp2p")]
#[test]
fn test_key_conversion() {
let libp2p_key = libp2p_core::identity::Keypair::generate_secp256k1();
let _enr_key: DefaultKey = libp2p_key
.try_into()
.expect("Should be able to convert a libp2p secp256k1 keypair");
let libp2p_key = libp2p_core::identity::Keypair::generate_ed25519();
let _enr_key: DefaultKey = libp2p_key
.try_into()
.expect("Should be able to convert a libp2p ed25519 keypair");
}
#[test]
fn test_key_secp256k1_encoding() {
let key = DefaultKey::generate_secp256k1();
let key_bytes = key.encode();
DefaultKey::secp256k1_from_bytes(&key_bytes).expect("Valid encoding");
}
#[test]
fn test_key_ed25519_encoding() {
let key = DefaultKey::generate_ed25519();
let key_bytes = key.encode();
DefaultKey::ed25519_from_bytes(&key_bytes).expect("Valid encoding");
}
}