primitives/sharing/
mod.rs

1// Secret sharing schemes.
2pub mod authenticated;
3pub mod unauthenticated;
4
5use std::borrow::Borrow;
6
7pub use authenticated::*;
8use itertools::{enumerate, izip};
9use serde::{de::DeserializeOwned, Serialize};
10
11use crate::{
12    algebra::{field::FieldExtension, ops::transpose::transpose},
13    errors::{PrimitiveError, VerificationError},
14    random::{CryptoRngCore, RandomWith},
15    types::PeerIndex,
16    utils::TakeExact,
17};
18
19// ------------------------- //
20// ---- Reconstructible ---- //
21// ------------------------- //
22/// Reconstructs a secret from a collection of openings and a local share.
23pub trait Reconstructible: Sized {
24    /// The type that is sent to / received from other peers.
25    type Opening: Serialize + Clone + DeserializeOwned + Send + Sync + 'static;
26    /// The type of the reconstructed value.
27    type Secret: Serialize + DeserializeOwned + PartialEq + Send + Sync + 'static;
28
29    /// Open the share towards another peer.
30    fn open_to(&self, peer_index: PeerIndex) -> Result<Self::Opening, PrimitiveError>;
31
32    /// Open the share towards all other peers. Returns an iterator with either one opening for
33    /// each peer or a single opening for all peers.
34    fn open_to_all_others(&self) -> impl ExactSizeIterator<Item = Self::Opening>;
35
36    /// Reconstruct a secret from openings coming from all other parties.
37    fn reconstruct(&self, openings: &[Self::Opening]) -> Result<Self::Secret, PrimitiveError>;
38
39    /// Reconstruct a secret from a collection of shares, by opening each share
40    /// towards all other peers, reconstructing `n` secrets from the openings and
41    /// checking that they are all equal.
42    fn reconstruct_all<T: Borrow<Self>>(shares: &[T]) -> Result<Self::Secret, PrimitiveError> {
43        let n_parties = shares.len();
44        if n_parties < 2 {
45            return Err(PrimitiveError::InvalidParameters(
46                "At least two shares are required for reconstruction.".to_string(),
47            ));
48        }
49        // Open each share to all other peers.
50        let mut all_openings = shares
51            .iter()
52            .map(|share| share.borrow().open_to_all_others())
53            .collect::<Vec<_>>();
54        // Reconstruct each secret.
55        enumerate(shares.iter())
56            .map(|(i, share)| {
57                let my_openings = enumerate(all_openings.iter_mut())
58                    .take_exact(n_parties)
59                    .filter(|(j, _)| i != *j)
60                    .map(|(_, opening)| opening.next())
61                    .collect::<Option<Vec<_>>>()
62                    .ok_or(VerificationError::MissingOpening(i))?;
63                share.borrow().reconstruct(my_openings.as_slice())
64            })
65            // Check that all reconstructed secrets are equal.
66            .reduce(|previous, current| match (previous, current) {
67                (Ok(prev), Ok(curr)) => match prev == curr {
68                    true => Ok(prev),
69                    false => Err(VerificationError::OpeningMismatch(
70                        serde_json::to_string(&prev).unwrap(),
71                        serde_json::to_string(&curr).unwrap(),
72                    )
73                    .into()),
74                },
75                (Err(e), _) | (_, Err(e)) => Err(e),
76            })
77            .unwrap() // Safe because `shares.len() >= 2`
78    }
79}
80
81impl<T: Reconstructible<Opening: Clone>> Reconstructible for Vec<T> {
82    type Opening = Vec<T::Opening>;
83    type Secret = Vec<T::Secret>;
84
85    fn open_to(&self, peer_index: PeerIndex) -> Result<Self::Opening, PrimitiveError> {
86        self.iter().map(|share| share.open_to(peer_index)).collect()
87    }
88
89    fn open_to_all_others(&self) -> impl ExactSizeIterator<Item = Self::Opening> {
90        let all_openings: Vec<Vec<_>> = self
91            .iter()
92            .map(|share| share.open_to_all_others().collect())
93            .collect();
94
95        transpose(all_openings).into_iter()
96    }
97
98    fn reconstruct(&self, openings: &[Self::Opening]) -> Result<Self::Secret, PrimitiveError> {
99        if openings.is_empty() {
100            return Err(PrimitiveError::InvalidParameters(
101                "At least one opening is required for reconstruction.".to_string(),
102            ));
103        }
104
105        if openings[0].len() != self.len() {
106            return Err(PrimitiveError::InvalidParameters(
107                "Number of openings must match number of shares.".to_string(),
108            ));
109        }
110
111        // Iterate over all the i-th elements of each entry of openings
112        let mut reconstructed = Vec::with_capacity(self.len());
113        for (i, share) in self.iter().enumerate() {
114            let my_openings: Vec<_> = openings
115                .iter()
116                .map(|opening| opening.get(i).cloned())
117                .collect::<Option<Vec<_>>>()
118                .ok_or(PrimitiveError::InvalidParameters(
119                    "Opening is missing for some share.".to_string(),
120                ))?;
121            reconstructed.push(share.reconstruct(my_openings.as_slice())?);
122        }
123        Ok(reconstructed)
124    }
125}
126
127impl<T: Reconstructible, S: Reconstructible> Reconstructible for (T, S) {
128    type Opening = (T::Opening, S::Opening);
129    type Secret = (T::Secret, S::Secret);
130
131    fn open_to(&self, peer_index: PeerIndex) -> Result<Self::Opening, PrimitiveError> {
132        Ok((self.0.open_to(peer_index)?, self.1.open_to(peer_index)?))
133    }
134
135    fn open_to_all_others(&self) -> impl ExactSizeIterator<Item = Self::Opening> {
136        let all_openings_t: Vec<_> = self.0.open_to_all_others().collect();
137        let all_openings_s: Vec<_> = self.1.open_to_all_others().collect();
138        izip!(all_openings_t, all_openings_s).map(|(o1, o2)| (o1, o2))
139    }
140
141    fn reconstruct(&self, openings: &[Self::Opening]) -> Result<Self::Secret, PrimitiveError> {
142        let (openings_t, openings_s): (Vec<_>, Vec<_>) = openings.iter().cloned().unzip();
143        Ok((
144            self.0.reconstruct(&openings_t)?,
145            self.1.reconstruct(&openings_s)?,
146        ))
147    }
148}
149
150// ---------------------------- //
151// ---- Random for N Peers ---- //
152// ---------------------------- //
153pub trait RandomAuthenticatedForNPeers<F: FieldExtension>:
154    RandomWith<Vec<Vec<GlobalFieldKey<F>>>>
155{
156    fn random_for_n_peers_with_alphas<Container: FromIterator<Self>>(
157        mut rng: impl CryptoRngCore,
158        n_parties: usize,
159        all_alphas: Vec<Vec<GlobalFieldKey<F>>>,
160    ) -> Container {
161        Self::random_n_with(&mut rng, n_parties, all_alphas)
162    }
163}
164
165impl<F: FieldExtension, S: RandomWith<Vec<Vec<GlobalFieldKey<F>>>>> RandomAuthenticatedForNPeers<F>
166    for S
167{
168}
169
170pub trait RandomAuthenticatedForNPeersWith<F: FieldExtension, T: Clone>:
171    RandomWith<(T, Vec<Vec<GlobalFieldKey<F>>>)>
172{
173    fn random_authenticated_for_n_peers_with<Container: FromIterator<Self>>(
174        mut rng: impl CryptoRngCore,
175        n_parties: usize,
176        value: T,
177        all_alphas: Vec<Vec<GlobalFieldKey<F>>>,
178    ) -> Container {
179        Self::random_n_with(&mut rng, n_parties, (value, all_alphas))
180    }
181}
182
183impl<F: FieldExtension, T: Clone, S: RandomWith<(T, Vec<Vec<GlobalFieldKey<F>>>)>>
184    RandomAuthenticatedForNPeersWith<F, T> for S
185{
186}
187
188/// A trait used to add a plaintext secret to its secret-shared (reconstructible) form.
189pub trait AddPlaintext: Reconstructible {
190    /// Helper information to be used when adding a constant to the share. For example in BDOZ
191    /// shares, you need to know whether the local peer is the first peer or not.
192    type AssociatedInformation: Clone + Send + Sync;
193    /// Add a constant to the share.
194    fn add_plaintext(&self, plaintext: &Self::Secret, assoc: Self::AssociatedInformation) -> Self;
195
196    /// Add a constant to the share, consuming the share and returning a new one.
197    fn add_plaintext_owned(
198        self,
199        plaintext: &Self::Secret,
200        assoc: Self::AssociatedInformation,
201    ) -> Self {
202        self.add_plaintext(plaintext, assoc)
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209    use crate::{algebra::elliptic_curve::Curve25519Ristretto, random::Random};
210
211    #[test]
212    fn test_transpose_empty_matrix() {
213        let matrix: Vec<Vec<i32>> = vec![];
214        let result = transpose(matrix.clone());
215        assert_eq!(result, matrix);
216    }
217
218    #[test]
219    fn test_transpose_empty_rows() {
220        let matrix: Vec<Vec<i32>> = vec![];
221        let result = transpose(matrix.clone());
222        assert_eq!(result, matrix);
223    }
224
225    #[test]
226    fn test_transpose_single_element() {
227        let matrix = vec![vec![1]];
228        let result = transpose(matrix);
229        assert_eq!(result, vec![vec![1]]);
230    }
231
232    #[test]
233    fn test_transpose_single_row() {
234        let matrix = vec![vec![1, 2, 3]];
235        let result = transpose(matrix);
236        assert_eq!(result, vec![vec![1], vec![2], vec![3]]);
237    }
238
239    #[test]
240    fn test_transpose_single_column() {
241        let matrix = vec![vec![1], vec![2], vec![3]];
242        let result = transpose(matrix);
243        assert_eq!(result, vec![vec![1, 2, 3]]);
244    }
245
246    #[test]
247    fn test_transpose_square_matrix() {
248        let matrix = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
249        let result = transpose(matrix);
250        let expected = vec![vec![1, 4, 7], vec![2, 5, 8], vec![3, 6, 9]];
251        assert_eq!(result, expected);
252    }
253
254    #[test]
255    fn test_transpose_rectangular_matrix() {
256        let matrix = vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8]];
257        let result = transpose(matrix);
258        let expected = vec![vec![1, 5], vec![2, 6], vec![3, 7], vec![4, 8]];
259        assert_eq!(result, expected);
260    }
261
262    #[test]
263    fn test_transpose_with_strings() {
264        let matrix = vec![vec!["a", "b"], vec!["c", "d"], vec!["e", "f"]];
265        let result = transpose(matrix);
266        let expected = vec![vec!["a", "c", "e"], vec!["b", "d", "f"]];
267        assert_eq!(result, expected);
268    }
269
270    #[test]
271    fn test_transpose_double_transpose() {
272        let matrix = vec![vec![1, 2, 3], vec![4, 5, 6]];
273        let result = transpose(transpose(matrix.clone()));
274        assert_eq!(result, matrix);
275    }
276
277    #[test]
278    fn test_reconstruct_vec() {
279        let n_parties = 3;
280        let mut rng = crate::random::test_rng();
281
282        let scalar_shares: Vec<_> =
283            ScalarShares::<Curve25519Ristretto, typenum::U5>::random_n(&mut rng, n_parties);
284        let scalar_shares = scalar_shares
285            .into_iter()
286            .map(|s| s.into_iter().collect::<Vec<_>>())
287            .collect::<Vec<_>>();
288
289        let reconstructed =
290            Vec::<ScalarShare<Curve25519Ristretto>>::reconstruct_all(&scalar_shares).unwrap();
291        let expected = (0..5)
292            .map(|i| {
293                ScalarShare::<Curve25519Ristretto>::reconstruct_all(
294                    &scalar_shares.iter().map(|v| &v[i]).collect::<Vec<_>>(),
295                )
296                .unwrap()
297            })
298            .collect::<Vec<_>>();
299        assert_eq!(reconstructed, expected);
300    }
301
302    #[test]
303    fn test_reconstruct_tuple() {
304        let n_parties = 3;
305        let mut rng = crate::random::test_rng();
306
307        let scalar_shares: Vec<_> =
308            ScalarShare::<Curve25519Ristretto>::random_n(&mut rng, n_parties);
309        let base_field_shares: Vec<_> =
310            BaseFieldShare::<Curve25519Ristretto>::random_n(&mut rng, n_parties);
311
312        let shares: Vec<(
313            ScalarShare<Curve25519Ristretto>,
314            BaseFieldShare<Curve25519Ristretto>,
315        )> = izip!(&scalar_shares, &base_field_shares)
316            .map(|(s, b)| (s.clone(), b.clone()))
317            .collect();
318
319        let reconstructed = <(
320            ScalarShare<Curve25519Ristretto>,
321            BaseFieldShare<Curve25519Ristretto>,
322        )>::reconstruct_all(&shares)
323        .unwrap();
324
325        assert_eq!(
326            reconstructed.0,
327            ScalarShare::<Curve25519Ristretto>::reconstruct_all(&scalar_shares).unwrap()
328        );
329        assert_eq!(
330            reconstructed.1,
331            BaseFieldShare::<Curve25519Ristretto>::reconstruct_all(&base_field_shares).unwrap()
332        );
333    }
334}