Skip to content

Commit

Permalink
Merge pull request #146 from xu-cheng/serde2
Browse files Browse the repository at this point in the history
Fix serde implementation for serde_json
  • Loading branch information
isislovecruft authored Sep 22, 2020
2 parents a9ebf7f + 69eccda commit 97c22f2
Show file tree
Hide file tree
Showing 6 changed files with 124 additions and 158 deletions.
6 changes: 4 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ merlin = { version = "2", default-features = false, optional = true }
rand = { version = "0.7", default-features = false, optional = true }
rand_core = { version = "0.5", default-features = false, optional = true }
serde_crate = { package = "serde", version = "1.0", default-features = false, optional = true }
serde_bytes = { version = "0.11", optional = true }
sha2 = { version = "0.9", default-features = false }
zeroize = { version = "1", default-features = false, features = ["zeroize_derive"] }

[dev-dependencies]
hex = "^0.4"
bincode = "^0.9"
bincode = "1.0"
serde_json = "1.0"
criterion = "0.3"
rand = "0.7"
serde_crate = { package = "serde", version = "1.0", features = ["derive"] }
Expand All @@ -51,7 +53,7 @@ default = ["std", "rand", "u64_backend"]
std = ["curve25519-dalek/std", "ed25519/std", "serde_crate/std", "sha2/std", "rand/std"]
alloc = ["curve25519-dalek/alloc", "rand/alloc", "zeroize/alloc"]
nightly = ["curve25519-dalek/nightly"]
serde = ["serde_crate", "ed25519/serde"]
serde = ["serde_crate", "serde_bytes", "ed25519/serde"]
batch = ["merlin", "rand"]
# This feature enables deterministic batch verification.
batch_deterministic = ["merlin", "rand", "rand_core"]
Expand Down
69 changes: 6 additions & 63 deletions src/keypair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,9 @@ use rand::{CryptoRng, RngCore};
#[cfg(feature = "serde")]
use serde::de::Error as SerdeError;
#[cfg(feature = "serde")]
use serde::de::Visitor;
#[cfg(feature = "serde")]
use serde::de::SeqAccess;
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "serde")]
use serde_bytes::{Bytes as SerdeBytes, ByteBuf as SerdeByteBuf};

pub use sha2::Sha512;

Expand Down Expand Up @@ -428,7 +426,8 @@ impl Serialize for Keypair {
where
S: Serializer,
{
serializer.serialize_bytes(&self.to_bytes()[..])
let bytes = &self.to_bytes()[..];
SerdeBytes::new(bytes).serialize(serializer)
}
}

