1#![allow(clippy::derive_hash_xor_eq)]
6#![cfg_attr(
9 feature = "use-insecure-test-only-mock-crypto",
10 allow(clippy::trivially_copy_pass_by_ref)
11)]
12#![warn(missing_docs)]
13
14pub use ff;
15pub use group;
16pub use pairing;
17
18mod cmp_pairing;
19mod into_fr;
20
21#[cfg(feature = "codec-support")]
22#[macro_use]
23mod codec_impl;
24
25pub mod error;
26pub mod poly;
27pub mod serde_impl;
28
29use std::borrow::Borrow;
30use std::cmp::Ordering;
31use std::convert::TryInto;
32use std::fmt;
33use std::hash::{Hash, Hasher};
34use std::ops::{AddAssign, Mul, MulAssign, SubAssign};
35use std::slice::Iter;
36use std::vec::Vec;
37
38use ff::Field;
39use hex_fmt::HexFmt;
40use log::debug;
41use pairing::Engine;
42use rand::distributions::{Distribution, Standard};
43use rand::{rngs::OsRng, Rng, RngCore, SeedableRng};
44use rand_chacha::ChaChaRng;
45use serde::{Deserialize, Serialize};
46use zeroize::Zeroize;
47
48use crate::cmp_pairing::cmp_projective;
49use crate::error::{Error, ScalaromBytesError, ScalaromBytesResult, Result};
50use crate::poly::{Commitment, Poly};
51
52pub use crate::into_fr::IntoScalar;
53
54mod util;
55use util::sha3_256;
56
57#[cfg(feature = "use-insecure-test-only-mock-crypto")]
58mod mock;
59
60#[cfg(feature = "use-insecure-test-only-mock-crypto")]
61pub use crate::mock::{
62 Mersenne8 as Scalar, Mocktography as PEngine, Ms8Affine as G1Affine,
63 Ms8Affine as G2Affine, Ms8Projective as G1Projective, Ms8Projective as G2Projective, PK_SIZE, SIG_SIZE,
64};
65
66#[cfg(not(feature = "use-insecure-test-only-mock-crypto"))]
67pub use bls12_381::{Bls12 as PEngine, Scalar, G1Affine, G2Affine, G1Projective, G2Projective};
68use group::{Curve, Group, GroupEncoding};
69
70#[cfg(not(feature = "use-insecure-test-only-mock-crypto"))]
72pub const PK_SIZE: usize = 48;
73
74#[cfg(not(feature = "use-insecure-test-only-mock-crypto"))]
76pub const SIG_SIZE: usize = 96;
77
78#[derive(Deserialize, Serialize, Copy, Clone, PartialEq, Eq)]
80pub struct PublicKey(#[serde(with = "serde_impl::projective_publickey")] pub G1Projective);
81
82impl Hash for PublicKey {
83 fn hash<H: Hasher>(&self, state: &mut H) {
84 self.0.to_affine().to_bytes().as_ref().hash(state);
85 }
86}
87
88impl fmt::Debug for PublicKey {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 let uncomp = self.0.to_affine().to_bytes();
91 write!(f, "PublicKey({:0.10})", HexFmt(uncomp))
92 }
93}
94
95impl PartialOrd for PublicKey {
96 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
97 Some(self.cmp(&other))
98 }
99}
100
101impl Ord for PublicKey {
102 fn cmp(&self, other: &Self) -> Ordering {
103 cmp_projective(&self.0, &other.0)
104 }
105}
106
107impl PublicKey {
108 pub fn from(g1: G1Projective) -> Self {
109 PublicKey(g1)
110 }
111
112 pub fn verify_g2<H: Into<G2Affine>>(&self, sig: &Signature, hash: H) -> bool {
114 PEngine::pairing(&self.0.to_affine(), &hash.into()) == PEngine::pairing(&G1Affine::generator(), &sig.0.to_affine())
116 }
117
118 pub fn verify<M: AsRef<[u8]>>(&self, sig: &Signature, msg: M) -> bool {
122 self.verify_g2(sig, hash_g2(msg))
123 }
124
125 pub fn encrypt<M: AsRef<[u8]>>(&self, msg: M) -> Ciphertext {
130 self.encrypt_with_rng(&mut OsRng, msg)
131 }
132
133 pub fn encrypt_with_rng<R: RngCore, M: AsRef<[u8]>>(&self, rng: &mut R, msg: M) -> Ciphertext {
135 let r: Scalar = Scalar::random(rng);
136 let u = G1Affine::generator().mul(r);
137 let v: Vec<u8> = {
138 let g = self.0.to_affine().mul(r);
139 xor_with_hash(g, msg.as_ref())
140 };
141 let w = hash_g1_g2(u, &v).to_affine().mul(r);
142 Ciphertext(u, v, w)
143 }
144
145 pub fn from_bytes<B: Borrow<[u8; PK_SIZE]>>(bytes: B) -> ScalaromBytesResult<Self> {
147 let mut compressed: <G1Affine as GroupEncoding>::Repr = Default::default();
148 compressed.as_mut().copy_from_slice(bytes.borrow());
149 let opt_affine: Option<G1Affine> = G1Affine::from_bytes(&compressed).into();
151 let projective = opt_affine.ok_or(ScalaromBytesError::Invalid)?.into();
152 Ok(PublicKey(projective))
153 }
154
155 pub fn to_bytes(&self) -> [u8; PK_SIZE] {
157 let mut bytes = [0u8; PK_SIZE];
158 bytes.copy_from_slice(self.0.to_affine().to_bytes().as_ref());
159 bytes
160 }
161}
162
163#[cfg_attr(feature = "codec-support", derive(codec::Encode, codec::Decode))]
165#[derive(Deserialize, Serialize, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
166pub struct PublicKeyShare(pub PublicKey);
167
168impl fmt::Debug for PublicKeyShare {
169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170 let uncomp = (self.0).0.to_affine().to_uncompressed();
171 write!(f, "PublicKeyShare({:0.10})", HexFmt(uncomp))
172 }
173}
174
175impl PublicKeyShare {
176 pub fn verify_g2<H: Into<G2Affine>>(&self, sig: &SignatureShare, hash: H) -> bool {
178 self.0.verify_g2(&sig.0, hash)
179 }
180
181 pub fn verify<M: AsRef<[u8]>>(&self, sig: &SignatureShare, msg: M) -> bool {
185 self.verify_g2(sig, hash_g2(msg))
186 }
187
188 pub fn verify_decryption_share(&self, share: &DecryptionShare, ct: &Ciphertext) -> bool {
190 let Ciphertext(ref u, ref v, ref w) = *ct;
191 let hash = hash_g1_g2(*u, v);
192 PEngine::pairing(&share.0.to_affine(), &hash.to_affine()) == PEngine::pairing(&(self.0).0.to_affine(), &w.to_affine())
193 }
194
195 pub fn from_bytes<B: Borrow<[u8; PK_SIZE]>>(bytes: B) -> ScalaromBytesResult<Self> {
197 Ok(PublicKeyShare(PublicKey::from_bytes(bytes)?))
198 }
199
200 pub fn to_bytes(&self) -> [u8; PK_SIZE] {
202 self.0.to_bytes()
203 }
204}
205
206#[derive(Deserialize, Serialize, Clone, PartialEq, Eq)]
209pub struct Signature(#[serde(with = "serde_impl::projective")] G2Projective);
210
211impl PartialOrd for Signature {
212 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
213 Some(self.cmp(&other))
214 }
215}
216
217impl Ord for Signature {
218 fn cmp(&self, other: &Self) -> Ordering {
219 cmp_projective(&self.0, &other.0)
220 }
221}
222
223impl Distribution<Signature> for Standard {
224 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Signature {
225 Signature(G2Projective::random(rng))
226 }
227}
228
229impl fmt::Debug for Signature {
230 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231 let uncomp = self.0.to_affine().to_uncompressed();
232 write!(f, "Signature({:0.10})", HexFmt(uncomp))
233 }
234}
235
236impl Hash for Signature {
237 fn hash<H: Hasher>(&self, state: &mut H) {
238 self.0.to_affine().to_bytes().as_ref().hash(state);
239 }
240}
241
242impl Signature {
243 pub fn parity(&self) -> bool {
245 let uncomp = self.0.to_affine().to_uncompressed();
246 let xor_bytes: u8 = uncomp.as_ref().iter().fold(0, |result, byte| result ^ byte);
247 let parity = 0 != xor_bytes.count_ones() % 2;
248 debug!("Signature: {:0.10}, parity: {}", HexFmt(uncomp), parity);
249 parity
250 }
251
252 pub fn from_bytes<B: Borrow<[u8; SIG_SIZE]>>(bytes: B) -> ScalaromBytesResult<Self> {
254 let mut compressed: <G2Affine as GroupEncoding>::Repr = Default::default();
255 compressed.as_mut().copy_from_slice(bytes.borrow());
256 let opt_affine: Option<G2Affine> = G2Affine::from_bytes(&compressed).into();
257 let projective = opt_affine.ok_or(ScalaromBytesError::Invalid)?.into();
258 Ok(Signature(projective))
259 }
260
261 pub fn to_bytes(&self) -> [u8; SIG_SIZE] {
263 let mut bytes = [0u8; SIG_SIZE];
264 bytes.copy_from_slice(self.0.to_affine().to_bytes().as_ref());
265 bytes
266 }
267}
268
269#[cfg_attr(feature = "codec-support", derive(codec::Encode, codec::Decode))]
272#[derive(Deserialize, Serialize, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
273pub struct SignatureShare(pub Signature);
274
275impl Distribution<SignatureShare> for Standard {
276 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> SignatureShare {
277 SignatureShare(rng.gen())
278 }
279}
280
281impl fmt::Debug for SignatureShare {
282 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283 let uncomp = (self.0).0.to_affine().to_uncompressed();
284 write!(f, "SignatureShare({:0.10})", HexFmt(uncomp))
285 }
286}
287
288impl SignatureShare {
289 pub fn from_bytes<B: Borrow<[u8; SIG_SIZE]>>(bytes: B) -> ScalaromBytesResult<Self> {
291 Ok(SignatureShare(Signature::from_bytes(bytes)?))
292 }
293
294 pub fn to_bytes(&self) -> [u8; SIG_SIZE] {
296 self.0.to_bytes()
297 }
298}
299
300#[derive(PartialEq, Eq, Clone)]
309pub struct SecretKey(pub Scalar);
310
311impl Zeroize for SecretKey {
312 fn zeroize(&mut self) {
313 self.0.zeroize();
314 }
315}
316
317impl Drop for SecretKey {
318 fn drop(&mut self) {
319 self.zeroize();
320 }
321}
322
323impl Default for SecretKey {
325 fn default() -> Self {
326 let mut fr = Scalar::zero();
327 SecretKey::from_mut(&mut fr)
328 }
329}
330
331impl Distribution<SecretKey> for Standard {
332 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> SecretKey {
337 SecretKey(Scalar::random(rng))
338 }
339}
340
341impl fmt::Debug for SecretKey {
343 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
344 f.debug_tuple("SecretKey").field(&DebugDots).finish()
345 }
346}
347
348impl SecretKey {
349 pub fn from_mut(fr: &mut Scalar) -> Self {
357 let sk = SecretKey(*fr);
358 fr.zeroize();
359 sk
360 }
361
362 pub fn random() -> Self {
370 rand::random()
371 }
372
373 pub fn public_key(&self) -> PublicKey {
375 PublicKey(G1Affine::generator().mul(self.0))
376 }
377
378 pub fn sign_g2<H: Into<G2Affine>>(&self, hash: H) -> Signature {
380 Signature(hash.into().mul(self.0))
381 }
382
383 pub fn sign<M: AsRef<[u8]>>(&self, msg: M) -> Signature {
387 self.sign_g2(hash_g2(msg))
388 }
389
390 pub fn decrypt(&self, ct: &Ciphertext) -> Option<Vec<u8>> {
392 if !ct.verify() {
393 return None;
394 }
395 let Ciphertext(ref u, ref v, _) = *ct;
396 let g = u.to_affine().mul(self.0);
397 Some(xor_with_hash(g, v))
398 }
399
400 pub fn reveal(&self) -> String {
404 format!("SecretKey({:?})", self.0)
405 }
406}
407
408#[derive(Clone, PartialEq, Eq, Default)]
415pub struct SecretKeyShare(pub SecretKey);
416
417impl Distribution<SecretKeyShare> for Standard {
420 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> SecretKeyShare {
421 SecretKeyShare(rng.gen())
422 }
423}
424
425impl fmt::Debug for SecretKeyShare {
426 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427 f.debug_tuple("SecretKeyShare").field(&DebugDots).finish()
428 }
429}
430
431impl SecretKeyShare {
432 pub fn from_mut(fr: &mut Scalar) -> Self {
440 SecretKeyShare(SecretKey::from_mut(fr))
441 }
442
443 pub fn public_key_share(&self) -> PublicKeyShare {
445 PublicKeyShare(self.0.public_key())
446 }
447
448 pub fn sign_g2<H: Into<G2Affine>>(&self, hash: H) -> SignatureShare {
450 SignatureShare(self.0.sign_g2(hash))
451 }
452
453 pub fn sign<M: AsRef<[u8]>>(&self, msg: M) -> SignatureShare {
455 SignatureShare(self.0.sign(msg))
456 }
457
458 pub fn decrypt_share(&self, ct: &Ciphertext) -> Option<DecryptionShare> {
460 if !ct.verify() {
461 return None;
462 }
463 Some(self.decrypt_share_no_verify(ct))
464 }
465
466 pub fn decrypt_share_no_verify(&self, ct: &Ciphertext) -> DecryptionShare {
468 DecryptionShare(ct.0.to_affine().mul((self.0).0))
469 }
470
471 pub fn reveal(&self) -> String {
475 format!("SecretKeyShare({:?})", (self.0).0)
476 }
477}
478
479#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
481pub struct Ciphertext(
482 #[serde(with = "serde_impl::projective")] G1Projective,
483 Vec<u8>,
484 #[serde(with = "serde_impl::projective")] G2Projective,
485);
486
487impl Hash for Ciphertext {
488 fn hash<H: Hasher>(&self, state: &mut H) {
489 let Ciphertext(ref u, ref v, ref w) = *self;
490 u.to_affine().to_bytes().as_ref().hash(state);
491 v.hash(state);
492 w.to_affine().to_bytes().as_ref().hash(state);
493 }
494}
495
496impl PartialOrd for Ciphertext {
497 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
498 Some(self.cmp(&other))
499 }
500}
501
502impl Ord for Ciphertext {
503 fn cmp(&self, other: &Self) -> Ordering {
504 let Ciphertext(ref u0, ref v0, ref w0) = self;
505 let Ciphertext(ref u1, ref v1, ref w1) = other;
506 cmp_projective(u0, u1)
507 .then(v0.cmp(v1))
508 .then(cmp_projective(w0, w1))
509 }
510}
511
512impl Ciphertext {
513 pub fn verify(&self) -> bool {
516 let Ciphertext(ref u, ref v, ref w) = *self;
517 let hash = hash_g1_g2(*u, v);
518 PEngine::pairing(&G1Affine::generator(), &w.to_affine()) == PEngine::pairing(&u.to_affine(), &hash.to_affine())
519 }
520
521 pub fn to_bytes(&self) -> Vec<u8> {
523 let Ciphertext(ref u, ref v, ref w) = *self;
524
525 let mut bytes = Vec::with_capacity(48 + 96 + v.len());
526 bytes.extend_from_slice(&u.to_affine().to_compressed());
527 bytes.extend_from_slice(&w.to_affine().to_compressed());
528 bytes.extend_from_slice(&v);
529 bytes
530 }
531
532 pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
535 if bytes.len() < 48 + 96 {
536 return None;
537 }
538
539
540 let u_bytes: [u8; 48] = bytes[..48].try_into().expect("slice has correct length");
541 let u_res = G1Affine::from_compressed(&u_bytes);
542 if u_res.is_none().unwrap_u8() == 1 {
543 return None;
544 }
545
546 let w_bytes: [u8; 96] = bytes[48..48 + 96].try_into().expect("slice has correct length");
547 let w_res = G2Affine::from_compressed(&w_bytes);
548 if w_res.is_none().unwrap_u8() == 1 {
549 return None;
550 }
551
552 let u = G1Projective::from(u_res.unwrap());
553 let w = G2Projective::from(w_res.unwrap());
554 let v = bytes[48 + 96..].to_vec();
555
556 Some(Ciphertext(u, v, w))
557 }
558}
559
560#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)]
562pub struct DecryptionShare(#[serde(with = "serde_impl::projective")] G1Projective);
563
564impl DecryptionShare {
565 pub fn to_bytes(&self) -> [u8; 48] {
567 self.0.to_affine().to_compressed()
568 }
569
570 pub fn from_bytes(bytes: &[u8; 48]) -> Option<Self> {
573 let res = G1Affine::from_compressed(bytes);
574 if res.is_none().unwrap_u8() == 1 {
575 return None;
576 }
577 Some(DecryptionShare(G1Projective::from(res.unwrap())))
578 }
579}
580
581impl Distribution<DecryptionShare> for Standard {
582 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> DecryptionShare {
583 DecryptionShare(G1Projective::random(rng))
584 }
585}
586
587impl Hash for DecryptionShare {
588 fn hash<H: Hasher>(&self, state: &mut H) {
589 self.0.to_affine().to_bytes().as_ref().hash(state);
590 }
591}
592
593impl fmt::Debug for DecryptionShare {
594 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
595 f.debug_tuple("DecryptionShare").field(&DebugDots).finish()
596 }
597}
598
599#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
601pub struct PublicKeySet {
602 pub commit: Commitment,
605}
606
607impl Hash for PublicKeySet {
608 fn hash<H: Hasher>(&self, state: &mut H) {
609 self.commit.hash(state);
610 }
611}
612
613impl From<Commitment> for PublicKeySet {
614 fn from(commit: Commitment) -> PublicKeySet {
615 PublicKeySet { commit }
616 }
617}
618
619impl PublicKeySet {
620 pub fn coefficients(&self) -> Iter<G1Projective> {
622 self.commit.coeff.iter()
623 }
624
625 pub fn threshold(&self) -> usize {
628 self.commit.degree()
629 }
630
631 pub fn public_key(&self) -> PublicKey {
633 PublicKey(self.commit.coeff[0])
634 }
635
636 pub fn public_key_share<T: IntoScalar>(&self, i: T) -> PublicKeyShare {
638 let value = self.commit.evaluate(into_fr_plus_1(i));
639 PublicKeyShare(PublicKey(value))
640 }
641
642 pub fn combine_signatures<'a, T, I>(&self, shares: I) -> Result<Signature>
676 where
677 I: IntoIterator<Item = (T, &'a SignatureShare)>,
678 T: IntoScalar,
679 {
680 let samples = shares.into_iter().map(|(i, share)| (i, &(share.0).0));
681 Ok(Signature(interpolate(self.commit.degree(), samples)?))
682 }
683
684 pub fn decrypt<'a, T, I>(&self, shares: I, ct: &Ciphertext) -> Result<Vec<u8>>
686 where
687 I: IntoIterator<Item = (T, &'a DecryptionShare)>,
688 T: IntoScalar,
689 {
690 let samples = shares.into_iter().map(|(i, share)| (i, &share.0));
691 let g = interpolate(self.commit.degree(), samples)?;
692 Ok(xor_with_hash(g, &ct.1))
693 }
694}
695
696#[derive(Clone, PartialEq, Eq)]
698pub struct SecretKeySet {
699 poly: Poly,
702}
703
704impl From<Poly> for SecretKeySet {
705 fn from(poly: Poly) -> SecretKeySet {
706 SecretKeySet { poly }
707 }
708}
709
710impl SecretKeySet {
711 pub fn random<R: Rng>(threshold: usize, rng: &mut R) -> Self {
719 SecretKeySet::try_random(threshold, rng)
720 .unwrap_or_else(|e| panic!("Failed to create random `SecretKeySet`: {}", e))
721 }
722
723 pub fn try_random<R: Rng>(threshold: usize, rng: &mut R) -> Result<Self> {
727 Poly::try_random(threshold, rng).map(SecretKeySet::from)
728 }
729
730 pub fn threshold(&self) -> usize {
733 self.poly.degree()
734 }
735
736 pub fn secret_key_share<T: IntoScalar>(&self, i: T) -> SecretKeyShare {
738 let mut fr = self.poly.evaluate(into_fr_plus_1(i));
739 SecretKeyShare::from_mut(&mut fr)
740 }
741
742 pub fn public_keys(&self) -> PublicKeySet {
744 PublicKeySet {
745 commit: self.poly.commitment(),
746 }
747 }
748
749 #[cfg(test)]
751 fn secret_key(&self) -> SecretKey {
752 let mut fr = self.poly.evaluate(0);
753 SecretKey::from_mut(&mut fr)
754 }
755}
756
757pub fn hash_g2<M: AsRef<[u8]>>(msg: M) -> G2Projective{
759 let digest = sha3_256(msg.as_ref());
760 G2Projective::random(&mut ChaChaRng::from_seed(digest))
761}
762
763fn hash_g1_g2<M: AsRef<[u8]>>(g1: G1Projective, msg: M) -> G2Projective {
765 let mut msg = if msg.as_ref().len() > 64 {
768 sha3_256(msg.as_ref()).to_vec()
769 } else {
770 msg.as_ref().to_vec()
771 };
772 msg.extend(g1.to_affine().to_bytes().as_ref());
773 hash_g2(&msg)
774}
775
776fn xor_with_hash(g1: G1Projective, bytes: &[u8]) -> Vec<u8> {
778 let digest = sha3_256(g1.to_affine().to_bytes().as_ref());
779 let rng = ChaChaRng::from_seed(digest);
780 let xor = |(a, b): (u8, &u8)| a ^ b;
781 rng.sample_iter(&Standard).zip(bytes).map(xor).collect()
782}
783
784fn interpolate<C, B, T, I>(t: usize, items: I) -> Result<C>
787where
788 C: Curve,
789 <C as Group>::Scalar: MulAssign<Scalar> + MulAssign<<C as Group>::Scalar>,
790 I: IntoIterator<Item = (T, B)>,
791 T: IntoScalar,
792 B: Borrow<C>,
793{
794 let samples: Vec<_> = items
795 .into_iter()
796 .take(t + 1)
797 .map(|(i, sample)| (into_fr_plus_1(i), sample))
798 .collect();
799 if samples.len() <= t {
800 return Err(Error::NotEnoughShares);
801 }
802
803 if t == 0 {
804 return Ok(*samples[0].1.borrow());
805 }
806
807 let mut x_prod: Vec<C::Scalar> = Vec::with_capacity(t);
809 let mut tmp = C::Scalar::ONE;
810 x_prod.push(tmp);
811 for (x, _) in samples.iter().take(t) {
812 tmp.mul_assign(*x);
813 x_prod.push(tmp);
814 }
815 tmp = C::Scalar::ONE;
816 for (i, (x, _)) in samples[1..].iter().enumerate().rev() {
817 tmp.mul_assign(*x);
818 x_prod[i].mul_assign(tmp);
819 }
820
821 let mut result = C::identity();
822 for (mut l0, (x, sample)) in x_prod.into_iter().zip(&samples) {
823 let mut denom = C::Scalar::ONE;
826 for (x0, _) in samples.iter().filter(|(x0, _)| x0 != x) {
827 let mut diff = *x0;
828 diff.sub_assign(x);
829 denom.mul_assign(diff);
830 }
831 let opt_inv: Option<_> = denom.invert().into();
833 l0.mul_assign(&opt_inv.ok_or(Error::DuplicateEntry)?);
834 result.add_assign(*sample.borrow() * l0);
835 }
836 Ok(result)
837}
838
839fn into_fr_plus_1<I: IntoScalar>(x: I) -> Scalar {
840 let mut result = Scalar::one();
841 result.add_assign(&x.into_fr());
842 result
843}
844
845struct DebugDots;
848
849impl fmt::Debug for DebugDots {
850 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
851 write!(f, "...")
852 }
853}
854
855#[cfg(test)]
856mod tests {
857 use super::*;
858
859 use std::collections::BTreeMap;
860
861 use rand::{self, distributions::Standard, random, Rng};
862
863 #[test]
864 fn test_interpolate() {
865 let mut rng = rand::thread_rng();
866 for deg in 0..5 {
867 println!("deg = {}", deg);
868 let comm = Poly::random(deg, &mut rng).commitment();
869 let mut values = Vec::new();
870 let mut x = 0;
871 for _ in 0..=deg {
872 x += rng.gen_range(1..5);
873 values.push((x - 1, comm.evaluate(x)));
874 }
875 let actual = interpolate(deg, values).expect("wrong number of values");
876 assert_eq!(comm.evaluate(0), actual);
877 }
878 }
879
880 #[test]
881 fn test_simple_sig() {
882 let sk0 = SecretKey::random();
883 let sk1 = SecretKey::random();
884 let pk0 = sk0.public_key();
885 let msg0 = b"Real news";
886 let msg1 = b"Fake news";
887 assert!(pk0.verify(&sk0.sign(msg0), msg0));
888 assert!(!pk0.verify(&sk1.sign(msg0), msg0)); assert!(!pk0.verify(&sk0.sign(msg1), msg0)); }
891
892 #[test]
893 fn test_threshold_sig() {
894 let mut rng = rand::thread_rng();
895 let sk_set = SecretKeySet::random(3, &mut rng);
896 let pk_set = sk_set.public_keys();
897 let pk_master = pk_set.public_key();
898
899 assert_ne!(pk_master, pk_set.public_key_share(0).0);
901 assert_ne!(pk_master, pk_set.public_key_share(1).0);
902 assert_ne!(pk_master, pk_set.public_key_share(2).0);
903
904 let sk_master = sk_set.secret_key();
906 let sk_share_0 = sk_set.secret_key_share(0).0;
907 let sk_share_1 = sk_set.secret_key_share(1).0;
908 let sk_share_2 = sk_set.secret_key_share(2).0;
909 assert_ne!(sk_master, sk_share_0);
910 assert_ne!(sk_master, sk_share_1);
911 assert_ne!(sk_master, sk_share_2);
912
913 let msg = "Totally real news";
914
915 let sigs: BTreeMap<_, _> = [5, 8, 7, 10]
917 .iter()
918 .map(|&i| {
919 let sig = sk_set.secret_key_share(i).sign(msg);
920 (i, sig)
921 })
922 .collect();
923
924 for (i, sig) in &sigs {
926 assert!(pk_set.public_key_share(*i).verify(sig, msg));
927 }
928
929 let sig = pk_set.combine_signatures(&sigs).expect("signatures match");
931 assert!(pk_set.public_key().verify(&sig, msg));
932
933 let sigs2: BTreeMap<_, _> = [42, 43, 44, 45]
935 .iter()
936 .map(|&i| {
937 let sig = sk_set.secret_key_share(i).sign(msg);
938 (i, sig)
939 })
940 .collect();
941 let sig2 = pk_set.combine_signatures(&sigs2).expect("signatures match");
942 assert_eq!(sig, sig2);
943 }
944
945 #[test]
946 fn test_simple_enc() {
947 let sk_bob: SecretKey = random();
948 let sk_eve: SecretKey = random();
949 let pk_bob = sk_bob.public_key();
950 let msg = b"Muffins in the canteen today! Don't tell Eve!";
951 let ciphertext = pk_bob.encrypt(&msg[..]);
952 assert!(ciphertext.verify());
953
954 let ciphertext_bytes = ciphertext.to_bytes();
956 let decoded_ciphertext = Ciphertext::from_bytes(&ciphertext_bytes).expect("invalid ciphertext");
957 assert_eq!(ciphertext, decoded_ciphertext);
958
959 let decrypted = sk_bob.decrypt(&ciphertext).expect("invalid ciphertext");
961 assert_eq!(msg[..], decrypted[..]);
962
963 let decrypted_eve = sk_eve.decrypt(&ciphertext).expect("invalid ciphertext");
965 assert_ne!(msg[..], decrypted_eve[..]);
966
967 let Ciphertext(u, v, w) = ciphertext;
969 let fake_ciphertext = Ciphertext(u, vec![0; v.len()], w);
970 assert!(!fake_ciphertext.verify());
971 assert_eq!(None, sk_bob.decrypt(&fake_ciphertext));
972 }
973
974 #[test]
975 fn test_random_extreme_thresholds() {
976 let mut rng = rand::thread_rng();
977 let sks = SecretKeySet::random(0, &mut rng);
978 assert_eq!(0, sks.threshold());
979 assert!(SecretKeySet::try_random(usize::max_value(), &mut rng).is_err());
980 }
981
982 #[test]
983 fn test_threshold_enc() {
984 let mut rng = rand::thread_rng();
985 let sk_set = SecretKeySet::random(3, &mut rng);
986 let pk_set = sk_set.public_keys();
987 let msg = b"Totally real news";
988 let ciphertext = pk_set.public_key().encrypt(&msg[..]);
989
990 let shares: BTreeMap<_, _> = [5, 8, 7, 10]
992 .iter()
993 .map(|&i| {
994 let dec_share = sk_set
995 .secret_key_share(i)
996 .decrypt_share(&ciphertext)
997 .expect("ciphertext is invalid");
998
999 let encoded_decryption_share = dec_share.to_bytes();
1000 let decoded_encryption_share =
1001 DecryptionShare::from_bytes(&encoded_decryption_share)
1002 .expect("invalid decryption share");
1003 assert_eq!(dec_share, decoded_encryption_share);
1004
1005 (i, dec_share)
1006 })
1007 .collect();
1008
1009 for (i, share) in &shares {
1011 pk_set
1012 .public_key_share(*i)
1013 .verify_decryption_share(share, &ciphertext);
1014 }
1015
1016 let decrypted = pk_set
1018 .decrypt(&shares, &ciphertext)
1019 .expect("decryption shares match");
1020 assert_eq!(msg[..], decrypted[..]);
1021 }
1022
1023 #[test]
1025 fn test_hash_g2() {
1026 let rng = rand::thread_rng();
1027 let msg: Vec<u8> = rng.sample_iter(&Standard).take(1000).collect();
1028 let msg_end0: Vec<u8> = msg.iter().chain(b"end0").cloned().collect();
1029 let msg_end1: Vec<u8> = msg.iter().chain(b"end1").cloned().collect();
1030
1031 assert_eq!(hash_g2(&msg), hash_g2(&msg));
1032 assert_ne!(hash_g2(&msg), hash_g2(&msg_end0));
1033 assert_ne!(hash_g2(&msg_end0), hash_g2(&msg_end1));
1034 }
1035
1036 #[test]
1038 fn test_hash_g1_g2() {
1039 let mut rng = rand::thread_rng();
1040 let msg: Vec<u8> = (&mut rng).sample_iter(&Standard).take(1000).collect();
1041 let msg_end0: Vec<u8> = msg.iter().chain(b"end0").cloned().collect();
1042 let msg_end1: Vec<u8> = msg.iter().chain(b"end1").cloned().collect();
1043 let g0 = G1Projective::random(&mut rng);
1044 let g1 = G1Projective::random(&mut rng);
1045
1046 assert_eq!(hash_g1_g2(g0, &msg), hash_g1_g2(g0, &msg));
1047 assert_ne!(hash_g1_g2(g0, &msg), hash_g1_g2(g0, &msg_end0));
1048 assert_ne!(hash_g1_g2(g0, &msg_end0), hash_g1_g2(g0, &msg_end1));
1049 assert_ne!(hash_g1_g2(g0, &msg), hash_g1_g2(g1, &msg));
1050 }
1051
1052 #[test]
1054 fn test_xor_with_hash() {
1055 let mut rng = rand::thread_rng();
1056 let g0 = G1Projective::random(&mut rng);
1057 let g1 = G1Projective::random(&mut rng);
1058 let xwh = xor_with_hash;
1059 assert_eq!(xwh(g0, &[0; 5]), xwh(g0, &[0; 5]));
1060 assert_ne!(xwh(g0, &[0; 5]), xwh(g1, &[0; 5]));
1061 assert_eq!(5, xwh(g0, &[0; 5]).len());
1062 assert_eq!(6, xwh(g0, &[0; 6]).len());
1063 assert_eq!(20, xwh(g0, &[0; 20]).len());
1064 }
1065
1066 #[test]
1067 fn test_from_to_bytes() {
1068 let sk: SecretKey = random();
1069 let sig = sk.sign("Please sign here: ______");
1070 let pk = sk.public_key();
1071 let pk2 = PublicKey::from_bytes(pk.to_bytes()).expect("invalid pk representation");
1072 assert_eq!(pk, pk2);
1073 let sig2 = Signature::from_bytes(sig.to_bytes()).expect("invalid sig representation");
1074 assert_eq!(sig, sig2);
1075 }
1076
1077 #[test]
1078 fn test_serde() {
1079 let sk = SecretKey::random();
1080 let sig = sk.sign("Please sign here: ______");
1081 let pk = sk.public_key();
1082 let ser_pk = bincode::serialize(&pk).expect("serialize public key");
1083 let deser_pk = bincode::deserialize(&ser_pk).expect("deserialize public key");
1084 let serde_ser_pk = serde_json::to_string(&pk).expect("serde_json serialize public key");
1085 let serde_deser_pk: PublicKey = serde_json::from_str(&serde_ser_pk).expect("serde_json deserialized public key");
1086 assert_eq!(serde_ser_pk.chars().count(), PK_SIZE * 2 + 2); assert_eq!(pk, deser_pk);
1088 assert_eq!(pk, serde_deser_pk);
1089 let ser_sig = bincode::serialize(&sig).expect("serialize signature");
1090 let deser_sig = bincode::deserialize(&ser_sig).expect("deserialize signature");
1091 assert_eq!(ser_sig.len(), SIG_SIZE);
1092 assert_eq!(sig, deser_sig);
1093
1094 let threshold = 3;
1095 let sk_set = SecretKeySet::random(threshold, &mut OsRng::default());
1096 let pk_set = sk_set.public_keys();
1097 let ser_pk_set = serde_json::to_string(&pk_set).expect("serialize public key set");
1098 let de_pk_set = serde_json::from_str(&ser_pk_set).expect("deserialize public key set");
1099 assert_eq!(pk_set, de_pk_set);
1100
1101 for i in 0..sk_set.threshold() {
1102 let sk_share = sk_set.secret_key_share(i);
1103 let pk_share = sk_share.public_key_share();
1104 let ser_pk_share = serde_json::to_string(&pk_share).expect("serialize public key share");
1105 let de_pk_share: PublicKeyShare = serde_json::from_str(&ser_pk_share).expect("serialize public key share");
1106 assert_eq!(pk_share, de_pk_share);
1107 }
1108 }
1109
1110 #[cfg(feature = "codec-support")]
1111 #[test]
1112 fn test_codec() {
1113 use codec::{Decode, Encode};
1114 use rand::distributions::{Distribution, Standard};
1115 use rand::thread_rng;
1116
1117 macro_rules! assert_codec {
1118 ($obj:expr, $type:ty) => {
1119 let encoded: Vec<u8> = $obj.encode();
1120 let decoded: $type = <$type>::decode(&mut &encoded[..]).unwrap();
1121 assert_eq!(decoded, $obj.clone());
1122 };
1123 }
1124
1125 let sk = SecretKey::random();
1126 let pk = sk.public_key();
1127 assert_codec!(pk, PublicKey);
1128
1129 let pk_share = PublicKeyShare(pk);
1130 assert_codec!(pk_share, PublicKeyShare);
1131
1132 let sig = sk.sign(b"this is a test");
1133 assert_codec!(sig, Signature);
1134
1135 let sig_share = SignatureShare(sig);
1136 assert_codec!(sig_share, SignatureShare);
1137
1138 let cipher_text = pk.encrypt(b"cipher text");
1139 assert_codec!(cipher_text, Ciphertext);
1140
1141 let dec_share: DecryptionShare = Standard.sample(&mut thread_rng());
1142 assert_codec!(dec_share, DecryptionShare);
1143
1144 let sk_set = SecretKeySet::random(3, &mut thread_rng());
1145 let pk_set = sk_set.public_keys();
1146 assert_codec!(pk_set, PublicKeySet);
1147 }
1148
1149 #[test]
1150 fn test_size() {
1151 assert_eq!(<<G1Affine as GroupEncoding>::Repr as Default>::default().as_ref().len(), PK_SIZE);
1152 assert_eq!(<<G2Affine as GroupEncoding>::Repr as Default>::default().as_ref().len(), SIG_SIZE);
1153 }
1154
1155 #[test]
1156 fn test_zeroize() {
1157 let zero_sk = SecretKey::from_mut(&mut Scalar::zero());
1158
1159 let mut sk = SecretKey::random();
1160 assert_ne!(zero_sk, sk);
1161
1162 sk.zeroize();
1163 assert_eq!(zero_sk, sk);
1164 }
1165
1166 #[test]
1167 fn test_rng_seed() {
1168 let sk1 = SecretKey::random();
1169 let sk2 = SecretKey::random();
1170
1171 assert_ne!(sk1, sk2);
1172 let mut seed = [0u8; 32];
1173 rand::thread_rng().fill_bytes(&mut seed);
1174
1175 let mut rng = ChaChaRng::from_seed(seed);
1176 let sk3: SecretKey = rng.sample(Standard);
1177
1178 let mut rng = ChaChaRng::from_seed(seed);
1179 let sk4: SecretKey = rng.sample(Standard);
1180 assert_eq!(sk3, sk4);
1181 }
1182}