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
//! R1CS binary format parser/serializer
//!
//! Format specification: https://github.com/iden3/r1csfile/blob/master/doc/r1cs_bin_format.md

use std::io::{Error, ErrorKind, Read, Result, Write};

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};

const MAGIC: &[u8; 4] = b"r1cs";
const VERSION: u32 = 1;

#[derive(Debug, PartialEq, Eq)]
pub struct R1csFile<const FS: usize> {
    pub header: Header<FS>,
    pub constraints: Constraints<FS>,
    pub map: WireMap,
}

impl<const FS: usize> R1csFile<FS> {
    pub fn read<R: Read>(mut r: R) -> Result<Self> {
        let mut magic = [0u8; 4];
        r.read_exact(&mut magic)?;
        if magic != *MAGIC {
            return Err(Error::new(ErrorKind::InvalidData, "Invalid magic number"));
        }

        let version = r.read_u32::<LittleEndian>()?;
        if version != VERSION {
            return Err(Error::new(ErrorKind::InvalidData, "Unsupported version"));
        }

        // TODO: Should we support multiple sections of the same type?
        //
        // For now assume there is at most one section of each kind.
        let num_sections = r.read_u32::<LittleEndian>()?;

        let mut header = None;
        let mut constraints = None;
        let mut map = None;

        for _ in 0..num_sections {
            let section_header = SectionHeader::read(&mut r)?;

            match section_header.ty {
                SectionType::Header => {
                    if let None = header {
                        header = Some(Header::read(&mut r)?);
                    } else {
                        return Err(Error::new(
                            ErrorKind::InvalidData,
                            "Duplicated header section found",
                        ));
                    }
                }
                SectionType::Constraint => {
                    if let None = constraints {
                        constraints = Some(Constraints::read(&mut r, &section_header)?);
                    } else {
                        return Err(Error::new(
                            ErrorKind::InvalidData,
                            "Duplicated constraints section found",
                        ));
                    }
                }
                SectionType::Wire2LabelIdMap => {
                    if let None = map {
                        map = Some(WireMap::read(&mut r, &section_header)?);
                    } else {
                        return Err(Error::new(
                            ErrorKind::InvalidData,
                            "Duplicated wire map section found",
                        ));
                    }
                }
                SectionType::Unknown => {
                    return Err(Error::new(ErrorKind::InvalidData, "Unknown section"))
                }
            }
        }

        match (header, constraints, map) {
            (Some(header), Some(constraints), Some(map)) => Ok(R1csFile {
                header,
                constraints,
                map,
            }),
            (None, _, _) => Err(Error::new(ErrorKind::InvalidData, "Missing header section")),
            (_, None, _) => Err(Error::new(
                ErrorKind::InvalidData,
                "Missing constraints section",
            )),
            (_, _, None) => Err(Error::new(
                ErrorKind::InvalidData,
                "Missing wire map section",
            )),
        }
    }

    pub fn write<W: Write>(&self, mut w: W) -> Result<()> {
        w.write_all(MAGIC)?;
        w.write_u32::<LittleEndian>(VERSION)?;
        w.write_u32::<LittleEndian>(3)?; // number of sections

        self.header.write(&mut w)?;
        self.constraints.write(&mut w)?;
        self.map.write(&mut w)?;

        Ok(())
    }
}

#[derive(Debug, PartialEq, Eq)]
pub struct Header<const FS: usize> {
    pub prime: FieldElement<FS>,
    pub n_wires: u32,
    pub n_pub_out: u32,
    pub n_pub_in: u32,
    pub n_prvt_in: u32,
    pub n_labels: u64,
    pub n_constraints: u32,
}

impl<const FS: usize> Header<FS> {
    fn read<R: Read>(mut r: R) -> Result<Self> {
        let field_size = r.read_u32::<LittleEndian>()?;
        if field_size != FS as u32 {
            return Err(Error::new(ErrorKind::InvalidData, "Wrong field size"));
        }

        let prime = FieldElement::read(&mut r)?;
        let n_wires = r.read_u32::<LittleEndian>()?;
        let n_pub_out = r.read_u32::<LittleEndian>()?;
        let n_pub_in = r.read_u32::<LittleEndian>()?;
        let n_prvt_in = r.read_u32::<LittleEndian>()?;
        let n_labels = r.read_u64::<LittleEndian>()?;
        let n_constraints = r.read_u32::<LittleEndian>()?;

        Ok(Header {
            prime,
            n_wires,
            n_pub_out,
            n_pub_in,
            n_prvt_in,
            n_labels,
            n_constraints,
        })
    }

