Skip to content

Commit

Permalink
no std changes
Browse files Browse the repository at this point in the history
  • Loading branch information
jowparks committed Aug 8, 2024
1 parent 6362ab4 commit ddfbe11
Show file tree
Hide file tree
Showing 11 changed files with 126 additions and 52 deletions.
16 changes: 8 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,20 @@ repository = "https://github.com/iron-fish/ironfish-frost"
blake3 = { version = "1.5.0", optional = true }
chacha20 = "0.9.1"
chacha20poly1305 = "0.10.1"
ed25519-dalek = { version = "2.1.0", features = ["rand_core"] }
ed25519-dalek = { version = "2.1.0", default-features = false, features = ["rand_core", "alloc"] }
rand_chacha = { version = "0.3.1", optional = true }
rand_core = "0.6.4"
reddsa = { git = "https://github.com/ZcashFoundation/reddsa.git", rev = "b9c3107e6ec5333a89a7fa064f2d10f749a90cce", features = ["frost", "frost-rerandomized"] }
siphasher = { version = "1.0.0", optional = true }
x25519-dalek = { version = "2.0.0", features = ["reusable_secrets", "static_secrets"] }
rand_core = { version = "0.6.4", default-features = false, features = ["alloc"] }
reddsa = { git = "https://github.com/ZcashFoundation/reddsa.git", rev="9ac52c5c60e454b0032d78a22c05fb79aae1d51e", features = ["frost"], default-features = false }
siphasher = { version = "1.0.0", default-features = false }
x25519-dalek = { version = "2.0.0", default-features = false, features = ["reusable_secrets", "static_secrets"] }

[dev-dependencies]
hex-literal = "0.4.1"
rand = "0.8.5"

[features]
default = ["std", "signing"]
default = ["signing"]

std = []
signing = ["dep:blake3", "dep:rand_chacha", "dep:siphasher", "std"]
dkg = ["std", "signing"]
signing = ["dep:blake3", "dep:rand_chacha", "std"]
dkg = []
9 changes: 5 additions & 4 deletions src/checksum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,15 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use std::error;
use std::fmt;
use core::fmt;

use siphasher::sip::SipHasher24;
pub(crate) type ChecksumHasher = SipHasher24;

pub(crate) const CHECKSUM_LEN: usize = 8;

pub(crate) type Checksum = u64;

pub(crate) type ChecksumHasher = SipHasher24;

#[derive(Clone, Debug)]
pub enum ChecksumError {
SigningCommitmentError,
Expand All @@ -33,4 +31,7 @@ impl fmt::Display for ChecksumError {
}
}

#[cfg(feature = "std")]
use std::error;
#[cfg(feature = "std")]
impl error::Error for ChecksumError {}
7 changes: 6 additions & 1 deletion src/dkg/group_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::io;
use crate::multienc;
use crate::participant::Identity;
use crate::participant::Secret;
use rand_core::CryptoRng;
use rand_core::RngCore;
use std::io;

#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

pub const GROUP_SECRET_KEY_LEN: usize = 32;

Expand Down
15 changes: 11 additions & 4 deletions src/dkg/round1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use crate::frost::keys::VerifiableSecretSharingCommitment;
use crate::frost::Field;
use crate::frost::Identifier;
use crate::frost::JubjubScalarField;
use crate::io;
use crate::multienc;
use crate::participant;
use crate::participant::Identity;
Expand All @@ -23,12 +24,18 @@ use crate::serde::read_variable_length_bytes;
use crate::serde::write_u16;
use crate::serde::write_variable_length;
use crate::serde::write_variable_length_bytes;
use core::borrow::Borrow;
use rand_core::CryptoRng;
use rand_core::RngCore;
use std::borrow::Borrow;
use std::hash::Hasher;
use std::io;
use std::mem;

use core::hash::Hasher;
use core::mem;

#[cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

type Scalar = <JubjubScalarField as Field>::Scalar;

