Skip to content

Commit ceb583c

Browse files
authored
chore: update ed25519-dalek to v2.1.1 (#122)
1 parent 8a9330c commit ceb583c

File tree

4 files changed

+54
-79
lines changed

4 files changed

+54
-79
lines changed

Cargo.lock

Lines changed: 1 addition & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ async-trait = "0.1.80"
1313
bs58 = "0.4.0"
1414
bytes = "1.4.0"
1515
cid = "0.10.1"
16-
ed25519-dalek = "1.0.1"
16+
ed25519-dalek = { version = "2.1.1", features = ["rand_core"] }
1717
futures = "0.3.27"
1818
futures-timer = "3.0.3"
1919
hex-literal = "0.4.1"

src/crypto/ed25519.rs

Lines changed: 50 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -24,38 +24,40 @@
2424
use crate::{error::Error, PeerId};
2525

2626
use ed25519_dalek::{self as ed25519, Signer as _, Verifier as _};
27-
use rand::RngCore;
27+
use std::fmt;
2828
use zeroize::Zeroize;
2929

30-
use std::{cmp, convert::TryFrom, fmt};
31-
3230
/// An Ed25519 keypair.
33-
pub struct Keypair(ed25519::Keypair);
31+
#[derive(Clone)]
32+
pub struct Keypair(ed25519::SigningKey);
3433

3534
impl Keypair {
3635
/// Generate a new random Ed25519 keypair.
3736
pub fn generate() -> Keypair {
3837
Keypair::from(SecretKey::generate())
3938
}
4039

41-
/// Encode the keypair into a byte array by concatenating the bytes
40+
/// Convert the keypair into a byte array by concatenating the bytes
4241
/// of the secret scalar and the compressed public point,
4342
/// an informal standard for encoding Ed25519 keypairs.
44-
pub fn encode(&self) -> [u8; 64] {
45-
self.0.to_bytes()
43+
pub fn to_bytes(&self) -> [u8; 64] {
44+
self.0.to_keypair_bytes()
4645
}
4746

48-
/// Decode a keypair from the [binary format](https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.5)
49-
/// produced by [`Keypair::encode`], zeroing the input on success.
47+
/// Try to parse a keypair from the [binary format](https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.5)
48+
/// produced by [`Keypair::to_bytes`], zeroing the input on success.
5049
///
5150
/// Note that this binary format is the same as `ed25519_dalek`'s and `ed25519_zebra`'s.
52-
pub fn decode(kp: &mut [u8]) -> crate::Result<Keypair> {
53-
ed25519::Keypair::from_bytes(kp)
51+
pub fn try_from_bytes(kp: &mut [u8]) -> Result<Keypair, Error> {
52+
let bytes = <[u8; 64]>::try_from(&*kp)
53+
.map_err(|e| Error::Other(format!("Failed to parse ed25519 keypair: {e}")))?;
54+
55+
ed25519::SigningKey::from_keypair_bytes(&bytes)
5456
.map(|k| {
5557
kp.zeroize();
5658
Keypair(k)
5759
})
58-
.map_err(|error| Error::Other(format!("Failed to parse keypair: {error:?}")))
60+
.map_err(|e| Error::Other(format!("Failed to parse ed25519 keypair: {e}")))
5961
}
6062

6163
/// Sign a message using the private key of this keypair.
@@ -65,56 +67,39 @@ impl Keypair {
6567

6668
/// Get the public key of this keypair.
6769
pub fn public(&self) -> PublicKey {
68-
PublicKey(self.0.public)
70+
PublicKey(self.0.verifying_key())
6971
}
7072

7173
/// Get the secret key of this keypair.
7274
pub fn secret(&self) -> SecretKey {
73-
SecretKey::from_bytes(&mut self.0.secret.to_bytes())
74-
.expect("ed25519::SecretKey::from_bytes(to_bytes(k)) != k")
75+
SecretKey(self.0.to_bytes())
7576
}
7677
}
7778

7879
impl fmt::Debug for Keypair {
7980
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80-
f.debug_struct("Keypair").field("public", &self.0.public).finish()
81-
}
82-
}
83-
84-
impl Clone for Keypair {
85-
fn clone(&self) -> Keypair {
86-
let mut sk_bytes = self.0.secret.to_bytes();
87-
let secret = SecretKey::from_bytes(&mut sk_bytes)
88-
.expect("ed25519::SecretKey::from_bytes(to_bytes(k)) != k")
89-
.0;
90-
let public = ed25519::PublicKey::from_bytes(&self.0.public.to_bytes())
91-
.expect("ed25519::PublicKey::from_bytes(to_bytes(k)) != k");
92-
Keypair(ed25519::Keypair { secret, public })
81+
f.debug_struct("Keypair").field("public", &self.0.verifying_key()).finish()
9382
}
9483
}
9584

9685
/// Demote an Ed25519 keypair to a secret key.
9786
impl From<Keypair> for SecretKey {
9887
fn from(kp: Keypair) -> SecretKey {
99-
SecretKey(kp.0.secret)
88+
SecretKey(kp.0.to_bytes())
10089
}
10190
}
10291

10392
/// Promote an Ed25519 secret key into a keypair.
10493
impl From<SecretKey> for Keypair {
10594
fn from(sk: SecretKey) -> Keypair {
106-
let secret: ed25519::ExpandedSecretKey = (&sk.0).into();
107-
let public = ed25519::PublicKey::from(&secret);
108-
Keypair(ed25519::Keypair {
109-
secret: sk.0,
110-
public,
111-
})
95+
let signing = ed25519::SigningKey::from_bytes(&sk.0);
96+
Keypair(signing)
11297
}
11398
}
11499

115100
/// An Ed25519 public key.
116101
#[derive(Eq, Clone)]
117-
pub struct PublicKey(ed25519::PublicKey);
102+
pub struct PublicKey(ed25519::VerifyingKey);
118103

119104
impl fmt::Debug for PublicKey {
120105
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
@@ -126,7 +111,7 @@ impl fmt::Debug for PublicKey {
126111
}
127112
}
128113

129-
impl cmp::PartialEq for PublicKey {
114+
impl PartialEq for PublicKey {
130115
fn eq(&self, other: &Self) -> bool {
131116
self.0.as_bytes().eq(other.0.as_bytes())
132117
}
@@ -138,16 +123,19 @@ impl PublicKey {
138123
ed25519::Signature::try_from(sig).and_then(|s| self.0.verify(msg, &s)).is_ok()
139124
}
140125

141-
/// Encode the public key into a byte array in compressed form, i.e.
126+
/// Convert the public key to a byte array in compressed form, i.e.
142127
/// where one coordinate is represented by a single bit.
143-
pub fn encode(&self) -> [u8; 32] {
128+
pub fn to_bytes(&self) -> [u8; 32] {
144129
self.0.to_bytes()
145130
}
146131

147-
/// Decode a public key from a byte array as produced by `encode`.
148-
pub fn decode(k: &[u8]) -> crate::Result<PublicKey> {
149-
ed25519::PublicKey::from_bytes(k)
150-
.map_err(|error| Error::Other(format!("Failed to parse keypair: {error:?}")))
132+
/// Try to parse a public key from a byte array containing the actual key as produced by
133+
/// `to_bytes`.
134+
pub fn try_from_bytes(k: &[u8]) -> crate::Result<PublicKey> {
135+
let k = <[u8; 32]>::try_from(k)
136+
.map_err(|e| Error::Other(format!("Failed to parse ed25519 public key: {e}")))?;
137+
ed25519::VerifyingKey::from_bytes(&k)
138+
.map_err(|e| Error::Other(format!("Failed to parse ed25519 public key: {e}")))
151139
.map(PublicKey)
152140
}
153141

@@ -158,19 +146,13 @@ impl PublicKey {
158146
}
159147

160148
/// An Ed25519 secret key.
149+
#[derive(Clone)]
161150
pub struct SecretKey(ed25519::SecretKey);
162151

163152
/// View the bytes of the secret key.
164153
impl AsRef<[u8]> for SecretKey {
165154
fn as_ref(&self) -> &[u8] {
166-
self.0.as_bytes()
167-
}
168-
}
169-
170-
impl Clone for SecretKey {
171-
fn clone(&self) -> SecretKey {
172-
let mut sk_bytes = self.0.to_bytes();
173-
Self::from_bytes(&mut sk_bytes).expect("ed25519::SecretKey::from_bytes(to_bytes(k)) != k")
155+
&self.0[..]
174156
}
175157
}
176158

@@ -183,29 +165,24 @@ impl fmt::Debug for SecretKey {
183165
impl SecretKey {
184166
/// Generate a new Ed25519 secret key.
185167
pub fn generate() -> SecretKey {
186-
let mut bytes = [0u8; 32];
187-
rand::thread_rng().fill_bytes(&mut bytes);
188-
SecretKey(
189-
ed25519::SecretKey::from_bytes(&bytes).expect(
190-
"this returns `Err` only if the length is wrong; the length is correct; qed",
191-
),
192-
)
168+
let signing = ed25519::SigningKey::generate(&mut rand::rngs::OsRng);
169+
SecretKey(signing.to_bytes())
193170
}
194-
195-
/// Create an Ed25519 secret key from a byte slice, zeroing the input on success.
171+
/// Try to parse an Ed25519 secret key from a byte slice
172+
/// containing the actual key, zeroing the input on success.
196173
/// If the bytes do not constitute a valid Ed25519 secret key, an error is
197174
/// returned.
198-
pub fn from_bytes(mut sk_bytes: impl AsMut<[u8]>) -> crate::Result<SecretKey> {
175+
pub fn try_from_bytes(mut sk_bytes: impl AsMut<[u8]>) -> crate::Result<SecretKey> {
199176
let sk_bytes = sk_bytes.as_mut();
200-
let secret = ed25519::SecretKey::from_bytes(&*sk_bytes)
201-
.map_err(|error| Error::Other(format!("Failed to parse keypair: {error:?}")))?;
177+
let secret = <[u8; 32]>::try_from(&*sk_bytes)
178+
.map_err(|e| Error::Other(format!("Failed to parse ed25519 secret key: {e}")))?;
202179
sk_bytes.zeroize();
203180
Ok(SecretKey(secret))
204181
}
205182

206183
/// Convert this secret key to a byte array.
207184
pub fn to_bytes(&self) -> [u8; 32] {
208-
self.0.to_bytes()
185+
self.0
209186
}
210187
}
211188

@@ -215,15 +192,15 @@ mod tests {
215192
use quickcheck::*;
216193

217194
fn eq_keypairs(kp1: &Keypair, kp2: &Keypair) -> bool {
218-
kp1.public() == kp2.public() && kp1.0.secret.as_bytes() == kp2.0.secret.as_bytes()
195+
kp1.public() == kp2.public() && kp1.0.to_bytes() == kp2.0.to_bytes()
219196
}
220197

221198
#[test]
222199
fn ed25519_keypair_encode_decode() {
223200
fn prop() -> bool {
224201
let kp1 = Keypair::generate();
225-
let mut kp1_enc = kp1.encode();
226-
let kp2 = Keypair::decode(&mut kp1_enc).unwrap();
202+
let mut kp1_enc = kp1.to_bytes();
203+
let kp2 = Keypair::try_from_bytes(&mut kp1_enc).unwrap();
227204
eq_keypairs(&kp1, &kp2) && kp1_enc.iter().all(|b| *b == 0)
228205
}
229206
QuickCheck::new().tests(10).quickcheck(prop as fn() -> _);
@@ -233,8 +210,8 @@ mod tests {
233210
fn ed25519_keypair_from_secret() {
234211
fn prop() -> bool {
235212
let kp1 = Keypair::generate();
236-
let mut sk = kp1.0.secret.to_bytes();
237-
let kp2 = Keypair::from(SecretKey::from_bytes(&mut sk).unwrap());
213+
let mut sk = kp1.0.to_bytes();
214+
let kp2 = Keypair::from(SecretKey::try_from_bytes(&mut sk).unwrap());
238215
eq_keypairs(&kp1, &kp2) && sk == [0u8; 32]
239216
}
240217
QuickCheck::new().tests(10).quickcheck(prop as fn() -> _);
@@ -269,13 +246,13 @@ mod tests {
269246
tracing::trace!("public: {:?}", key.public());
270247

271248
let new_key = Keypair::from(key.secret());
272-
assert!(new_key.secret().as_ref() == key.secret().as_ref());
273-
assert!(new_key.public() == key.public());
249+
assert_eq!(new_key.secret().as_ref(), key.secret().as_ref());
250+
assert_eq!(new_key.public(), key.public());
274251

275252
let new_secret = SecretKey::from(new_key.clone());
276-
assert!(new_secret.as_ref() == new_key.secret().as_ref());
253+
assert_eq!(new_secret.as_ref(), new_key.secret().as_ref());
277254

278255
let cloned_secret = new_secret.clone();
279-
assert!(cloned_secret.as_ref() == new_secret.as_ref());
256+
assert_eq!(cloned_secret.as_ref(), new_secret.as_ref());
280257
}
281258
}

src/crypto/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ impl From<&PublicKey> for keys_proto::PublicKey {
8484
match key {
8585
PublicKey::Ed25519(key) => keys_proto::PublicKey {
8686
r#type: keys_proto::KeyType::Ed25519 as i32,
87-
data: key.encode().to_vec(),
87+
data: key.to_bytes().to_vec(),
8888
},
8989
}
9090
}
@@ -99,7 +99,7 @@ impl TryFrom<keys_proto::PublicKey> for PublicKey {
9999

100100
match key_type {
101101
keys_proto::KeyType::Ed25519 =>
102-
Ok(ed25519::PublicKey::decode(&pubkey.data).map(PublicKey::Ed25519)?),
102+
Ok(ed25519::PublicKey::try_from_bytes(&pubkey.data).map(PublicKey::Ed25519)?),
103103
_ => Err(Error::Other(format!(
104104
"Unsupported key type: {}",
105105
key_type.as_str_name()

0 commit comments

Comments
 (0)