-
Notifications
You must be signed in to change notification settings - Fork 86
/
mod.rs
188 lines (154 loc) · 6.67 KB
/
mod.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
182
183
184
185
186
187
188
use crate::sponge::{Absorb, CryptographicSponge, FieldElementSize};
use ark_ff::PrimeField;
use ark_r1cs_std::alloc::AllocVar;
use ark_r1cs_std::boolean::Boolean;
use ark_r1cs_std::fields::emulated_fp::params::{get_params, OptimizationType};
use ark_r1cs_std::fields::emulated_fp::{AllocatedEmulatedFpVar, EmulatedFpVar};
use ark_r1cs_std::fields::fp::{AllocatedFp, FpVar};
use ark_r1cs_std::uint8::UInt8;
use ark_r1cs_std::R1CSVar;
use ark_relations::lc;
use ark_relations::r1cs::{ConstraintSystemRef, LinearCombination, SynthesisError};
use ark_std::vec;
use ark_std::vec::Vec;
mod absorb;
pub use absorb::*;
/// Converts little-endian bits to a list of emulated elements.
pub fn bits_le_to_emulated<'a, F: PrimeField, CF: PrimeField>(
cs: ConstraintSystemRef<CF>,
all_emulated_bits_le: impl IntoIterator<Item = &'a Vec<Boolean<CF>>>,
) -> Result<Vec<EmulatedFpVar<F, CF>>, SynthesisError> {
let all_emulated_bits_le = all_emulated_bits_le.into_iter().collect::<Vec<_>>();
if all_emulated_bits_le.is_empty() {
return Ok(Vec::new());
}
let mut max_emulated_bits = 0usize;
for bits in &all_emulated_bits_le {
max_emulated_bits = max_emulated_bits.max(bits.len());
}
let mut lookup_table = Vec::<Vec<CF>>::new();
let mut cur = F::one();
for _ in 0..max_emulated_bits {
let repr = AllocatedEmulatedFpVar::<F, CF>::get_limbs_representations(
&cur,
OptimizationType::Constraints,
)?;
lookup_table.push(repr);
cur.double_in_place();
}
let params = get_params(
F::MODULUS_BIT_SIZE as usize,
CF::MODULUS_BIT_SIZE as usize,
OptimizationType::Constraints,
);
let mut output = Vec::with_capacity(all_emulated_bits_le.len());
for emulated_bits_le in all_emulated_bits_le {
let mut val = vec![CF::zero(); params.num_limbs];
let mut lc = vec![LinearCombination::<CF>::zero(); params.num_limbs];
for (j, bit) in emulated_bits_le.iter().enumerate() {
if bit.value().unwrap_or_default() {
for (k, val) in val.iter_mut().enumerate().take(params.num_limbs) {
*val += &lookup_table[j][k];
}
}
#[allow(clippy::needless_range_loop)]
for k in 0..params.num_limbs {
lc[k] = &lc[k] + bit.lc() * lookup_table[j][k];
}
}
let mut limbs = Vec::new();
for k in 0..params.num_limbs {
let gadget =
AllocatedFp::new_witness(ark_relations::ns!(cs, "alloc"), || Ok(val[k])).unwrap();
lc[k] = lc[k].clone() - (CF::one(), gadget.variable);
cs.enforce_constraint(lc!(), lc!(), lc[k].clone()).unwrap();
limbs.push(FpVar::<CF>::from(gadget));
}
output.push(EmulatedFpVar::<F, CF>::Var(
AllocatedEmulatedFpVar::<F, CF> {
cs: cs.clone(),
limbs,
num_of_additions_over_normal_form: CF::zero(),
is_in_the_normal_form: true,
target_phantom: Default::default(),
},
));
}
Ok(output)
}
/// Enables simple access to the "gadget" version of the sponge.
/// Simplifies trait bounds in downstream generic code.
pub trait SpongeWithGadget<CF: PrimeField>: CryptographicSponge {
/// The gadget version of `Self`.
type Var: CryptographicSpongeVar<CF, Self>;
}
/// The interface for a cryptographic sponge constraints on field `CF`.
/// A sponge can `absorb` or take in inputs and later `squeeze` or output bytes or field elements.
/// The outputs are dependent on previous `absorb` and `squeeze` calls.
pub trait CryptographicSpongeVar<CF: PrimeField, S: CryptographicSponge>: Clone {
/// Parameters used by the sponge.
type Parameters;
/// Initialize a new instance of the sponge.
fn new(cs: ConstraintSystemRef<CF>, params: &Self::Parameters) -> Self;
/// Returns a ref to the underlying constraint system the sponge is operating in.
fn cs(&self) -> ConstraintSystemRef<CF>;
/// Absorb an input into the sponge.
fn absorb(&mut self, input: &impl AbsorbGadget<CF>) -> Result<(), SynthesisError>;
/// Squeeze `num_bytes` bytes from the sponge.
fn squeeze_bytes(&mut self, num_bytes: usize) -> Result<Vec<UInt8<CF>>, SynthesisError>;
/// Squeeze `num_bit` bits from the sponge.
fn squeeze_bits(&mut self, num_bits: usize) -> Result<Vec<Boolean<CF>>, SynthesisError>;
/// Squeeze `sizes.len()` emulated field elements from the sponge, where the `i`-th element of
/// the output has size `sizes[i]`.
fn squeeze_emulated_field_elements_with_sizes<F: PrimeField>(
&mut self,
sizes: &[FieldElementSize],
) -> Result<(Vec<EmulatedFpVar<F, CF>>, Vec<Vec<Boolean<CF>>>), SynthesisError> {
if sizes.len() == 0 {
return Ok((Vec::new(), Vec::new()));
}
let cs = self.cs();
let mut total_bits = 0usize;
for size in sizes {
total_bits += size.num_bits::<F>();
}
let bits = self.squeeze_bits(total_bits)?;
let mut dest_bits = Vec::<Vec<Boolean<CF>>>::with_capacity(sizes.len());
let mut bits_window = bits.as_slice();
for size in sizes {
let num_bits = size.num_bits::<F>();
let emulated_bits_le = bits_window[..num_bits].to_vec();
bits_window = &bits_window[num_bits..];
dest_bits.push(emulated_bits_le);
}
let dest_gadgets = bits_le_to_emulated(cs, dest_bits.iter())?;
Ok((dest_gadgets, dest_bits))
}
/// Squeeze `num_elements` emulated field elements from the sponge.
fn squeeze_emulated_field_elements<F: PrimeField>(
&mut self,
num_elements: usize,
) -> Result<(Vec<EmulatedFpVar<F, CF>>, Vec<Vec<Boolean<CF>>>), SynthesisError> {
self.squeeze_emulated_field_elements_with_sizes::<F>(
vec![FieldElementSize::Full; num_elements].as_slice(),
)
}
/// Creates a new sponge with applied domain separation.
fn fork(&self, domain: &[u8]) -> Result<Self, SynthesisError> {
let mut new_sponge = self.clone();
let mut input = Absorb::to_sponge_bytes_as_vec(&domain.len());
input.extend_from_slice(domain);
let elems: Vec<CF> = input.to_sponge_field_elements_as_vec();
let elem_vars = elems
.into_iter()
.map(|elem| FpVar::Constant(elem))
.collect::<Vec<_>>();
new_sponge.absorb(&elem_vars)?;
Ok(new_sponge)
}
/// Squeeze `num_elements` field elements from the sponge.
fn squeeze_field_elements(
&mut self,
num_elements: usize,
) -> Result<Vec<FpVar<CF>>, SynthesisError>;
}