Expand All @@ -438,63 +437,7 @@ impl<'d> Deserialize<'d> for Keypair {
where
D: Deserializer<'d>,
{
struct KeypairVisitor;

impl<'d> Visitor<'d> for KeypairVisitor {
type Value = Keypair;

fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
formatter.write_str("An ed25519 keypair, 64 bytes in total where the secret key is \
the first 32 bytes and is in unexpanded form, and the second \
32 bytes is a compressed point for a public key.")
}

fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Keypair, E>
where
E: SerdeError,
{
if bytes.len() != KEYPAIR_LENGTH {
return Err(SerdeError::invalid_length(bytes.len(), &self));
}

let secret_key = SecretKey::from_bytes(&bytes[..SECRET_KEY_LENGTH]);
let public_key = PublicKey::from_bytes(&bytes[SECRET_KEY_LENGTH..]);

if let (Ok(secret), Ok(public)) = (secret_key, public_key) {
Ok(Keypair{ secret, public })
} else {
Err(SerdeError::invalid_length(bytes.len(), &self))
}
}

fn visit_seq<A>(self, mut seq: A) -> Result<Keypair, A::Error>
where
A: SeqAccess<'d>
{
if let Some(len) = seq.size_hint() {
if len != KEYPAIR_LENGTH {
return Err(SerdeError::invalid_length(len, &self));
}
}

// TODO: We could do this with `MaybeUninit` to avoid unnecessary initialization costs
let mut bytes: [u8; KEYPAIR_LENGTH] = [0u8; KEYPAIR_LENGTH];

for i in 0..KEYPAIR_LENGTH {
bytes[i] = seq.next_element()?.ok_or_else(|| SerdeError::invalid_length(i, &self))?;
}

let secret_key = SecretKey::from_bytes(&bytes[..SECRET_KEY_LENGTH]);
let public_key = PublicKey::from_bytes(&bytes[SECRET_KEY_LENGTH..]);

if let (Ok(secret), Ok(public)) = (secret_key, public_key) {
Ok(Keypair{ secret, public })
} else {
Err(SerdeError::invalid_length(bytes.len(), &self))
}
}

}
deserializer.deserialize_bytes(KeypairVisitor)
let bytes = <SerdeByteBuf>::deserialize(deserializer)?;
Keypair::from_bytes(bytes.as_ref()).map_err(SerdeError::custom)
}
}
12 changes: 6 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,16 +176,16 @@
//! # fn main() {
//! # use rand::rngs::OsRng;
//! # use ed25519_dalek::{Keypair, Signature, Signer, Verifier, PublicKey};
//! use bincode::{serialize, Infinite};
//! use bincode::serialize;
//! # let mut csprng = OsRng{};
//! # let keypair: Keypair = Keypair::generate(&mut csprng);
//! # let message: &[u8] = b"This is a test of the tsunami alert system.";
//! # let signature: Signature = keypair.sign(message);
//! # let public_key: PublicKey = keypair.public;
//! # let verified: bool = public_key.verify(message, &signature).is_ok();
//!
//! let encoded_public_key: Vec<u8> = serialize(&public_key, Infinite).unwrap();
//! let encoded_signature: Vec<u8> = serialize(&signature, Infinite).unwrap();
//! let encoded_public_key: Vec<u8> = serialize(&public_key).unwrap();
//! let encoded_signature: Vec<u8> = serialize(&signature).unwrap();
//! # }
//! # #[cfg(not(feature = "serde"))]
//! # fn main() {}
Expand All @@ -206,7 +206,7 @@
//! # fn main() {
//! # use rand::rngs::OsRng;
//! # use ed25519_dalek::{Keypair, Signature, Signer, Verifier, PublicKey};
//! # use bincode::{serialize, Infinite};
//! # use bincode::serialize;
//! use bincode::deserialize;
//!
//! # let mut csprng = OsRng{};
Expand All @@ -215,8 +215,8 @@
//! # let signature: Signature = keypair.sign(message);
//! # let public_key: PublicKey = keypair.public;
//! # let verified: bool = public_key.verify(message, &signature).is_ok();
//! # let encoded_public_key: Vec<u8> = serialize(&public_key, Infinite).unwrap();
//! # let encoded_signature: Vec<u8> = serialize(&signature, Infinite).unwrap();
//! # let encoded_public_key: Vec<u8> = serialize(&public_key).unwrap();
//! # let encoded_signature: Vec<u8> = serialize(&signature).unwrap();
//! let decoded_public_key: PublicKey = deserialize(&encoded_public_key).unwrap();
//! let decoded_signature: Signature = deserialize(&encoded_signature).unwrap();
//!
Expand Down
29 changes: 5 additions & 24 deletions src/public.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,9 @@ pub use sha2::Sha512;
#[cfg(feature = "serde")]
use serde::de::Error as SerdeError;
#[cfg(feature = "serde")]
use serde::de::Visitor;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "serde")]
use serde::{Deserializer, Serializer};
use serde_bytes::{Bytes as SerdeBytes, ByteBuf as SerdeByteBuf};

use crate::constants::*;
use crate::errors::*;
Expand Down Expand Up @@ -362,7 +360,7 @@ impl Serialize for PublicKey {
where
S: Serializer,
{
serializer.serialize_bytes(self.as_bytes())
SerdeBytes::new(self.as_bytes()).serialize(serializer)
}
}

