pub mod authenticated;
pub mod unauthenticated;
use std::{borrow::Borrow, sync::Arc};
pub use authenticated::*;
use itertools::{enumerate, izip};
use serde::{de::DeserializeOwned, Serialize};
use wincode::{SchemaRead, SchemaWrite};
use crate::{
algebra::ops::transpose::transpose,
errors::PrimitiveError,
types::PeerIndex,
utils::TakeExact,
};
pub trait Reconstructible: Sized {
type Value: Serialize
+ DeserializeOwned
+ for<'de> SchemaRead<'de, Dst = Self::Value>
+ SchemaWrite<Src = Self::Value>
+ Clone
+ PartialEq
+ Send
+ Sync
+ 'static;
type Opening: Serialize
+ DeserializeOwned
+ for<'de> SchemaRead<'de, Dst = Self::Opening>
+ SchemaWrite<Src = Self::Opening>
+ Clone
+ Send
+ Sync
+ 'static;
fn open_to(&self, peer_index: PeerIndex) -> Result<Self::Opening, PrimitiveError>;
fn open_to_all_others(&self) -> impl ExactSizeIterator<Item = Self::Opening>;
fn reconstruct(&self, openings: Vec<Self::Opening>) -> Result<Self::Value, PrimitiveError>;
fn reconstruct_all<T: Borrow<Self>>(shares: Vec<T>) -> Result<Self::Value, PrimitiveError> {
let n_parties = shares.len();
if n_parties < 2 {
return Err(PrimitiveError::MinimumLength(2, n_parties));
}
let mut all_openings = shares
.iter()
.map(|share| share.borrow().open_to_all_others())
.collect::<Vec<_>>();
enumerate(shares.iter())
.map(|(i, share)| {
let my_openings = enumerate(all_openings.iter_mut())
.take_exact(n_parties)
.filter(|(j, _)| i != *j)
.map(|(_, opening)| opening.next())
.collect::<Option<Vec<_>>>()
.ok_or_else(|| PrimitiveError::InvalidPeerIndex(i, shares.len() - 1))?;
share.borrow().reconstruct(my_openings)
})
.reduce(|previous, current| match (previous, current) {
(Ok(prev), Ok(curr)) => match prev == curr {
true => Ok(prev),
false => Err(PrimitiveError::WrongOpening(
serde_json::to_string(&prev).unwrap(),
serde_json::to_string(&curr).unwrap(),
)),
},
(Err(e), _) | (_, Err(e)) => Err(e),
})
.unwrap() }
}
impl<T: Reconstructible<Opening: Clone>> Reconstructible for Vec<T> {
type Opening = Vec<T::Opening>;
type Value = Vec<T::Value>;
fn open_to(&self, peer_index: PeerIndex) -> Result<Self::Opening, PrimitiveError> {
self.iter().map(|share| share.open_to(peer_index)).collect()
}
fn open_to_all_others(&self) -> impl ExactSizeIterator<Item = Self::Opening> {
let all_openings: Vec<Vec<_>> = self
.iter()
.map(|share| share.open_to_all_others().collect())
.collect();
transpose(all_openings).into_iter()
}
fn reconstruct(&self, openings: Vec<Self::Opening>) -> Result<Self::Value, PrimitiveError> {
if openings.is_empty() {
return Err(PrimitiveError::MinimumLength(1, 0));
}
if openings[0].len() != self.len() {
return Err(PrimitiveError::InvalidParameters(
"Number of openings must match number of shares.".to_string(),
));
}
let mut reconstructed = Vec::with_capacity(self.len());
for (i, share) in self.iter().enumerate() {
let my_openings: Vec<_> = openings
.iter()
.map(|opening| opening.get(i).cloned())
.collect::<Option<Vec<_>>>()
.ok_or_else(|| {
PrimitiveError::InvalidParameters(
"Opening is missing for some share.".to_string(),
)
})?;
reconstructed.push(share.reconstruct(my_openings)?);
}
Ok(reconstructed)
}
}
impl<T: Reconstructible<Opening: Clone>> Reconstructible for Arc<[T]> {
type Opening = Arc<[T::Opening]>;
type Value = Arc<[T::Value]>;
fn open_to(&self, peer_index: PeerIndex) -> Result<Self::Opening, PrimitiveError> {
self.iter().map(|share| share.open_to(peer_index)).collect()
}
fn open_to_all_others(&self) -> impl ExactSizeIterator<Item = Self::Opening> {
let all_openings: Vec<Vec<_>> = self
.iter()
.map(|share| share.open_to_all_others().collect())
.collect();
transpose(all_openings)
.into_iter()
.map(Arc::from)
.collect::<Vec<_>>()
.into_iter()
}
fn reconstruct(&self, openings: Vec<Self::Opening>) -> Result<Self::Value, PrimitiveError> {
if openings.is_empty() {
return Err(PrimitiveError::MinimumLength(1, 0));
}
if openings[0].len() != self.len() {
return Err(PrimitiveError::InvalidParameters(
"Number of openings must match number of shares.".to_string(),
));
}
let mut reconstructed = Vec::with_capacity(self.len());
for (i, share) in self.iter().enumerate() {
let my_openings: Vec<_> = openings
.iter()
.map(|opening| opening.get(i).cloned())
.collect::<Option<Vec<_>>>()
.ok_or_else(|| {
PrimitiveError::InvalidParameters(
"Opening is missing for some share.".to_string(),
)
})?;
reconstructed.push(share.reconstruct(my_openings)?);
}
Ok(reconstructed.into())
}
}
impl<T: Reconstructible, S: Reconstructible> Reconstructible for (T, S) {
type Opening = (T::Opening, S::Opening);
type Value = (T::Value, S::Value);
fn open_to(&self, peer_index: PeerIndex) -> Result<Self::Opening, PrimitiveError> {
Ok((self.0.open_to(peer_index)?, self.1.open_to(peer_index)?))
}
fn open_to_all_others(&self) -> impl ExactSizeIterator<Item = Self::Opening> {
let all_openings_t: Vec<_> = self.0.open_to_all_others().collect();
let all_openings_s: Vec<_> = self.1.open_to_all_others().collect();
izip!(all_openings_t, all_openings_s).map(|(o1, o2)| (o1, o2))
}
fn reconstruct(&self, openings: Vec<Self::Opening>) -> Result<Self::Value, PrimitiveError> {
let (openings_t, openings_s): (Vec<_>, Vec<_>) = openings.into_iter().unzip();
Ok((
self.0.reconstruct(openings_t)?,
self.1.reconstruct(openings_s)?,
))
}
}
pub trait PlaintextOps: Reconstructible + Clone {
fn add_plaintext(self, ptx: &Self::Value, is_first_peer: bool) -> Self;
fn sub_plaintext(self, ptx: &Self::Value, is_first_peer: bool) -> Self;
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
algebra::elliptic_curve::Curve25519Ristretto,
random::Random,
sharing::ScalarShares,
};
#[test]
fn test_reconstruct_vec() {
let n_parties = 3;
let mut rng = crate::random::test_rng();
let scalar_shares: Vec<_> =
ScalarShares::<Curve25519Ristretto, typenum::U5>::random_n(&mut rng, n_parties);
let scalar_shares = scalar_shares
.into_iter()
.map(|s| s.into_iter().collect::<Vec<_>>())
.collect::<Vec<_>>();
let reconstructed =
Vec::<ScalarShare<Curve25519Ristretto>>::reconstruct_all(scalar_shares.clone())
.unwrap();
let expected = (0..5)
.map(|i| {
ScalarShare::<Curve25519Ristretto>::reconstruct_all(
scalar_shares.iter().map(|v| v[i].clone()).collect(),
)
.unwrap()
})
.collect::<Vec<_>>();
assert_eq!(reconstructed, expected);
}
#[test]
fn test_reconstruct_tuple() {
let n_parties = 3;
let mut rng = crate::random::test_rng();
let scalar_shares: Vec<_> =
ScalarShare::<Curve25519Ristretto>::random_n(&mut rng, n_parties);
let base_field_shares: Vec<_> =
BaseFieldShare::<Curve25519Ristretto>::random_n(&mut rng, n_parties);
let shares: Vec<(
ScalarShare<Curve25519Ristretto>,
BaseFieldShare<Curve25519Ristretto>,
)> = izip!(&scalar_shares, &base_field_shares)
.map(|(s, b)| (s.clone(), b.clone()))
.collect();
let reconstructed = <(
ScalarShare<Curve25519Ristretto>,
BaseFieldShare<Curve25519Ristretto>,
)>::reconstruct_all(shares)
.unwrap();
assert_eq!(
reconstructed.0,
ScalarShare::<Curve25519Ristretto>::reconstruct_all(scalar_shares).unwrap()
);
assert_eq!(
reconstructed.1,
BaseFieldShare::<Curve25519Ristretto>::reconstruct_all(base_field_shares).unwrap()
);
}
}