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
/*
    Copyright Michael Lodder. All Rights Reserved.
    SPDX-License-Identifier: Apache-2.0
*/
//! Verifiable Secret Sharing Schemes are using to split secrets into
//! multiple shares and distribute them among different entities,
//! with the ability to verify if the shares are correct and belong
//! to a specific set. This crate includes Shamir's secret sharing
//! scheme which does not support verification but is more of a
//! building block for the other schemes.
//!
//! This crate supports Feldman and Pedersen verifiable secret sharing
//! schemes.
//!
//! Feldman and Pedersen are similar in many ways. It's hard to describe when to use
//! one over the other. Indeed both are used in
//! <http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.134.6445&rep=rep1&type=pdf>.
//!
//! Feldman reveals the public value of the verifier whereas Pedersen's hides it.
//!
//! Feldman and Pedersen are different from Shamir when splitting the secret.
//! Combining shares back into the original secret is identical across all methods
//! and is available for each scheme for convenience.
//!
//! This crate is no-standard compliant and uses const generics to specify sizes.
//!
//! This crate supports any number as the maximum number of shares to be requested.
//! Anything higher than 255 is pretty ridiculous but if such a use case exists please let me know.
//! This said, any number of shares can be requested since identifiers can be any size.
//!
//! Shares are represented as byte arrays. Shares can represent finite fields or groups
//! depending on the use case. In the simplest case,
//! the first byte is reserved for the share identifier (x-coordinate)
//! and everything else is the actual value of the share (y-coordinate).
//! However, anything can be used as the identifier as long as it implements the
//! [`ShareIdentifier`] trait.
//!
//! When specifying share sizes, use the field size in bytes + 1 for the identifier in the easiest
//! case.
//!
//! To split a p256 secret using Shamir
//!
//! ```
//! use vsss_rs::{*, shamir};
//! use elliptic_curve::ff::PrimeField;
//! use p256::{NonZeroScalar, Scalar, SecretKey};
//!
//! let mut osrng = rand_core::OsRng::default();
//! let sk = SecretKey::random(&mut osrng);
//! let nzs = sk.to_nonzero_scalar();
//! let res = shamir::split_secret::<Scalar, u8, Vec<u8>>(2, 3, *nzs.as_ref(), &mut osrng);
//! assert!(res.is_ok());
//! let shares = res.unwrap();
//! let res = combine_shares(&shares);
//! assert!(res.is_ok());
//! let scalar: Scalar = res.unwrap();
//! let nzs_dup =  NonZeroScalar::from_repr(scalar.to_repr()).unwrap();
//! let sk_dup = SecretKey::from(nzs_dup);
//! assert_eq!(sk_dup.to_bytes(), sk.to_bytes());
//! ```
//!
//! To split a k256 secret using Shamir
//!
//! ```
//! use vsss_rs::{*, shamir};
//! use elliptic_curve::ff::PrimeField;
//! use k256::{NonZeroScalar, Scalar, ProjectivePoint, SecretKey};
//!
//! let mut osrng = rand_core::OsRng::default();
//! let sk = SecretKey::random(&mut osrng);
//! let secret = *sk.to_nonzero_scalar();
//! let res = shamir::split_secret::<Scalar, u8, Vec<u8>>(2, 3, secret, &mut osrng);
//! assert!(res.is_ok());
//! let shares = res.unwrap();
//! let res = combine_shares(&shares);
//! assert!(res.is_ok());
//! let scalar: Scalar = res.unwrap();
//! let nzs_dup = NonZeroScalar::from_repr(scalar.to_repr()).unwrap();
//! let sk_dup = SecretKey::from(nzs_dup);
//! assert_eq!(sk_dup.to_bytes(), sk.to_bytes());
//! ```
//!
//! Feldman or Pedersen return extra information for verification using their respective verifiers
//!
//! ```
//! use vsss_rs::{*, feldman};
//! use bls12_381_plus::{Scalar, G1Projective};
//! use elliptic_curve::ff::Field;
//!
//! let mut rng = rand_core::OsRng::default();
//! let secret = Scalar::random(&mut rng);
//! let res = feldman::split_secret::<G1Projective, u8, Vec<u8>>(2, 3, secret, None, &mut rng);
//! assert!(res.is_ok());
//! let (shares, verifier) = res.unwrap();
//! for s in &shares {
//!     assert!(verifier.verify_share(s).is_ok());
//! }
//! let res = combine_shares(&shares);
//! assert!(res.is_ok());
//! let secret_1: Scalar = res.unwrap();
//! assert_eq!(secret, secret_1);
//! ```
//!
//! Curve25519 is not a prime field but this crate does support it using
//! `features=["curve25519"]` which is enabled by default. This feature
//! wraps curve25519-dalek libraries so they can be used with Shamir, Feldman, and Pedersen.
//!
//! Here's an example of using Ed25519 and x25519
//!
//! ```
//! #[cfg(feature = "curve25519")] {
//! use curve25519_dalek::scalar::Scalar;
//! use rand::Rng;
//! use ed25519_dalek::SigningKey;
//! use vsss_rs::{curve25519::WrappedScalar, *};
//! use x25519_dalek::StaticSecret;
//!
//! let mut osrng = rand::rngs::OsRng::default();
//! let sc = Scalar::hash_from_bytes::<sha2::Sha512>(&osrng.gen::<[u8; 32]>());
//! let sk1 = StaticSecret::from(sc.to_bytes());
//! let ske1 = SigningKey::from_bytes(&sc.to_bytes());
//! let res = shamir::split_secret::<WrappedScalar, u8, Vec<u8>>(2, 3, sc.into(), &mut osrng);
//! assert!(res.is_ok());
//! let shares = res.unwrap();
//! let res = combine_shares(&shares);
//! assert!(res.is_ok());
//! let scalar: WrappedScalar = res.unwrap();
//! assert_eq!(scalar.0, sc);
//! let sk2 = StaticSecret::from(scalar.0.to_bytes());
//! let ske2 = SigningKey::from_bytes(&scalar.0.to_bytes());
//! assert_eq!(sk2.to_bytes(), sk1.to_bytes());
//! assert_eq!(ske1.to_bytes(), ske2.to_bytes());
//! }
//! ```
#![deny(
    missing_docs,
    unused_import_braces,
    unused_qualifications,
    unused_parens,
    unused_lifetimes,
    unconditional_recursion,
    unused_extern_crates,
    trivial_casts,
    trivial_numeric_casts
)]
#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]

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