Expand All @@ -372,24 +370,7 @@ impl<'d> Deserialize<'d> for PublicKey {
where
D: Deserializer<'d>,
{
struct PublicKeyVisitor;

impl<'d> Visitor<'d> for PublicKeyVisitor {
type Value = PublicKey;

fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
formatter.write_str(
"An ed25519 public key as a 32-byte compressed point, as specified in RFC8032",
)
}

fn visit_bytes<E>(self, bytes: &[u8]) -> Result<PublicKey, E>
where
E: SerdeError,
{
PublicKey::from_bytes(bytes).or(Err(SerdeError::invalid_length(bytes.len(), &self)))
}
}
deserializer.deserialize_bytes(PublicKeyVisitor)
let bytes = <SerdeByteBuf>::deserialize(deserializer)?;
PublicKey::from_bytes(bytes.as_ref()).map_err(SerdeError::custom)
}
}
52 changes: 9 additions & 43 deletions src/secret.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,9 @@ use sha2::Sha512;
#[cfg(feature = "serde")]
use serde::de::Error as SerdeError;
#[cfg(feature = "serde")]
use serde::de::Visitor;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "serde")]
use serde::{Deserializer, Serializer};
use serde_bytes::{Bytes as SerdeBytes, ByteBuf as SerdeByteBuf};

use zeroize::Zeroize;

Expand Down Expand Up @@ -184,7 +182,7 @@ impl Serialize for SecretKey {
where
S: Serializer,
{
serializer.serialize_bytes(self.as_bytes())
SerdeBytes::new(self.as_bytes()).serialize(serializer)
}
}

Expand All @@ -194,23 +192,8 @@ impl<'d> Deserialize<'d> for SecretKey {
where
D: Deserializer<'d>,
{
struct SecretKeyVisitor;

impl<'d> Visitor<'d> for SecretKeyVisitor {
type Value = SecretKey;

fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
formatter.write_str("An ed25519 secret key as 32 bytes, as specified in RFC8032.")
}

fn visit_bytes<E>(self, bytes: &[u8]) -> Result<SecretKey, E>
where
E: SerdeError,
{
SecretKey::from_bytes(bytes).or(Err(SerdeError::invalid_length(bytes.len(), &self)))
}
}
deserializer.deserialize_bytes(SecretKeyVisitor)
let bytes = <SerdeByteBuf>::deserialize(deserializer)?;
SecretKey::from_bytes(bytes.as_ref()).map_err(SerdeError::custom)
}
}

Expand Down Expand Up @@ -521,7 +504,8 @@ impl Serialize for ExpandedSecretKey {
where
S: Serializer,
{
serializer.serialize_bytes(&self.to_bytes()[..])
let bytes = &self.to_bytes()[..];
SerdeBytes::new(bytes).serialize(serializer)
}
}

Expand All @@ -531,26 +515,8 @@ impl<'d> Deserialize<'d> for ExpandedSecretKey {
where
D: Deserializer<'d>,
{
struct ExpandedSecretKeyVisitor;

impl<'d> Visitor<'d> for ExpandedSecretKeyVisitor {
type Value = ExpandedSecretKey;

fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
formatter.write_str(
"An ed25519 expanded secret key as 64 bytes, as specified in RFC8032.",
)
}

fn visit_bytes<E>(self, bytes: &[u8]) -> Result<ExpandedSecretKey, E>
where
E: SerdeError,
{
ExpandedSecretKey::from_bytes(bytes)
.or(Err(SerdeError::invalid_length(bytes.len(), &self)))
}
}
deserializer.deserialize_bytes(ExpandedSecretKeyVisitor)
let bytes = <SerdeByteBuf>::deserialize(deserializer)?;
ExpandedSecretKey::from_bytes(bytes.as_ref()).map_err(SerdeError::custom)
}
}

Expand Down
Loading

0 comments on commit 97c22f2

Please sign in to comment.