Skip to content

Serde implementation #73

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/crypto-bigint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,9 @@ jobs:
- run: cargo build --target ${{ matrix.target }} --release --no-default-features --features generic-array
- run: cargo build --target ${{ matrix.target }} --release --no-default-features --features rand_core
- run: cargo build --target ${{ matrix.target }} --release --no-default-features --features rlp
- run: cargo build --target ${{ matrix.target }} --release --no-default-features --features serde
- run: cargo build --target ${{ matrix.target }} --release --no-default-features --features zeroize
- run: cargo build --target ${{ matrix.target }} --release --no-default-features --features alloc,der,generic-array,rand_core,rlp,zeroize
- run: cargo build --target ${{ matrix.target }} --release --no-default-features --features alloc,der,generic-array,rand_core,rlp,serde,zeroize

test:
runs-on: ubuntu-latest
Expand Down
33 changes: 33 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,11 @@ der = { version = "=0.6.0-pre.3", optional = true, default-features = false }
generic-array = { version = "0.14", optional = true }
rand_core = { version = "0.6", optional = true }
rlp = { version = "0.5", optional = true, default-features = false }
serdect = { version = "0.1", optional = true, default-features = false }
zeroize = { version = "1", optional = true, default-features = false }

[dev-dependencies]
bincode = "1"
hex-literal = "0.3"
num-bigint = "0.4"
num-traits = "0.2"
Expand All @@ -38,6 +40,7 @@ rand_chacha = "0.3"
default = ["rand"]
alloc = []
rand = ["rand_core/std"]
serde = ["serdect"]

[package.metadata.docs.rs]
all-features = true
Expand Down
73 changes: 73 additions & 0 deletions src/checked.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};

#[cfg(feature = "serde")]
use serdect::serde::{Deserialize, Deserializer, Serialize, Serializer};

/// Provides intentionally-checked arithmetic on `T`.
///
/// Internally this leverages the [`CtOption`] type from the [`subtle`] crate
Expand Down Expand Up @@ -56,3 +59,73 @@ impl<T> From<Checked<T>> for Option<T> {
checked.0.into()
}
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de, T: Default + Deserialize<'de>> Deserialize<'de> for Checked<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<T>::deserialize(deserializer)?;
let choice = Choice::from(value.is_some() as u8);
Ok(Self(CtOption::new(value.unwrap_or_default(), choice)))
}
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de, T: Copy + Serialize> Serialize for Checked<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
Option::<T>::from(self.0).serialize(serializer)
}
}

#[cfg(all(test, feature = "serde"))]
mod tests {
use crate::{Checked, U64};
use subtle::{Choice, ConstantTimeEq, CtOption};

#[test]
fn serde() {
let test = Checked::new(U64::from_u64(0x0011223344556677));

let serialized = bincode::serialize(&test).unwrap();
let deserialized: Checked<U64> = bincode::deserialize(&serialized).unwrap();

assert!(bool::from(test.ct_eq(&deserialized)));

let test = Checked::new(U64::ZERO) - Checked::new(U64::ONE);
assert!(bool::from(
test.ct_eq(&Checked(CtOption::new(U64::ZERO, Choice::from(0))))
));

let serialized = bincode::serialize(&test).unwrap();
let deserialized: Checked<U64> = bincode::deserialize(&serialized).unwrap();

assert!(bool::from(test.ct_eq(&deserialized)));
}

#[test]
fn serde_owned() {
let test = Checked::new(U64::from_u64(0x0011223344556677));

let serialized = bincode::serialize(&test).unwrap();
let deserialized: Checked<U64> = bincode::deserialize_from(serialized.as_slice()).unwrap();

assert!(bool::from(test.ct_eq(&deserialized)));

let test = Checked::new(U64::ZERO) - Checked::new(U64::ONE);
assert!(bool::from(
test.ct_eq(&Checked(CtOption::new(U64::ZERO, Choice::from(0))))
));

let serialized = bincode::serialize(&test).unwrap();
let deserialized: Checked<U64> = bincode::deserialize_from(serialized.as_slice()).unwrap();

assert!(bool::from(test.ct_eq(&deserialized)));
}
}
25 changes: 25 additions & 0 deletions src/limb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ use crate::Zero;
use core::fmt;
use subtle::{Choice, ConditionallySelectable};

#[cfg(feature = "serde")]
use serdect::serde::{Deserialize, Deserializer, Serialize, Serializer};

#[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
compile_error!("this crate builds on 32-bit and 64-bit platforms only");

Expand Down Expand Up @@ -143,6 +146,28 @@ impl fmt::UpperHex for Limb {
}
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de> Deserialize<'de> for Limb {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(Self(LimbUInt::deserialize(deserializer)?))
}
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de> Serialize for Limb {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.0.serialize(serializer)
}
}

#[cfg(feature = "zeroize")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
impl zeroize::DefaultIsZeroes for Limb {}
77 changes: 77 additions & 0 deletions src/non_zero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ use {
rand_core::{CryptoRng, RngCore},
};

#[cfg(feature = "serde")]
use serdect::serde::{
de::{Error, Unexpected},
Deserialize, Deserializer, Serialize, Serializer,
};

