penumbra_keys/keys/fvk/
r1cs.rs

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
use ark_r1cs_std::prelude::*;
use ark_relations::r1cs::SynthesisError;
use decaf377::{
    r1cs::{ElementVar, FqVar},
    Element, Fq, Fr,
};
use decaf377_rdsa::{SpendAuth, VerificationKey, VerificationKeyBytes};
use once_cell::sync::Lazy;

fn generator() -> Element {
    Element::GENERATOR
}

pub(crate) static SPENDAUTH_BASEPOINT: Lazy<Element> = Lazy::new(generator);

pub struct RandomizedVerificationKey {
    pub inner: ElementVar,
}

impl AllocVar<VerificationKey<SpendAuth>, Fq> for RandomizedVerificationKey {
    fn new_variable<T: std::borrow::Borrow<VerificationKey<SpendAuth>>>(
        cs: impl Into<ark_relations::r1cs::Namespace<Fq>>,
        f: impl FnOnce() -> Result<T, SynthesisError>,
        mode: ark_r1cs_std::prelude::AllocationMode,
    ) -> Result<Self, SynthesisError> {
        let ns = cs.into();
        let cs = ns.cs();
        let inner: VerificationKey<SpendAuth> = *f()?.borrow();
        match mode {
            AllocationMode::Constant => unimplemented!(),
            AllocationMode::Input => {
                let point = decaf377::Encoding(*inner.as_ref())
                    .vartime_decompress()
                    .map_err(|_| SynthesisError::MalformedVerifyingKey)?;
                let element_var: ElementVar = AllocVar::new_input(cs, || Ok(point))?;
                Ok(Self { inner: element_var })
            }
            AllocationMode::Witness => unimplemented!(),
        }
    }
}

impl R1CSVar<Fq> for RandomizedVerificationKey {
    type Value = VerificationKey<SpendAuth>;

    fn cs(&self) -> ark_relations::r1cs::ConstraintSystemRef<Fq> {
        self.inner.cs()
    }

    fn value(&self) -> Result<Self::Value, SynthesisError> {
        let point = self.inner.value()?;
        let key_bytes = point.vartime_compress();
        let verification_key_bytes: VerificationKeyBytes<SpendAuth> = key_bytes.0.into();
        Ok(
            VerificationKey::<SpendAuth>::try_from(verification_key_bytes)
                .expect("should be able to convert from bytes"),
        )
    }
}

impl RandomizedVerificationKey {
    pub fn compress_to_field(&self) -> Result<FqVar, SynthesisError> {
        self.inner.compress_to_field()
    }
}

impl EqGadget<Fq> for RandomizedVerificationKey {
    fn is_eq(&self, other: &Self) -> Result<Boolean<Fq>, SynthesisError> {
        let self_fq = self.inner.compress_to_field()?;
        let other_fq = other.compress_to_field()?;
        self_fq.is_eq(&other_fq)
    }
}

pub struct AuthorizationKeyVar {
    pub inner: ElementVar,
}

impl AllocVar<VerificationKey<SpendAuth>, Fq> for AuthorizationKeyVar {
    fn new_variable<T: std::borrow::Borrow<VerificationKey<SpendAuth>>>(
        cs: impl Into<ark_relations::r1cs::Namespace<Fq>>,
        f: impl FnOnce() -> Result<T, SynthesisError>,
        mode: ark_r1cs_std::prelude::AllocationMode,
    ) -> Result<Self, SynthesisError> {
        let ns = cs.into();
        let cs = ns.cs();
        let inner: VerificationKey<SpendAuth> = *f()?.borrow();
        match mode {
            AllocationMode::Constant => unimplemented!(),
            AllocationMode::Input => unimplemented!(),
            AllocationMode::Witness => {
                let ak_point = decaf377::Encoding(*inner.as_ref())
                    .vartime_decompress()
                    .map_err(|_| SynthesisError::MalformedVerifyingKey)?;
                let ak_element_var: ElementVar =
                    AllocVar::<Element, Fq>::new_witness(cs.clone(), || Ok(ak_point))?;

                // The ak must never be identity.
                let identity = ElementVar::new_constant(cs, decaf377::Element::default())?;
                identity.enforce_not_equal(&ak_element_var)?;
                Ok(Self {
                    inner: ak_element_var,
                })
            }
        }
    }
}

impl R1CSVar<Fq> for AuthorizationKeyVar {
    type Value = VerificationKey<SpendAuth>;

    fn cs(&self) -> ark_relations::r1cs::ConstraintSystemRef<Fq> {
        self.inner.cs()
    }

    fn value(&self) -> Result<Self::Value, SynthesisError> {
        let point = self.inner.value()?;
        let key_bytes = point.vartime_compress();
        let verification_key_bytes: VerificationKeyBytes<SpendAuth> = key_bytes.0.into();
        Ok(
            VerificationKey::<SpendAuth>::try_from(verification_key_bytes)
                .expect("should be able to convert from bytes"),
        )
    }
}

impl AuthorizationKeyVar {
    pub fn randomize(
        &self,
        spend_auth_randomizer: &SpendAuthRandomizerVar,
    ) -> Result<RandomizedVerificationKey, SynthesisError> {
        let cs = self.inner.cs();
        let spend_auth_basepoint_var = ElementVar::new_constant(cs, *SPENDAUTH_BASEPOINT)?;
        let point = self.inner.clone()
            + spend_auth_basepoint_var
                .scalar_mul_le(spend_auth_randomizer.inner.to_bits_le()?.iter())?;
        Ok(RandomizedVerificationKey { inner: point })
    }
}

pub struct SpendAuthRandomizerVar {
    inner: Vec<UInt8<Fq>>,
}

impl AllocVar<Fr, Fq> for SpendAuthRandomizerVar {
    fn new_variable<T: std::borrow::Borrow<Fr>>(
        cs: impl Into<ark_relations::r1cs::Namespace<Fq>>,
        f: impl FnOnce() -> Result<T, SynthesisError>,
        mode: ark_r1cs_std::prelude::AllocationMode,
    ) -> Result<Self, SynthesisError> {
        let ns = cs.into();
        let cs = ns.cs();
        let inner: Fr = *f()?.borrow();
        match mode {
            AllocationMode::Constant => unimplemented!(),
            AllocationMode::Input => unimplemented!(),
            AllocationMode::Witness => {
                let spend_auth_randomizer_arr: [u8; 32] = inner.to_bytes();
                Ok(Self {
                    inner: UInt8::new_witness_vec(cs, &spend_auth_randomizer_arr)?,
                })
            }
        }
    }
}

impl R1CSVar<Fq> for SpendAuthRandomizerVar {
    type Value = Fr;

    fn cs(&self) -> ark_relations::r1cs::ConstraintSystemRef<Fq> {
        self.inner.cs()
    }

    fn value(&self) -> Result<Self::Value, SynthesisError> {
        let mut bytes = [0u8; 32];
        for (i, byte) in self.inner.iter().enumerate() {
            bytes[i] = byte.value()?;
        }
        Ok(Fr::from_bytes_checked(&bytes).expect("can convert bytes to Fr"))
    }
}