Expand Down
18 changes: 14 additions & 4 deletions src/dkg/round2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use crate::frost::keys::VerifiableSecretSharingCommitment;
use crate::frost::Field;
use crate::frost::Identifier;
use crate::frost::JubjubScalarField;
use crate::io;
use crate::multienc;
use crate::participant;
use crate::participant::Identity;
Expand All @@ -25,13 +26,22 @@ use crate::serde::read_variable_length_bytes;
use crate::serde::write_u16;
use crate::serde::write_variable_length;
use crate::serde::write_variable_length_bytes;
use core::borrow::Borrow;
use core::hash::Hasher;
use core::mem;
use rand_core::CryptoRng;
use rand_core::RngCore;
use std::borrow::Borrow;
// use log::info;

#[cfg(feature = "std")]
use std::collections::BTreeMap;
use std::hash::Hasher;
use std::io;
use std::mem;

#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(not(feature = "std"))]
use alloc::collections::BTreeMap;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

type Scalar = <JubjubScalarField as Field>::Scalar;

Expand Down
24 changes: 17 additions & 7 deletions src/dkg/round3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use crate::error::IronfishFrostError;
use crate::frost::keys::dkg::part3;
use crate::frost::keys::KeyPackage;
use crate::frost::keys::PublicKeyPackage as FrostPublicKeyPackage;
use crate::io;
use crate::participant::Identity;
use crate::participant::Secret;
use crate::serde::read_u16;
Expand All @@ -20,10 +21,18 @@ use crate::serde::read_variable_length_bytes;
use crate::serde::write_u16;
use crate::serde::write_variable_length;
use crate::serde::write_variable_length_bytes;
use core::borrow::Borrow;
use reddsa::frost::redjubjub::VerifyingKey;
use std::borrow::Borrow;

#[cfg(feature = "std")]
use std::collections::BTreeMap;
use std::io;

#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(not(feature = "std"))]
use alloc::collections::BTreeMap;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

