testudo/src/group.rs
src/group.rsRaw
1use crate::errors::ProofVerifyError;
2use ark_ec::msm::VariableBaseMSM;
3use ark_ff::PrimeField;
4
5use lazy_static::lazy_static;
6
7use super::scalar::Scalar;
8
9use ark_ec::ProjectiveCurve;
10use ark_serialize::*;
11use core::borrow::Borrow;
12
13pub type GroupElement = ark_bls12_377::G1Projective;
14pub type GroupElementAffine = ark_bls12_377::G1Affine;
15pub type Fq = ark_bls12_377::Fq;
16pub type Fr = ark_bls12_377::Fr;
17
18#[derive(Clone, Eq, PartialEq, Hash, Debug, CanonicalSerialize, CanonicalDeserialize)]
19pub struct CompressedGroup(pub Vec<u8>);
20
21lazy_static! {
22 pub static ref GROUP_BASEPOINT: GroupElement = GroupElement::prime_subgroup_generator();
23}
24
25pub trait CompressGroupElement {
26 fn compress(&self) -> CompressedGroup;
27}
28
29pub trait DecompressGroupElement {
30 fn decompress(encoded: &CompressedGroup) -> Option<GroupElement>;
31}
32
33pub trait UnpackGroupElement {
34 fn unpack(&self) -> Result<GroupElement, ProofVerifyError>;
35}
36
37impl CompressGroupElement for GroupElement {
38 fn compress(&self) -> CompressedGroup {
39 let mut point_encoding = Vec::new();
40 self.serialize(&mut point_encoding).unwrap();
41 CompressedGroup(point_encoding)
42 }
43}
44
45impl DecompressGroupElement for GroupElement {
46 fn decompress(encoded: &CompressedGroup) -> Option<Self> {
47 let res = GroupElement::deserialize(&*encoded.0);
48 if let Ok(r) = res {
49 Some(r)
50 } else {
51 println!("{:?}", res);
52 None
53 }
54 }
55}
56
57impl UnpackGroupElement for CompressedGroup {
58 fn unpack(&self) -> Result<GroupElement, ProofVerifyError> {
59 let encoded = self.0.clone();
60 GroupElement::decompress(self).ok_or(ProofVerifyError::DecompressionError(encoded))
61 }
62}
63
64pub trait VartimeMultiscalarMul {
65 fn vartime_multiscalar_mul(scalars: &[Scalar], points: &[GroupElement]) -> GroupElement;
66}
67
68impl VartimeMultiscalarMul for GroupElement {
69 fn vartime_multiscalar_mul(scalars: &[Scalar], points: &[GroupElement]) -> GroupElement {
70 let repr_scalars = scalars
71 .iter()
72 .map(|S| S.borrow().into_repr())
73 .collect::<Vec<<Scalar as PrimeField>::BigInt>>();
74 let aff_points = points
75 .iter()
76 .map(|P| P.borrow().into_affine())
77 .collect::<Vec<GroupElementAffine>>();
78 VariableBaseMSM::multi_scalar_mul(aff_points.as_slice(), repr_scalars.as_slice())
79 }
80}