#[cfg(feature = "std")]
#[cfg_attr(feature = "std", macro_use)]
extern crate std;

#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::{boxed::Box, vec::Vec};
#[cfg(feature = "std")]
use std::vec::Vec;

#[cfg(test)]
pub(crate) mod tests;

mod error;
pub mod feldman;
#[allow(clippy::suspicious_arithmetic_impl)]
#[allow(clippy::suspicious_op_assign_impl)]
mod gf256;
mod numbering;
pub mod pedersen;
mod polynomial;
mod set;
pub mod shamir;
mod share;
mod util;

use shamir::{check_params, create_shares};
use subtle::*;

pub use error::*;
pub use feldman::Feldman;
pub use gf256::*;
pub use identifier::*;
pub use numbering::*;
pub use pedersen::{Pedersen, PedersenResult};
pub use polynomial::*;
pub use set::*;
pub use shamir::Shamir;
pub use share::*;
pub use util::*;

#[cfg(any(feature = "alloc", feature = "std"))]
pub use pedersen::StdPedersenResult;

#[cfg(feature = "curve25519")]
#[cfg_attr(docsrs, doc(cfg(feature = "curve25519")))]
pub mod curve25519;
mod identifier;

#[cfg(feature = "curve25519")]
pub use curve25519_dalek;
pub use elliptic_curve;
use elliptic_curve::{group::GroupEncoding, Group, PrimeField};
pub use subtle;

