blsful 4.0.0

BLS signature implementation according to the IETF spec on the BLS12-381 curve.
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
use crate::helpers::{KEYGEN_SALT, get_crypto_rng};
use crate::impls::inner_types::*;
use crate::*;
use core::fmt::{self, Formatter};
use rand::CryptoRng;
use rand::RngExt;
use serde::de::{SeqAccess, Visitor};
use subtle::CtOption;
use vsss_rs::*;

/// Number of bytes needed to represent the secret key
pub const SECRET_KEY_BYTES: usize = 32;

/// A BLS secret key implementation
///
/// This does not expose the underlying curve
/// and signature scheme and can be used in situations where the specific
/// implementation is not known at compile time and where trait objects
/// are desirable but cannot be used because they lack the `Sized` trait.
/// The downside is that the type is indicated by a byte or string
/// for serialization and deserialization. If this is not desirable,
/// then use [`SecretKey<C>`](struct.SecretKey.html) instead.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SecretKeyEnum {
    /// A secret key for signatures in G1 and public keys in G2
    G1(SecretKey<Bls12381G1Impl>),
    /// A secret key for signatures in G2 and public keys in G1
    G2(SecretKey<Bls12381G2Impl>),
}

impl Serialize for SecretKeyEnum {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        match self {
            SecretKeyEnum::G1(sk) => (Bls12381::G1, sk).serialize(s),
            SecretKeyEnum::G2(sk) => (Bls12381::G2, sk).serialize(s),
        }
    }
}

impl<'de> Deserialize<'de> for SecretKeyEnum {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct SecretKeyEnumVisitor;

        impl<'de> Visitor<'de> for SecretKeyEnumVisitor {
            type Value = SecretKeyEnum;

            fn expecting(&self, f: &mut Formatter<'_>) -> fmt::Result {
                write!(f, "a tuple of the type and secret key")
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let ee = seq
                    .next_element::<Bls12381>()?
                    .ok_or_else(|| serde::de::Error::invalid_length(0, &self))?;
                match ee {
                    Bls12381::G1 => {
                        let sk = seq
                            .next_element::<SecretKey<Bls12381G1Impl>>()?
                            .ok_or_else(|| serde::de::Error::invalid_length(1, &self))?;
                        Ok(SecretKeyEnum::G1(sk))
                    }
                    Bls12381::G2 => {
                        let sk = seq
                            .next_element::<SecretKey<Bls12381G2Impl>>()?
                            .ok_or_else(|| serde::de::Error::invalid_length(1, &self))?;
                        Ok(SecretKeyEnum::G2(sk))
                    }
                }
            }
        }
        d.deserialize_tuple(2, SecretKeyEnumVisitor)
    }
}

impl Default for SecretKeyEnum {
    fn default() -> Self {
        Self::G1(SecretKey(Scalar::default()))
    }
}

impl From<&SecretKeyEnum> for Vec<u8> {
    fn from(value: &SecretKeyEnum) -> Self {
        let (tt, output) = match value {
            SecretKeyEnum::G1(sk) => (Bls12381::G1, Vec::from(sk)),
            SecretKeyEnum::G2(sk) => (Bls12381::G2, Vec::from(sk)),
        };
        typed_bytes(tt, output)
    }
}

impl TryFrom<&[u8]> for SecretKeyEnum {
    type Error = BlsError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        let (ee, value) = Bls12381::split_typed_bytes(value)?;
        match ee {
            Bls12381::G1 => {
                let sk = SecretKey::<Bls12381G1Impl>::try_from(value)?;
                Ok(SecretKeyEnum::G1(sk))
            }
            Bls12381::G2 => {
                let sk = SecretKey::<Bls12381G2Impl>::try_from(value)?;
                Ok(SecretKeyEnum::G2(sk))
            }
        }
    }
}

impl_from_derivatives!(SecretKeyEnum);

impl SecretKeyEnum {
    /// Return the concrete BLS12-381 signature group for this secret key.
    pub fn curve(&self) -> Bls12381 {
        match self {
            Self::G1(_) => Bls12381::G1,
            Self::G2(_) => Bls12381::G2,
        }
    }

    /// Create a new random secret key
    pub fn new(t: Bls12381) -> Self {
        match t {
            Bls12381::G1 => SecretKeyEnum::G1(SecretKey::new()),
            Bls12381::G2 => SecretKeyEnum::G2(SecretKey::new()),
        }
    }

