arnaucube
arnaucube/circom-compatPublic Self-hosted repository
circom-compat/src/circom/r1cs_reader.rs
src/circom/r1cs_reader.rsRaw
  1//! R1CS circom file reader
  2//! Copied from https://github.com/poma/zkutil
  3use byteorder::{LittleEndian, ReadBytesExt};
  4use std::io::{Error, ErrorKind, Result};
  5
  6use ark_ec::PairingEngine;
  7use ark_ff::FromBytes;
  8use ark_std::io::Read;
  9
 10use super::{ConstraintVec, Constraints};
 11
 12#[derive(Clone, Debug)]
 13pub struct R1CS<E: PairingEngine> {
 14    pub num_inputs: usize,
 15    pub num_aux: usize,
 16    pub num_variables: usize,
 17    pub constraints: Vec<Constraints<E>>,
 18    pub wire_mapping: Option<Vec<usize>>,
 19}
 20
 21impl<E: PairingEngine> From<R1CSFile<E>> for R1CS<E> {
 22    fn from(file: R1CSFile<E>) -> Self {
 23        let num_inputs = (1 + file.header.n_pub_in + file.header.n_pub_out) as usize;
 24        let num_variables = file.header.n_wires as usize;
 25        let num_aux = num_variables - num_inputs;
 26        R1CS {
 27            num_aux,
 28            num_inputs,
 29            num_variables,
 30            constraints: file.constraints,
 31            wire_mapping: Some(file.wire_mapping.iter().map(|e| *e as usize).collect()),
 32        }
 33    }
 34}
 35
 36pub struct R1CSFile<E: PairingEngine> {
 37    pub version: u32,
 38    pub header: Header,
 39    pub constraints: Vec<Constraints<E>>,
 40    pub wire_mapping: Vec<u64>,
 41}
 42
 43impl<E: PairingEngine> R1CSFile<E> {
 44    pub fn new<R: Read>(mut reader: R) -> Result<R1CSFile<E>> {
 45        let mut magic = [0u8; 4];
 46        reader.read_exact(&mut magic)?;
 47        if magic != [0x72, 0x31, 0x63, 0x73] {
 48            // magic = "r1cs"
 49            return Err(Error::new(ErrorKind::InvalidData, "Invalid magic number"));
 50        }
 51
 52        let version = reader.read_u32::<LittleEndian>()?;
 53        if version != 1 {
 54            return Err(Error::new(ErrorKind::InvalidData, "Unsupported version"));
 55        }
 56
 57        let _num_sections = reader.read_u32::<LittleEndian>()?;
 58
 59        // todo: rewrite this to support different section order and unknown sections
 60        // todo: handle sec_size correctly
 61        let _sec_type = reader.read_u32::<LittleEndian>()?;
 62        let sec_size = reader.read_u64::<LittleEndian>()?;
 63
 64        let header = Header::new(&mut reader, sec_size)?;
 65        let _sec_type = reader.read_u32::<LittleEndian>()?;
 66        let _sec_size = reader.read_u64::<LittleEndian>()?;
 67        let constraints = read_constraints::<&mut R, E>(&mut reader, &header)?;
 68
 69        let _sec_type = reader.read_u32::<LittleEndian>()?;
 70        let sec_size = reader.read_u64::<LittleEndian>()?;
 71        let wire_mapping = read_map(&mut reader, sec_size, &header)?;
 72
 73        Ok(R1CSFile {
 74            version,
 75            header,
 76            constraints,
 77            wire_mapping,
 78        })
 79    }
 80}
 81
 82pub struct Header {
 83    pub field_size: u32,
 84    pub prime_size: Vec<u8>,
 85    pub n_wires: u32,
 86    pub n_pub_out: u32,
 87    pub n_pub_in: u32,
 88    pub n_prv_in: u32,
 89    pub n_labels: u64,
 90    pub n_constraints: u32,
 91}
 92
 93impl Header {
 94    fn new<R: Read>(mut reader: R, size: u64) -> Result<Header> {
 95        let field_size = reader.read_u32::<LittleEndian>()?;
 96        if field_size != 32 {
 97            return Err(Error::new(
 98                ErrorKind::InvalidData,
 99                "This parser only supports 32-byte fields",
100            ));
101        }
102
103        if size != 32 + field_size as u64 {
104            return Err(Error::new(
105                ErrorKind::InvalidData,
106                "Invalid header section size",
107            ));
108        }
109
110        let mut prime_size = vec![0u8; field_size as usize];
111        reader.read_exact(&mut prime_size)?;
112
113        if prime_size
114            != hex::decode("010000f093f5e1439170b97948e833285d588181b64550b829a031e1724e6430")
115                .unwrap()
116        {
117            return Err(Error::new(
118                ErrorKind::InvalidData,
119                "This parser only supports bn256",
120            ));
121        }
122
123        Ok(Header {
124            field_size,
125            prime_size,
126            n_wires: reader.read_u32::<LittleEndian>()?,
127            n_pub_out: reader.read_u32::<LittleEndian>()?,
128            n_pub_in: reader.read_u32::<LittleEndian>()?,
129            n_prv_in: reader.read_u32::<LittleEndian>()?,
130            n_labels: reader.read_u64::<LittleEndian>()?,
131            n_constraints: reader.read_u32::<LittleEndian>()?,
132        })
133    }
134}
135
136fn read_constraint_vec<R: Read, E: PairingEngine>(mut reader: R) -> Result<ConstraintVec<E>> {
137    let n_vec = reader.read_u32::<LittleEndian>()? as usize;
138    let mut vec = Vec::with_capacity(n_vec);
139    for _ in 0..n_vec {
140        vec.push((
141            reader.read_u32::<LittleEndian>()? as usize,
142            E::Fr::read(&mut reader)?,
143        ));
144    }
145    Ok(vec)
146}
147
148fn read_constraints<R: Read, E: PairingEngine>(
149    mut reader: R,
150    header: &Header,
151) -> Result<Vec<Constraints<E>>> {
152    // todo check section size
153    let mut vec = Vec::with_capacity(header.n_constraints as usize);
154    for _ in 0..header.n_constraints {
155        vec.push((
156            read_constraint_vec::<&mut R, E>(&mut reader)?,
157            read_constraint_vec::<&mut R, E>(&mut reader)?,
158            read_constraint_vec::<&mut R, E>(&mut reader)?,
159        ));
160    }
161    Ok(vec)
162}
163
164fn read_map<R: Read>(mut reader: R, size: u64, header: &Header) -> Result<Vec<u64>> {
165    if size != header.n_wires as u64 * 8 {
166        return Err(Error::new(
167            ErrorKind::InvalidData,
168            "Invalid map section size",
169        ));
170    }
171    let mut vec = Vec::with_capacity(header.n_wires as usize);
172    for _ in 0..header.n_wires {
173        vec.push(reader.read_u64::<LittleEndian>()?);
174    }
175    if vec[0] != 0 {
176        return Err(Error::new(
177            ErrorKind::InvalidData,
178            "Wire 0 should always be mapped to 0",
179        ));
180    }
181    Ok(vec)
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187    use ark_bn254::{Bn254, Fr};
188
189    #[test]
190    fn sample() {
191        let data = hex_literal::hex!(
192            "
193        72316373
194        01000000
195        03000000
196        01000000 40000000 00000000
197        20000000
198        010000f0 93f5e143 9170b979 48e83328 5d588181 b64550b8 29a031e1 724e6430
199        07000000
200        01000000
201        02000000
202        03000000
203        e8030000 00000000
204        03000000
205        02000000 88020000 00000000
206        02000000
207        05000000 03000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
208        06000000 08000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
209        03000000
210        00000000 02000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
211        02000000 14000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
212        03000000 0C000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
213        02000000
214        00000000 05000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
215        02000000 07000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
216        03000000
217        01000000 04000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
218        04000000 08000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
219        05000000 03000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
220        02000000
221        03000000 2C000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
222        06000000 06000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
223        00000000
224        01000000
225        06000000 04000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
226        03000000
227        00000000 06000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
228        02000000 0B000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
229        03000000 05000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
230        01000000
231        06000000 58020000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
232        03000000 38000000 00000000
233        00000000 00000000
234        03000000 00000000
235        0a000000 00000000
236        0b000000 00000000
237        0c000000 00000000
238        0f000000 00000000
239        44010000 00000000
240    "
241        );
242
243        let file = R1CSFile::<Bn254>::new(&data[..]).unwrap();
244        assert_eq!(file.version, 1);
245
246        assert_eq!(file.header.field_size, 32);
247        assert_eq!(
248            file.header.prime_size,
249            hex::decode("010000f093f5e1439170b97948e833285d588181b64550b829a031e1724e6430")
250                .unwrap(),
251        );
252        assert_eq!(file.header.n_wires, 7);
253        assert_eq!(file.header.n_pub_out, 1);
254        assert_eq!(file.header.n_pub_in, 2);
255        assert_eq!(file.header.n_prv_in, 3);
256        assert_eq!(file.header.n_labels, 0x03e8);
257        assert_eq!(file.header.n_constraints, 3);
258
259        assert_eq!(file.constraints.len(), 3);
260        assert_eq!(file.constraints[0].0.len(), 2);
261        assert_eq!(file.constraints[0].0[0].0, 5);
262        assert_eq!(file.constraints[0].0[0].1, Fr::from(3));
263        assert_eq!(file.constraints[2].1[0].0, 0);
264        assert_eq!(file.constraints[2].1[0].1, Fr::from(6));
265        assert_eq!(file.constraints[1].2.len(), 0);
266
267        assert_eq!(file.wire_mapping.len(), 7);
268        assert_eq!(file.wire_mapping[1], 3);
269    }
270}