    fn write<W: Write>(&self, mut w: W) -> Result<()> {
        let header = SectionHeader {
            ty: SectionType::Header,
            size: 6 * 4 + 8 + FS as u64,
        };

        header.write(&mut w)?;

        w.write_u32::<LittleEndian>(FS as u32)?;
        self.prime.write(&mut w)?;
        w.write_u32::<LittleEndian>(self.n_wires)?;
        w.write_u32::<LittleEndian>(self.n_pub_out)?;
        w.write_u32::<LittleEndian>(self.n_pub_in)?;
        w.write_u32::<LittleEndian>(self.n_prvt_in)?;
        w.write_u64::<LittleEndian>(self.n_labels)?;
        w.write_u32::<LittleEndian>(self.n_constraints)?;

        Ok(())
    }
}

#[derive(Debug, Default, PartialEq, Eq)]
pub struct Constraints<const FS: usize>(pub Vec<Constraint<FS>>);

impl<const FS: usize> Constraints<FS> {
    fn read<R: Read>(r: R, section_header: &SectionHeader) -> Result<Self> {
        let mut section_data = r.take(section_header.size);

        let mut constraints = Vec::new();
        while section_data.limit() > 0 {
            let c = Constraint::read(&mut section_data)?;
            constraints.push(c);
        }

        Ok(Constraints(constraints))
    }

    fn write<W: Write>(&self, mut w: W) -> Result<()> {
        let header = SectionHeader {
            ty: SectionType::Constraint,
            size: self.0.iter().map(|c| c.size()).sum::<usize>() as u64,
        };

        header.write(&mut w)?;

        for c in &self.0 {
            c.write(&mut w)?;
        }

        Ok(())
    }
}

#[derive(Debug, Default, PartialEq, Eq)]
pub struct Constraint<const FS: usize>(
    pub Vec<(FieldElement<FS>, u32)>,
    pub Vec<(FieldElement<FS>, u32)>,
    pub Vec<(FieldElement<FS>, u32)>,
);

impl<const FS: usize> Constraint<FS> {
    fn read<R: Read>(mut r: R) -> Result<Self> {
        let a = Self::read_combination(&mut r)?;
        let b = Self::read_combination(&mut r)?;
        let c = Self::read_combination(&mut r)?;

        Ok(Constraint(a, b, c))
    }

    fn read_combination<R: Read>(mut r: R) -> Result<Vec<(FieldElement<FS>, u32)>> {
        let n = r.read_u32::<LittleEndian>()?;
        let mut factors = Vec::new();

        for _ in 0..n {
            let index = r.read_u32::<LittleEndian>()?;
            let factor = FieldElement::read(&mut r)?;
            factors.push((factor, index));
        }

        Ok(factors)
    }

    fn write<W: Write>(&self, mut w: W) -> Result<()> {
        let mut write = |comb: &Vec<(FieldElement<FS>, u32)>| -> Result<()> {
            w.write_u32::<LittleEndian>(comb.len() as u32)?;

            for (factor, index) in comb {
                w.write_u32::<LittleEndian>(*index)?;
                factor.write(&mut w)?;
            }

            Ok(())
        };

        write(&self.0)?;
        write(&self.1)?;
        write(&self.2)?;

        Ok(())
    }

    fn size(&self) -> usize {
        let a = self.0.iter().map(|(f, _)| f.len()).sum::<usize>() + self.0.len() * 4;
        let b = self.1.iter().map(|(f, _)| f.len()).sum::<usize>() + self.1.len() * 4;
        let c = self.2.iter().map(|(f, _)| f.len()).sum::<usize>() + self.2.len() * 4;

        a + b + c + 3 * 4
    }
}

#[derive(Debug, Default, PartialEq, Eq)]
pub struct WireMap(pub Vec<u64>);

impl WireMap {
    fn read<R: Read>(mut r: R, section_header: &SectionHeader) -> Result<Self> {
        let num_labels = section_header.size / 8;
        let mut label_ids = Vec::with_capacity(num_labels as usize);

        for _ in 0..num_labels {
            label_ids.push(r.read_u64::<LittleEndian>()?);
        }

        Ok(WireMap(label_ids))
    }