    /// Compute a secret key from a hash
    pub fn from_hash<B: AsRef<[u8]>>(t: Bls12381, data: B) -> Self {
        match t {
            Bls12381::G1 => SecretKeyEnum::G1(SecretKey::from_hash(data)),
            Bls12381::G2 => SecretKeyEnum::G2(SecretKey::from_hash(data)),
        }
    }

    /// Compute a secret key from a CS-PRNG
    pub fn random(t: Bls12381, rng: impl CryptoRng) -> Self {
        match t {
            Bls12381::G1 => SecretKeyEnum::G1(SecretKey::random(rng)),
            Bls12381::G2 => SecretKeyEnum::G2(SecretKey::random(rng)),
        }
    }

    /// Get the big-endian byte representation of this key
    pub fn to_be_bytes(&self) -> Vec<u8> {
        let (t, output) = match self {
            SecretKeyEnum::G1(sk) => (Bls12381::G1, sk.to_be_bytes()),
            SecretKeyEnum::G2(sk) => (Bls12381::G2, sk.to_be_bytes()),
        };
        typed_bytes(t, output)
    }

    /// Get the little-endian byte representation of this key
    pub fn to_le_bytes(&self) -> Vec<u8> {
        let (t, output) = match self {
            SecretKeyEnum::G1(sk) => (Bls12381::G1, sk.to_le_bytes()),
            SecretKeyEnum::G2(sk) => (Bls12381::G2, sk.to_le_bytes()),
        };
        typed_bytes(t, output)
    }

    /// Convert a big-endian representation of the secret key.
    pub fn from_be_bytes(bytes: &[u8]) -> CtOption<Self> {
        let (t, bytes) = match Bls12381::split_typed_bytes(bytes) {
            Ok(parts) => parts,
            Err(_) => return CtOption::new(Self::default(), Choice::from(0u8)),
        };
        match bytes.try_into() {
            Ok(sk) => match t {
                Bls12381::G1 => {
                    let ct_sk = SecretKey::from_be_bytes(&sk);
                    let choice = ct_sk.is_some();
                    let val = SecretKeyEnum::G1(Option::from(ct_sk).unwrap_or_default());
                    CtOption::new(val, choice)
                }
                Bls12381::G2 => {
                    let ct_sk = SecretKey::from_be_bytes(&sk);
                    let choice = ct_sk.is_some();
                    let val = SecretKeyEnum::G2(Option::from(ct_sk).unwrap_or_default());
                    CtOption::new(val, choice)
                }
            },
            Err(_) => CtOption::new(Self::default(), Choice::from(0u8)),
        }
    }

    /// Convert a little-endian representation of the secret key.
    pub fn from_le_bytes(bytes: &[u8]) -> CtOption<Self> {
        let (t, bytes) = match Bls12381::split_typed_bytes(bytes) {
            Ok(parts) => parts,
            Err(_) => return CtOption::new(Self::default(), Choice::from(0u8)),
        };
        match bytes.try_into() {
            Ok(sk) => match t {
                Bls12381::G1 => {
                    let ct_sk = SecretKey::from_le_bytes(&sk);
                    let choice = ct_sk.is_some();
                    let val = SecretKeyEnum::G1(Option::from(ct_sk).unwrap_or_default());
                    CtOption::new(val, choice)
                }
                Bls12381::G2 => {
                    let ct_sk = SecretKey::from_le_bytes(&sk);
                    let choice = ct_sk.is_some();
                    let val = SecretKeyEnum::G2(Option::from(ct_sk).unwrap_or_default());
                    CtOption::new(val, choice)
                }
            },
            Err(_) => CtOption::new(Self::default(), Choice::from(0u8)),
        }
    }

    /// Compute the public key for this secret key.
    pub fn public_key(&self) -> PublicKeyEnum {
        match self {
            SecretKeyEnum::G1(sk) => PublicKeyEnum::G1(sk.public_key()),
            SecretKeyEnum::G2(sk) => PublicKeyEnum::G2(sk.public_key()),
        }
    }

    /// Create a proof of possession for this secret key.
    pub fn proof_of_possession(&self) -> BlsResult<ProofOfPossessionEnum> {
        match self {
            SecretKeyEnum::G1(sk) => sk.proof_of_possession().map(ProofOfPossessionEnum::G1),
            SecretKeyEnum::G2(sk) => sk.proof_of_possession().map(ProofOfPossessionEnum::G2),
        }
    }