#[derive(Clone, Eq, PartialEq, Debug)]
pub struct PublicKeyPackage {
Expand Down Expand Up @@ -72,9 +81,11 @@ impl PublicKeyPackage {
bytes
}

#[cfg(feature = "std")]
pub fn serialize_into<W: io::Write>(&self, mut writer: W) -> Result<(), IronfishFrostError> {
let frost_public_key_package = self.frost_public_key_package.serialize()?;
pub fn serialize_into<W: io::Write>(&self, mut writer: W) -> io::Result<()> {
let frost_public_key_package = self
.frost_public_key_package
.serialize()
.map_err(|_| io::Error::other("public key package serialization failed"))?;
write_variable_length_bytes(&mut writer, &frost_public_key_package)?;
write_variable_length(&mut writer, &self.identities, |writer, identity| {
identity.serialize_into(writer)
Expand All @@ -84,7 +95,6 @@ impl PublicKeyPackage {
Ok(())
}

#[cfg(feature = "std")]
pub fn deserialize_from<R: io::Read>(mut reader: R) -> Result<Self, IronfishFrostError> {
let frost_public_key_package = read_variable_length_bytes(&mut reader)?;
let frost_public_key_package =
Expand Down Expand Up @@ -171,7 +181,7 @@ where
// inputs
round1_frost_packages
.remove(&identity.to_frost_identifier())
.ok_or_else(|| IronfishFrostError::InvalidInput)?;
.ok_or(IronfishFrostError::InvalidInput)?;

let expected_round2_checksum =
round2::input_checksum(round1_public_packages.iter().map(Borrow::borrow));
Expand Down
2 changes: 0 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use reddsa::frost::redjubjub::JubjubBlake2b512;

use crate::io;

#[cfg(feature = "signing")]
use crate::checksum::ChecksumError;

#[derive(Debug)]
Expand All @@ -17,7 +16,6 @@ pub enum IronfishFrostError {
IoError(io::Error),
FrostError(FrostError<JubjubBlake2b512>),
SignatureError(ed25519_dalek::SignatureError),
#[cfg(feature = "signing")]
ChecksumError(ChecksumError),
}

Expand Down
31 changes: 29 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

mod serde;

#[cfg(feature = "signing")]
mod checksum;

pub mod error;
Expand Down Expand Up @@ -39,6 +38,11 @@ mod io {
pub(crate) use std::io::Write;
}

#[cfg(not(feature = "std"))]
#[macro_use]
#[cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(not(feature = "std"))]
mod io {
use core::cmp;
Expand All @@ -53,7 +57,7 @@ mod io {
}
}

pub type Result<T> = core::result::Result<T, Error>;
pub(crate) type Result<T> = core::result::Result<T, Error>;

pub trait Read {
fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
Expand All @@ -74,6 +78,13 @@ mod io {
Err(Error)
}
}

fn by_ref(&mut self) -> &mut Self
where
Self: Sized,
{
self
}
}

impl<R: Read> Read for &mut R {
Expand Down Expand Up @@ -137,3 +148,19 @@ mod io {
}
}
}

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

#[cfg(not(feature = "std"))]
impl io::Write for Vec<u8> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.extend_from_slice(buf);
Ok(buf.len())
}

fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.extend_from_slice(buf);
Ok(())
}
}
44 changes: 27 additions & 17 deletions src/multienc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ use rand_core::RngCore;
use x25519_dalek::PublicKey;
use x25519_dalek::ReusableSecret;

#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(not(feature = "std"))]
use crate::alloc::borrow::ToOwned;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

pub const HEADER_SIZE: usize = 56;
pub const KEY_SIZE: usize = 32;

Expand All @@ -29,31 +36,30 @@ pub const fn metadata_size(num_recipients: usize) -> usize {
HEADER_SIZE + KEY_SIZE * num_recipients
}

#[cfg(feature = "std")]
pub fn read_encrypted_blob<R>(mut reader: R) -> io::Result<Vec<u8>>
pub fn read_encrypted_blob<R>(reader: &mut R) -> Result<Vec<u8>, io::Error>
where
R: io::Read,
R: crate::io::Read,
{
use std::io::Read;

let mut result = Vec::new();
let reader = reader.by_ref();

reader.take(HEADER_SIZE as u64).read_to_end(&mut result)?;
let mut header_bytes = [0u8; HEADER_SIZE];
reader.read_exact(&mut header_bytes)?;
let header: Header = Header::deserialize_from(&header_bytes[..])?;

let header = Header::deserialize_from(&result[..])?;
for _ in 0..header.num_recipients {
reader.take(KEY_SIZE as u64).read_to_end(&mut result)?;
let mut key_bytes = vec![0u8; KEY_SIZE];
reader.read_exact(&mut key_bytes)?;
result.extend(key_bytes);
}
reader
.take(header.data_len as u64)
.read_to_end(&mut result)?;

let mut data_bytes = vec![0u8; header.data_len];
reader.read_exact(&mut data_bytes)?;
result.extend(data_bytes);

Ok(result)
}

#[must_use]
#[cfg(feature = "std")]
pub fn encrypt<'a, I, R>(data: &[u8], recipients: I, csrng: R) -> Vec<u8>
where
I: IntoIterator<Item = &'a Identity>,
Expand Down Expand Up @@ -140,15 +146,21 @@ where
///
/// This method expects the ciphertext and the metadata to be concatenated in one slice. Use
/// [`decrypt_in_place`] if you have two separate slices.
#[cfg(feature = "std")]
pub fn decrypt(secret: &Secret, data: &[u8]) -> io::Result<Vec<u8>> {
let header = Header::deserialize_from(data)?;
let metadata_len = metadata_size(header.num_recipients);
let total_len = metadata_len
.checked_add(header.data_len)
.ok_or_else(|| io::Error::other("overflow when calculating data size"))?;
if data.len() < total_len {
return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
#[cfg(feature = "std")]
{
return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
}
#[cfg(not(feature = "std"))]
{
return Err(io::Error);
}
}

let (metadata, ciphertext) = data.split_at(metadata_len);
Expand Down Expand Up @@ -241,7 +253,6 @@ impl Header {
write_usize(&mut writer, self.data_len)
}

#[cfg(feature = "std")]
fn deserialize_from<R: io::Read>(mut reader: R) -> io::Result<Self> {
let mut agreement_key = [0u8; 32];
reader.read_exact(&mut agreement_key)?;
Expand All @@ -265,7 +276,6 @@ impl Header {

#[cfg(test)]
mod tests {
#[cfg(feature = "std")]
mod detached {
use crate::multienc::decrypt;
use crate::multienc::encrypt;
Expand Down
Loading

0 comments on commit ddfbe11

Please sign in to comment.