    fn write<W: Write>(&self, mut w: W) -> Result<()> {
        let header = SectionHeader {
            ty: SectionType::Wire2LabelIdMap,
            size: self.0.len() as u64 * 8,
        };

        header.write(&mut w)?;

        for label_id in &self.0 {
            w.write_u64::<LittleEndian>(*label_id)?;
        }

        Ok(())
    }
}

struct SectionHeader {
    ty: SectionType,
    size: u64,
}

impl SectionHeader {
    fn read<R: Read>(mut r: R) -> Result<Self> {
        let ty = SectionType::read(&mut r)?;
        let size = r.read_u64::<LittleEndian>()?;

        Ok(SectionHeader { ty, size })
    }

    fn write<W: Write>(&self, mut w: W) -> Result<()> {
        w.write_u32::<LittleEndian>(self.ty as u32)?;
        w.write_u64::<LittleEndian>(self.size)?;

        Ok(())
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(u32)]
enum SectionType {
    Header = 1,
    Constraint = 2,
    Wire2LabelIdMap = 3,
    Unknown = u32::MAX,
}

impl SectionType {
    fn read<R: Read>(mut r: R) -> Result<Self> {
        let num = r.read_u32::<LittleEndian>()?;

        let ty = match num {
            1 => SectionType::Header,
            2 => SectionType::Constraint,
            3 => SectionType::Wire2LabelIdMap,
            _ => SectionType::Unknown,
        };

        Ok(ty)
    }
}

#[derive(Debug, PartialEq, Eq)]
pub struct FieldElement<const FS: usize>([u8; FS]);

impl<const FS: usize> FieldElement<FS> {
    pub fn as_bytes(&self) -> &[u8] {
        &self.0[..]
    }

    fn read<R: Read>(mut r: R) -> Result<Self> {
        let mut buf = [0; FS];
        r.read_exact(&mut buf)?;

        Ok(FieldElement(buf))
    }

    fn write<W: Write>(&self, mut w: W) -> Result<()> {
        w.write_all(&self.0[..])
    }
}

impl<const FS: usize> From<[u8; FS]> for FieldElement<FS> {
    fn from(array: [u8; FS]) -> Self {
        FieldElement(array)
    }
}

impl<const FS: usize> std::ops::Deref for FieldElement<FS> {
    type Target = [u8; FS];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use hex_literal::hex;

    #[test]
    fn test_parse() {
        let data = std::fs::read("tests/simple_circuit.r1cs").unwrap();
        let file = R1csFile::<32>::read(data.as_slice()).unwrap();

        // Thanks to https://github.com/poma/zkutil/blob/5d789ab3757dcd79eff244ca4998d7ab91683b40/src/r1cs_reader.rs#L188
        assert_eq!(
            file.header.prime,
            FieldElement::from(hex!(
                "010000f093f5e1439170b97948e833285d588181b64550b829a031e1724e6430"
            ))
        );
        assert_eq!(file.header.n_wires, 7);
        assert_eq!(file.header.n_pub_out, 1);
        assert_eq!(file.header.n_pub_in, 2);
        assert_eq!(file.header.n_prvt_in, 3);
        assert_eq!(file.header.n_labels, 0x03e8);
        assert_eq!(file.header.n_constraints, 3);

        assert_eq!(file.constraints.0.len(), 3);
        assert_eq!(file.constraints.0[0].0.len(), 2);
        assert_eq!(file.constraints.0[0].0[0].1, 5);
        assert_eq!(
            file.constraints.0[0].0[0].0,
            FieldElement::from(hex!(
                "0300000000000000000000000000000000000000000000000000000000000000"
            )),
        );
        assert_eq!(file.constraints.0[2].1[0].1, 0);
        assert_eq!(
            file.constraints.0[2].1[0].0,
            FieldElement::from(hex!(
                "0600000000000000000000000000000000000000000000000000000000000000"
            )),
        );
        assert_eq!(file.constraints.0[1].2.len(), 0);

        assert_eq!(file.map.0.len(), 7);
        assert_eq!(file.map.0[1], 3);
    }

    #[test]
    fn test_serialize() {
        let data = std::fs::read("tests/test_circuit.r1cs").unwrap();
        let parsed_file = R1csFile::<32>::read(data.as_slice()).unwrap();
        let mut serialized_file = Vec::new();
        parsed_file.write(&mut serialized_file).unwrap();

        // std::fs::write("simple_circuit_new.r1cs", &serialized_file).unwrap();

        assert_eq!(data.len(), serialized_file.len());
        assert_eq!(data, serialized_file);
    }
}