    /// Sign a message with this secret key using the specified scheme.
    pub fn sign(&self, scheme: SignatureSchemes, msg: &[u8]) -> BlsResult<SignatureEnum> {
        match self {
            SecretKeyEnum::G1(sk) => sk.sign(scheme, msg).map(SignatureEnum::G1),
            SecretKeyEnum::G2(sk) => sk.sign(scheme, msg).map(SignatureEnum::G2),
        }
    }

    /// Sign a message using the basic signature scheme.
    pub fn sign_basic(&self, msg: impl AsRef<[u8]>) -> BlsResult<SignatureEnum> {
        self.sign(SignatureSchemes::Basic, msg.as_ref())
    }

    /// Sign a message using the message-augmentation signature scheme.
    pub fn sign_augmented(&self, msg: impl AsRef<[u8]>) -> BlsResult<SignatureEnum> {
        self.sign(SignatureSchemes::MessageAugmentation, msg.as_ref())
    }

    /// Sign a message using the proof-of-possession signature scheme.
    pub fn sign_pop(&self, msg: impl AsRef<[u8]>) -> BlsResult<SignatureEnum> {
        self.sign(SignatureSchemes::ProofOfPossession, msg.as_ref())
    }
}

/// The secret key is a field element `x` where 0 < `x` < `r`
/// and `r` is the curve order. See Section 4.3 of
/// <https://eprint.iacr.org/2016/663.pdf>
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct SecretKey<C: BlsSignatureImpl>(
    /// The secret key raw value
    #[serde(serialize_with = "traits::scalar::serialize::<C, _>")]
    #[serde(deserialize_with = "traits::scalar::deserialize::<C, _>")]
    pub <<C as Pairing>::PublicKey as Group>::Scalar,
);

impl<C: BlsSignatureImpl> From<SecretKey<C>> for [u8; SECRET_KEY_BYTES] {
    fn from(sk: SecretKey<C>) -> [u8; SECRET_KEY_BYTES] {
        sk.to_be_bytes()
    }
}

impl<'a, C: BlsSignatureImpl> From<&'a SecretKey<C>> for [u8; SECRET_KEY_BYTES] {
    fn from(sk: &'a SecretKey<C>) -> [u8; SECRET_KEY_BYTES] {
        sk.to_be_bytes()
    }
}

impl_from_derivatives_generic!(SecretKey);

impl<C: BlsSignatureImpl> From<&SecretKey<C>> for Vec<u8> {
    fn from(value: &SecretKey<C>) -> Self {
        value.to_be_bytes().to_vec()
    }
}

impl<C: BlsSignatureImpl> TryFrom<&[u8]> for SecretKey<C> {
    type Error = BlsError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        let bytes = <[u8; 32]>::try_from(value)
            .map_err(|_| BlsError::InvalidInputs("Invalid secret key bytes".to_string()))?;
        Option::from(Self::from_be_bytes(&bytes))
            .ok_or_else(|| BlsError::InvalidInputs("Invalid secret key bytes".to_string()))
    }
}

impl<C: BlsSignatureImpl> SecretKey<C> {
    /// Create a new random secret key
    pub fn new() -> Self {
        Self::random(get_crypto_rng())
    }

    /// Compute a secret key from a hash
    pub fn from_hash<B: AsRef<[u8]>>(data: B) -> Self {
        Self(<C as HashToScalar>::hash_to_scalar(
            data.as_ref(),
            KEYGEN_SALT,
        ))
    }

    /// Compute a secret key from a CS-PRNG
    pub fn random(mut rng: impl CryptoRng) -> Self {
        Self(<C as HashToScalar>::hash_to_scalar(
            rng.random::<[u8; SECRET_KEY_BYTES]>(),
            KEYGEN_SALT,
        ))
    }

    /// Get the big-endian byte representation of this key
    pub fn to_be_bytes(&self) -> [u8; SECRET_KEY_BYTES] {
        scalar_to_be_bytes::<C, SECRET_KEY_BYTES>(self.0)
    }

    /// Get the little-endian byte representation of this key
    pub fn to_le_bytes(&self) -> [u8; SECRET_KEY_BYTES] {
        scalar_to_le_bytes::<C, SECRET_KEY_BYTES>(self.0)
    }