/// Create a no-std verifiable secret sharing scheme with size $num using fixed arrays
/// The arguments in order are:
///     The vsss name
///     The name for a pedersen secret sharing scheme result
///     The maximum threshold allowed
///     The maximum number of shares allowed
#[macro_export]
macro_rules! vsss_arr_impl {
    ($name:ident, $result:ident, $max_threshold:expr, $max_shares:expr) => {
        /// No-std verifiable secret sharing scheme with size $num
        pub struct $name<G, I, S>
        where
            G: Group + GroupEncoding + Default,
            I: ShareIdentifier,
            S: Share<Identifier = I>,
        {
            marker: core::marker::PhantomData<(G, I, S)>,
        }

        impl<G: Group + GroupEncoding + Default, I: ShareIdentifier, S: Share<Identifier = I>>
            Shamir<G::Scalar, I, S> for $name<G, I, S>
        {
            type InnerPolynomial = [G::Scalar; $max_threshold];
            type ShareSet = [S; $max_shares];
        }

        impl<G: Group + GroupEncoding + Default, I: ShareIdentifier, S: Share<Identifier = I>>
            Feldman<G, I, S> for $name<G, I, S>
        {
            type VerifierSet = [G; $max_threshold + 1];
        }

        impl<G: Group + GroupEncoding + Default, I: ShareIdentifier, S: Share<Identifier = I>>
            Pedersen<G, I, S> for $name<G, I, S>
        {
            type FeldmanVerifierSet = [G; $max_threshold + 1];
            type PedersenVerifierSet = [G; $max_threshold + 2];
            type PedersenResult = $result<G, I, S>;
        }

        /// The no-std result to use when an allocator is available with size $num
        pub struct $result<G, I, S>
        where
            G: Group + GroupEncoding + Default,
            I: ShareIdentifier,
            S: Share<Identifier = I>,
        {
            blinder: G::Scalar,
            secret_shares: [S; $max_shares],
            blinder_shares: [S; $max_shares],
            feldman_verifier_set: [G; $max_threshold + 1],
            pedersen_verifier_set: [G; $max_threshold + 2],
        }

        impl<G, I, S> PedersenResult<G, I, S> for $result<G, I, S>
        where
            G: Group + GroupEncoding + Default,
            I: ShareIdentifier,
            S: Share<Identifier = I>,
        {
            type ShareSet = [S; $max_shares];
            type FeldmanVerifierSet = [G; $max_threshold + 1];
            type PedersenVerifierSet = [G; $max_threshold + 2];

            fn new(
                blinder: G::Scalar,
                secret_shares: Self::ShareSet,
                blinder_shares: Self::ShareSet,
                feldman_verifier_set: Self::FeldmanVerifierSet,
                pedersen_verifier_set: Self::PedersenVerifierSet,
            ) -> Self {
                Self {
                    blinder,
                    secret_shares,
                    blinder_shares,
                    feldman_verifier_set,
                    pedersen_verifier_set,
                }
            }

            fn blinder(&self) -> G::Scalar {
                self.blinder
            }

            fn secret_shares(&self) -> &Self::ShareSet {
                &self.secret_shares
            }

            fn blinder_shares(&self) -> &Self::ShareSet {
                &self.blinder_shares
            }

            fn feldman_verifier_set(&self) -> &Self::FeldmanVerifierSet {
                &self.feldman_verifier_set
            }

            fn pedersen_verifier_set(&self) -> &Self::PedersenVerifierSet {
                &self.pedersen_verifier_set
            }
        }
    };
}

#[cfg(any(feature = "alloc", feature = "std"))]
/// Reconstruct a secret from shares created from split_secret. The X-coordinates operate in F The Y-coordinates operate in F
pub fn combine_shares<F: PrimeField, I: ShareIdentifier, S: Share<Identifier = I>>(
    shares: &[S],
) -> VsssResult<F> {
    shares.combine_to_field_element::<F, Vec<(F, F)>>()
}