/// Wrapper type for non-zero integers.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
pub struct NonZero<T: Zero>(T);
Expand Down Expand Up @@ -306,3 +312,74 @@ impl<const LIMBS: usize> From<NonZeroU128> for NonZero<UInt<LIMBS>> {
Self::from_u128(integer)
}
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de, T: Deserialize<'de> + Zero> Deserialize<'de> for NonZero<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value: T = T::deserialize(deserializer)?;

if bool::from(value.is_zero()) {
Err(D::Error::invalid_value(
Unexpected::Other("zero"),
&"a non-zero value",
))
} else {
Ok(Self(value))
}
}
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de, T: Serialize + Zero> Serialize for NonZero<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.0.serialize(serializer)
}
}

#[cfg(all(test, feature = "serde"))]
mod tests {
use crate::{NonZero, U64};
use bincode::ErrorKind;

#[test]
fn serde() {
let test =
Option::<NonZero<U64>>::from(NonZero::new(U64::from_u64(0x0011223344556677))).unwrap();

let serialized = bincode::serialize(&test).unwrap();
let deserialized: NonZero<U64> = bincode::deserialize(&serialized).unwrap();

assert_eq!(test, deserialized);

let serialized = bincode::serialize(&U64::ZERO).unwrap();
assert!(matches!(
*bincode::deserialize::<NonZero<U64>>(&serialized).unwrap_err(),
ErrorKind::Custom(message) if message == "invalid value: zero, expected a non-zero value"
));
}

#[test]
fn serde_owned() {
let test =
Option::<NonZero<U64>>::from(NonZero::new(U64::from_u64(0x0011223344556677))).unwrap();

let serialized = bincode::serialize(&test).unwrap();
let deserialized: NonZero<U64> = bincode::deserialize_from(serialized.as_slice()).unwrap();

assert_eq!(test, deserialized);

let serialized = bincode::serialize(&U64::ZERO).unwrap();
assert!(matches!(
*bincode::deserialize_from::<_, NonZero<U64>>(serialized.as_slice()).unwrap_err(),
ErrorKind::Custom(message) if message == "invalid value: zero, expected a non-zero value"
));
}
}
56 changes: 56 additions & 0 deletions src/uint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ use crate::{Concat, Encoding, Integer, Limb, Split, Zero};
use core::fmt;
use subtle::{Choice, ConditionallySelectable};

#[cfg(feature = "serde")]
use serdect::serde::{Deserialize, Deserializer, Serialize, Serializer};

#[cfg(feature = "zeroize")]
use zeroize::DefaultIsZeroes;

Expand Down Expand Up @@ -166,6 +169,37 @@ impl<const LIMBS: usize> fmt::UpperHex for UInt<LIMBS> {
}
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de, const LIMBS: usize> Deserialize<'de> for UInt<LIMBS>
where
UInt<LIMBS>: Encoding,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let mut buffer = Self::ZERO.to_le_bytes();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Couldn't come up with a cleaner way.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it's kind of tough. I think GenericArray::default() would work if you use Self::from_le_byte_array and the ArrayEncoding trait.

Otherwise there's UInt::<Limbs>::Repr::default() but unfortunately those impls only go up to 32-bytes, so not only would you need a Default bound to use them but also it would limit the serializable size to U256 unnecessarily.

serdect::array::deserialize_hex_or_bin(buffer.as_mut(), deserializer)?;

Ok(Self::from_le_bytes(buffer))
}
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de, const LIMBS: usize> Serialize for UInt<LIMBS>
where
UInt<LIMBS>: Encoding,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serdect::array::serialize_hex_lower_or_bin(&Encoding::to_le_bytes(self), serializer)
}
}

#[cfg(feature = "zeroize")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
impl<const LIMBS: usize> DefaultIsZeroes for UInt<LIMBS> {}
Expand Down Expand Up @@ -275,4 +309,26 @@ mod tests {
assert_eq!(hi, U64::from_u64(0x0011223344556677));
assert_eq!(lo, U64::from_u64(0x8899aabbccddeeff));
}

#[test]
#[cfg(feature = "serde")]
fn serde() {
const TEST: U64 = U64::from_u64(0x0011223344556677);

let serialized = bincode::serialize(&TEST).unwrap();
let deserialized: U64 = bincode::deserialize(&serialized).unwrap();

assert_eq!(TEST, deserialized);
}

#[test]
#[cfg(feature = "serde")]
fn serde_owned() {
const TEST: U64 = U64::from_u64(0x0011223344556677);

let serialized = bincode::serialize(&TEST).unwrap();
let deserialized: U64 = bincode::deserialize_from(serialized.as_slice()).unwrap();

assert_eq!(TEST, deserialized);
}
}
2 changes: 1 addition & 1 deletion src/uint/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ macro_rules! impl_uint_aliases {
}

fn from_le_bytes(bytes: Self::Repr) -> Self {
Self::from_be_slice(&bytes)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug I found on the way. We need to test Encoding.

Self::from_le_slice(&bytes)
}

#[inline]
Expand Down
Loading