vsss-rs 6.0.0

Verifiable Secret Sharing Schemes for splitting, combining and verifying secret shares
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use super::*;
use crate::*;
use core::{
    cmp::Ordering,
    fmt::{self, Display, Formatter},
    hash::{Hash, Hasher},
    ops::{Deref, DerefMut, Mul},
};
#[cfg(feature = "bigint")]
use crypto_bigint::{Encoding, modular::ConstMontyParams};
#[cfg(feature = "bigint")]
use elliptic_curve::{
    bigint::{self, ArrayEncoding, modular::ConstMontyParams as ResidueParams},
    ops::Reduce,
};

use elliptic_curve::{Field, PrimeField, scalar::IsHigh};

/// A share value represented as a [`PrimeField`].
pub type ValuePrimeField<F> = IdentifierPrimeField<F>;

/// A share identifier represented as a prime field element.
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct IdentifierPrimeField<F: PrimeField>(
    #[cfg_attr(
        feature = "curve-serde",
        serde(with = "elliptic_curve_tools::prime_field")
    )]
    pub F,
);

impl<F: PrimeField> Display for IdentifierPrimeField<F> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        for &b in self.0.to_repr().as_ref() {
            write!(f, "{:02x}", b)?;
        }
        Ok(())
    }
}

impl<F: PrimeField> Hash for IdentifierPrimeField<F> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.to_repr().as_ref().hash(state);
    }
}

#[allow(clippy::non_canonical_partial_ord_impl)]
impl<F: PrimeField + IsHigh> PartialOrd for IdentifierPrimeField<F> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (self.0.is_high().unwrap_u8(), other.0.is_high().unwrap_u8()) {
            (1, 1) => Some(other.0.to_repr().as_ref().cmp(self.0.to_repr().as_ref())),
            (0, 0) => Some(self.0.to_repr().as_ref().cmp(other.0.to_repr().as_ref())),
            (1, 0) => Some(Ordering::Less),
            (0, 1) => Some(Ordering::Greater),
            (_, _) => None,
        }
    }
}

impl<F: PrimeField + IsHigh> Ord for IdentifierPrimeField<F> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).expect("invalid share identifier")
    }
}

impl<F: PrimeField> Deref for IdentifierPrimeField<F> {
    type Target = F;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<F: PrimeField> DerefMut for IdentifierPrimeField<F> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<F: PrimeField> AsRef<F> for IdentifierPrimeField<F> {
    fn as_ref(&self) -> &F {
        &self.0
    }
}

impl<F: PrimeField> AsMut<F> for IdentifierPrimeField<F> {
    fn as_mut(&mut self) -> &mut F {
        &mut self.0
    }
}

impl<F: PrimeField> From<F> for IdentifierPrimeField<F> {
    fn from(value: F) -> Self {
        Self(value)
    }
}

impl<F: PrimeField> From<&IdentifierPrimeField<F>> for IdentifierPrimeField<F> {
    fn from(value: &IdentifierPrimeField<F>) -> Self {
        *value
    }
}

#[cfg(feature = "primitive")]
impl<F: PrimeField, P: Primitive<BYTES>, const BYTES: usize> From<&IdentifierPrimitive<P, BYTES>>
    for IdentifierPrimeField<F>
{
    fn from(value: &IdentifierPrimitive<P, BYTES>) -> Self {
        #[cfg(target_pointer_width = "64")]
        {
            if BYTES * 8 <= 64 {
                Self(F::from(value.0.to_u64().expect("invalid share identifier")))
            } else {
                Self(F::from_u128(
                    value.0.to_u128().expect("invalid share identifier"),
                ))
            }
        }
        #[cfg(target_pointer_width = "32")]
        {
            Self(F::from(value.0.to_u64().expect("invalid share identifier")))
        }
    }
}

#[cfg(feature = "bigint")]
impl<F: PrimeField + Reduce<bigint::Uint<LIMBS>>, MOD: ResidueParams<LIMBS>, const LIMBS: usize>
    From<&IdentifierResidue<MOD, LIMBS>> for IdentifierPrimeField<F>
where
    bigint::Uint<LIMBS>: ArrayEncoding,
{
    fn from(value: &IdentifierResidue<MOD, LIMBS>) -> Self {
        let t = value.0.retrieve();
        Self(F::reduce(&t))
    }
}

impl<F: PrimeField> Mul<&IdentifierPrimeField<F>> for IdentifierPrimeField<F> {
    type Output = IdentifierPrimeField<F>;