#[cfg(any(feature = "alloc", feature = "std"))]
/// Reconstruct a secret from shares created from split_secret. The X-coordinates operate in F The Y-coordinates operate in G
///
/// Exists to support operations like threshold BLS where the shares operate in F but the partial signatures operate in G.
pub fn combine_shares_group<
    G: Group + GroupEncoding + Default,
    I: ShareIdentifier,
    S: Share<Identifier = I>,
>(
    shares: &[S],
) -> VsssResult<G> {
    shares.combine_to_group_element::<G, Vec<(G::Scalar, G)>>()
}

#[cfg(any(feature = "alloc", feature = "std"))]
/// Standard verifiable secret sharing scheme
pub struct StdVsss<G, I, S>
where
    G: Group + GroupEncoding + Default,
    I: ShareIdentifier,
    S: Share<Identifier = I>,
{
    _marker: (core::marker::PhantomData<G>, core::marker::PhantomData<S>),
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<G, I, S> Shamir<G::Scalar, I, S> for StdVsss<G, I, S>
where
    G: Group + GroupEncoding + Default,
    I: ShareIdentifier,
    S: Share<Identifier = I>,
{
    type InnerPolynomial = Vec<G::Scalar>;
    type ShareSet = Vec<S>;
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<G, I, S> Feldman<G, I, S> for StdVsss<G, I, S>
where
    G: Group + GroupEncoding + Default,
    I: ShareIdentifier,
    S: Share<Identifier = I>,
{
    type VerifierSet = Vec<G>;
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<G, I, S> Pedersen<G, I, S> for StdVsss<G, I, S>
where
    G: Group + GroupEncoding + Default,
    I: ShareIdentifier,
    S: Share<Identifier = I>,
{
    type FeldmanVerifierSet = Vec<G>;
    type PedersenVerifierSet = Vec<G>;
    type PedersenResult = StdPedersenResult<G, I, S>;
}

#[cfg(any(feature = "alloc", feature = "std"))]
/// Default Standard verifiable secret sharing scheme
/// that uses a single byte for the identifier and a Vec<u8> for the share.
/// This is the most common use case since most secret sharing schemes don't generate
/// more than 255 shares.
pub struct DefaultStdVsss<G: Group + GroupEncoding + Default> {
    _marker: core::marker::PhantomData<G>,
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<G: Group + GroupEncoding + Default> Shamir<G::Scalar, u8, Vec<u8>> for DefaultStdVsss<G> {
    type InnerPolynomial = Vec<G::Scalar>;
    type ShareSet = Vec<Vec<u8>>;
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<G> Feldman<G, u8, Vec<u8>> for DefaultStdVsss<G>
where
    G: Group + GroupEncoding + Default,
{
    type VerifierSet = Vec<G>;
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<G> Pedersen<G, u8, Vec<u8>> for DefaultStdVsss<G>
where
    G: Group + GroupEncoding + Default,
{
    type FeldmanVerifierSet = Vec<G>;
    type PedersenVerifierSet = Vec<G>;
    type PedersenResult = StdPedersenResult<G, u8, Vec<u8>>;
}

#[cfg(any(feature = "alloc", feature = "std"))]
#[test]
fn default_std_vsss() {
    use elliptic_curve::ff::Field;

    let mut osrng = rand_core::OsRng::default();
    let secret = p256::Scalar::random(&mut osrng);
    let res = DefaultStdVsss::<p256::ProjectivePoint>::split_secret(2, 3, secret, &mut osrng);
    assert!(res.is_ok());
    let shares = res.unwrap();
    let res = combine_shares(&shares);
    assert!(res.is_ok());
    let scalar: p256::Scalar = res.unwrap();
    assert_eq!(secret, scalar);
}