Skip to content
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

Serde implementation #73

Merged
merged 6 commits into from
Jun 11, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
27 changes: 27 additions & 0 deletions Cargo.lock

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

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,12 @@ 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 }
serde_ = { version = "1", package = "serde", optional = true, default-features = false }
serde-big-array = { version = "0.4", optional = true }
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 +41,7 @@ rand_chacha = "0.3"
default = ["rand"]
alloc = []
rand = ["rand_core/std"]
serde = ["serde_", "serde-big-array"]

[package.metadata.docs.rs]
all-features = true
Expand Down
78 changes: 78 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 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,78 @@ 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)?;

Ok(Self(match value {
Some(value) => CtOption::new(value, Choice::from(1)),
None => CtOption::new(T::default(), Choice::from(0)),
}))
daxpedda marked this conversation as resolved.
Show resolved Hide resolved
daxpedda marked this conversation as resolved.
Show resolved Hide resolved
}
}

#[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(test)]
mod tests {
use crate::{Checked, U64};
use subtle::{Choice, ConstantTimeEq, CtOption};

#[test]
#[cfg(feature = "serde")]
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]
#[cfg(feature = "serde")]
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)));
}
}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,9 @@
#[cfg(all(feature = "alloc", test))]
extern crate alloc;

#[cfg(feature = "serde")]
extern crate serde_ as serde;

#[macro_use]
mod nlimbs;

Expand Down
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 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 {}
80 changes: 80 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 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,77 @@ 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(test)]
mod tests {
use crate::{NonZero, U64};
#[cfg(feature = "serde")]
use bincode::ErrorKind;

#[test]
#[cfg(feature = "serde")]
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]
#[cfg(feature = "serde")]
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"
));
}
}
52 changes: 52 additions & 0 deletions src/uint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ use crate::{Concat, Encoding, Integer, Limb, Split, Zero};
use core::fmt;
use subtle::{Choice, ConditionallySelectable};

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

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

Expand Down Expand Up @@ -166,6 +172,30 @@ 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> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(Self {
limbs: BigArray::deserialize(deserializer)?,
})
}
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de, const LIMBS: usize> Serialize for UInt<LIMBS> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
BigArray::serialize(&self.limbs, 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 +305,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);
}
}
Loading