    fn mul(self, rhs: &IdentifierPrimeField<F>) -> Self::Output {
        Self(self.0 * rhs.0)
    }
}

#[cfg(feature = "primitive")]
impl<F: PrimeField, P: Primitive<BYTES>, const BYTES: usize> Mul<&IdentifierPrimitive<P, BYTES>>
    for IdentifierPrimeField<F>
{
    type Output = IdentifierPrimeField<F>;

    fn mul(self, rhs: &IdentifierPrimitive<P, BYTES>) -> Self::Output {
        let rhs = IdentifierPrimeField::<F>::from(rhs);
        Self(self.0 * rhs.0)
    }
}

#[cfg(feature = "bigint")]
impl<F: PrimeField + Reduce<bigint::Uint<LIMBS>>, MOD: ResidueParams<LIMBS>, const LIMBS: usize>
    Mul<&IdentifierResidue<MOD, LIMBS>> for IdentifierPrimeField<F>
where
    bigint::Uint<LIMBS>: ArrayEncoding,
{
    type Output = IdentifierPrimeField<F>;

    fn mul(self, rhs: &IdentifierResidue<MOD, LIMBS>) -> Self::Output {
        let rhs = IdentifierPrimeField::<F>::from(rhs);
        Self(self.0 * rhs.0)
    }
}

#[cfg(feature = "bigint")]
impl<F: PrimeField + Reduce<bigint::Uint<LIMBS>>, const LIMBS: usize>
    From<&uint::IdentifierUint<LIMBS>> for IdentifierPrimeField<F>
where
    crypto_bigint::Uint<LIMBS>: Encoding,
{
    fn from(value: &uint::IdentifierUint<LIMBS>) -> Self {
        if LIMBS * 8 != F::Repr::default().as_ref().len() {
            panic!(
                "cannot convert from IdentifierUint to IdentifierPrimeField with different limb size"
            );
        }
        Self(F::reduce(&bigint::Uint::from_words(value.0.to_words())))
    }
}

#[cfg(feature = "bigint")]
impl<F: PrimeField + Reduce<bigint::Uint<LIMBS>>, const LIMBS: usize>
    Mul<&uint::IdentifierUint<LIMBS>> for IdentifierPrimeField<F>
where
    crypto_bigint::Uint<LIMBS>: Encoding,
{
    type Output = IdentifierPrimeField<F>;

    fn mul(self, rhs: &uint::IdentifierUint<LIMBS>) -> Self::Output {
        let rhs = IdentifierPrimeField::<F>::from(rhs);
        Self(self.0 * rhs.0)
    }
}

#[cfg(feature = "bigint")]
impl<F: PrimeField + Reduce<bigint::Uint<LIMBS>>, MOD: ConstMontyParams<LIMBS>, const LIMBS: usize>
    From<&IdentifierConstMontyResidue<MOD, LIMBS>> for IdentifierPrimeField<F>
where
    crypto_bigint::Uint<LIMBS>: Encoding,
{
    fn from(value: &IdentifierConstMontyResidue<MOD, LIMBS>) -> Self {
        let t = value.0.retrieve();
        Self(F::reduce(&bigint::Uint::from_words(t.to_words())))
    }
}

#[cfg(feature = "bigint")]
impl<F: PrimeField + Reduce<bigint::Uint<LIMBS>>, MOD: ConstMontyParams<LIMBS>, const LIMBS: usize>
    Mul<&IdentifierConstMontyResidue<MOD, LIMBS>> for IdentifierPrimeField<F>
where
    crypto_bigint::Uint<LIMBS>: Encoding,
{
    type Output = IdentifierPrimeField<F>;

    fn mul(self, rhs: &IdentifierConstMontyResidue<MOD, LIMBS>) -> Self::Output {
        let rhs = IdentifierPrimeField::<F>::from(rhs);
        Self(self.0 * rhs.0)
    }
}

#[cfg(feature = "zeroize")]
impl<F: PrimeField + zeroize::DefaultIsZeroes> zeroize::DefaultIsZeroes
    for IdentifierPrimeField<F>
{
}

impl<F: PrimeField> ShareElement for IdentifierPrimeField<F> {
    type Serialization = F::Repr;
    type Inner = F;

    fn random(mut rng: impl CryptoRng) -> Self {
        Self(F::random(&mut rng))
    }

    fn zero() -> Self {
        Self(<F as Field>::ZERO)
    }

    fn one() -> Self {
        Self(<F as Field>::ONE)
    }

    fn is_zero(&self) -> Choice {
        F::is_zero(self)
    }

    fn serialize(&self) -> Self::Serialization {
        self.to_repr()
    }

    fn deserialize(serialized: &Self::Serialization) -> VsssResult<Self> {
        Option::from(F::from_repr(*serialized).map(Self)).ok_or(Error::InvalidShareElement)
    }

    fn from_slice(vec: &[u8]) -> VsssResult<Self> {
        let mut repr = F::Repr::default();
        if vec.len() != repr.as_ref().len() {
            return Err(Error::InvalidShareElement);
        }
        repr.as_mut().copy_from_slice(vec);
        Option::from(F::from_repr(repr))
            .map(Self)
            .ok_or(Error::InvalidShareElement)
    }

    #[cfg(any(feature = "alloc", feature = "std"))]
    fn to_vec(&self) -> Vec<u8> {
        self.to_repr().as_ref().to_vec()
    }
}

impl<F: PrimeField> ShareIdentifier for IdentifierPrimeField<F> {
    fn inc(&mut self, increment: &Self) {
        self.0 += increment.0;
    }