    /// Convert a big-endian representation of the secret key.
    pub fn from_be_bytes(bytes: &[u8; SECRET_KEY_BYTES]) -> CtOption<Self> {
        scalar_from_be_bytes::<C, SECRET_KEY_BYTES>(bytes).map(Self)
    }

    /// Convert a little-endian representation of the secret key.
    pub fn from_le_bytes(bytes: &[u8; SECRET_KEY_BYTES]) -> CtOption<Self> {
        scalar_from_le_bytes::<C, SECRET_KEY_BYTES>(bytes).map(Self)
    }

    /// Secret-share this key by creating `limit` shares, of which `threshold`
    /// are required to reconstruct the secret.
    pub fn split(&self, threshold: usize, limit: usize) -> BlsResult<Vec<SecretKeyShare<C>>> {
        self.split_with_rng(threshold, limit, get_crypto_rng())
    }

    /// Secret-share this key using the specified RNG by creating `limit` shares,
    /// of which `threshold` are required to reconstruct the secret.
    pub fn split_with_rng(
        &self,
        threshold: usize,
        limit: usize,
        mut rng: impl CryptoRng,
    ) -> BlsResult<Vec<SecretKeyShare<C>>> {
        let secret = IdentifierPrimeField(self.0);
        let shares = shamir::split_secret::<<C as Pairing>::SecretKeyShare>(
            threshold, limit, &secret, &mut rng,
        )?
        .into_iter()
        .map(SecretKeyShare)
        .collect::<Vec<_>>();
        Ok(shares)
    }

    /// Reconstruct a secret from shares created by [`Self::split`].
    pub fn combine(shares: &[SecretKeyShare<C>]) -> BlsResult<Self> {
        if shares.len() < 2 {
            return Err(BlsError::InvalidInputs(
                "at least two secret key shares are required".to_string(),
            ));
        }
        let ss = shares.iter().map(|s| s.0.clone()).collect::<Vec<_>>();
        let secret = ss.combine()?;
        Ok(Self(secret.0))
    }

    /// Compute the public key
    pub fn public_key(&self) -> PublicKey<C> {
        PublicKey(<C as BlsSignatureCore>::public_key(&self.0))
    }

    /// Create a proof of possession
    pub fn proof_of_possession(&self) -> BlsResult<ProofOfPossession<C>> {
        Ok(ProofOfPossession(<C as BlsSignaturePop>::pop_prove(
            &self.0,
        )?))
    }

    /// Sign a message with this secret key using the specified scheme
    pub fn sign(&self, scheme: SignatureSchemes, msg: &[u8]) -> BlsResult<Signature<C>> {
        match scheme {
            SignatureSchemes::Basic => {
                let inner = <C as BlsSignatureBasic>::sign(&self.0, msg)?;
                Ok(Signature::Basic(inner))
            }
            SignatureSchemes::MessageAugmentation => {
                let inner = <C as BlsSignatureMessageAugmentation>::sign(&self.0, msg)?;
                Ok(Signature::MessageAugmentation(inner))
            }
            SignatureSchemes::ProofOfPossession => {
                let inner = <C as BlsSignaturePop>::sign(&self.0, msg)?;
                Ok(Signature::ProofOfPossession(inner))
            }
        }
    }

    /// Sign a message using the basic signature scheme.
    pub fn sign_basic(&self, msg: impl AsRef<[u8]>) -> BlsResult<Signature<C>> {
        self.sign(SignatureSchemes::Basic, msg.as_ref())
    }

    /// Sign a message using the message-augmentation signature scheme.
    pub fn sign_augmented(&self, msg: impl AsRef<[u8]>) -> BlsResult<Signature<C>> {
        self.sign(SignatureSchemes::MessageAugmentation, msg.as_ref())
    }

    /// Sign a message using the proof-of-possession signature scheme.
    pub fn sign_pop(&self, msg: impl AsRef<[u8]>) -> BlsResult<Signature<C>> {
        self.sign(SignatureSchemes::ProofOfPossession, msg.as_ref())
    }

    /// Create a signcryption decryption key that hides the secret key and can
    /// decrypt the ciphertext.
    pub fn sign_decryption_key<B: AsRef<[u8]>>(
        &self,
        ciphertext: &SignCryptCiphertext<C>,
    ) -> SignCryptDecryptionKey<C> {
        SignCryptDecryptionKey(ciphertext.u * self.0)
    }
}