    fn invert(&self) -> VsssResult<Self> {
        Option::from(self.0.invert())
            .map(Self)
            .ok_or(Error::InvalidShareElement)
    }
}

impl<F: PrimeField> IdentifierPrimeField<F> {
    /// Returns additive identity.
    pub const ZERO: Self = Self(F::ZERO);
    /// Returns multiplicative identity.
    pub const ONE: Self = Self(F::ONE);
}

#[cfg(test)]
mod tests {
    use super::IdentifierPrimeField;
    use crate::{
        Error, IdentifierConstMontyResidue, IdentifierPrimitive, IdentifierResidue, ShareElement,
        ShareIdentifier,
    };
    use core::hash::{Hash, Hasher};
    use crypto_bigint::{U256 as CryptoU256, const_monty_params};
    use elliptic_curve::bigint::{U256 as EcU256, const_monty_params as ec_const_monty_params};
    use k256::Scalar;
    use std::{collections::hash_map::DefaultHasher, string::ToString};

    ec_const_monty_params!(
        EcResidueMod,
        EcU256,
        "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"
    );
    const_monty_params!(
        CryptoResidueMod,
        CryptoU256,
        "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"
    );

    #[test]
    fn prime_field_share_element_methods_round_trip() {
        let identifier = IdentifierPrimeField(Scalar::from(11u64));
        let serialized = identifier.serialize();
        let serialized_bytes: &[u8] = serialized.as_ref();

        assert_eq!(identifier.to_string(), hex::encode(serialized_bytes));
        assert_eq!(
            IdentifierPrimeField::<Scalar>::deserialize(&serialized),
            Ok(identifier)
        );
        assert_eq!(
            IdentifierPrimeField::<Scalar>::from_slice(serialized_bytes),
            Ok(identifier)
        );
        assert_eq!(identifier.to_vec(), serialized_bytes);
        assert_eq!(
            IdentifierPrimeField::<Scalar>::from_slice(&[1, 2]),
            Err(Error::InvalidShareElement)
        );
        assert_eq!(
            IdentifierPrimeField::<Scalar>::ZERO,
            IdentifierPrimeField::zero()
        );
        assert_eq!(
            IdentifierPrimeField::<Scalar>::ONE,
            IdentifierPrimeField::one()
        );
        assert_eq!(
            IdentifierPrimeField::<Scalar>::zero().is_zero().unwrap_u8(),
            1
        );
        assert_eq!(
            IdentifierPrimeField::<Scalar>::one().is_zero().unwrap_u8(),
            0
        );
    }

    #[test]
    fn prime_field_reference_access_hash_order_and_arithmetic_work() {
        let mut identifier = IdentifierPrimeField(Scalar::from(2u64));
        assert_eq!(*identifier, Scalar::from(2u64));
        assert_eq!(*identifier.as_ref(), Scalar::from(2u64));
        *identifier.as_mut() = Scalar::from(3u64);
        assert_eq!(identifier.0, Scalar::from(3u64));

        let from_ref = IdentifierPrimeField::from(&identifier);
        assert_eq!(from_ref, identifier);
        assert_eq!(
            identifier * &IdentifierPrimeField(Scalar::from(4u64)),
            IdentifierPrimeField(Scalar::from(12u64))
        );
        identifier.inc(&IdentifierPrimeField(Scalar::from(2u64)));
        assert_eq!(identifier.0, Scalar::from(5u64));
        assert_eq!(
            IdentifierPrimeField::<Scalar>::one().invert(),
            Ok(IdentifierPrimeField::one())
        );
        assert_eq!(
            IdentifierPrimeField::<Scalar>::zero().invert(),
            Err(Error::InvalidShareElement)
        );
        assert!(
            IdentifierPrimeField(Scalar::from(1u64)) < IdentifierPrimeField(Scalar::from(2u64))
        );

        let mut hasher = DefaultHasher::new();
        identifier.hash(&mut hasher);
        assert_ne!(hasher.finish(), 0);
    }

    #[test]
    fn prime_field_converts_and_multiplies_with_supported_identifier_wrappers() {
        let base = IdentifierPrimeField(Scalar::from(3u64));
        let primitive = IdentifierPrimitive::<u16, 2>(4);
        assert_eq!(
            IdentifierPrimeField::<Scalar>::from(&primitive),
            IdentifierPrimeField(Scalar::from(4u64))
        );
        assert_eq!(base * &primitive, IdentifierPrimeField(Scalar::from(12u64)));

        let crypto_uint = crate::element::uint::IdentifierUint::<4>::from_slice(
            CryptoU256::from(6u64).to_be_bytes().as_ref(),
        )
        .unwrap();
        assert_eq!(
            base * &crypto_uint,
            IdentifierPrimeField(Scalar::from(18u64))
        );

        let residue = IdentifierResidue::<EcResidueMod, 4>::from_slice(
            EcU256::from(7u64).to_be_bytes().as_ref(),
        )
        .unwrap();
        assert_eq!(base * &residue, IdentifierPrimeField(Scalar::from(21u64)));

        let const_monty = IdentifierConstMontyResidue::<CryptoResidueMod, 4>::from_slice(
            CryptoU256::from(8u64).to_be_bytes().as_ref(),
        )
        .unwrap();
        assert_eq!(
            base * &const_monty,
            IdentifierPrimeField(Scalar::from(24u64))
        );
    }
}