zkinterface/lib.rs
1//! # zkInterface, a standard tool for zero-knowledge interoperability
2//!
3//! zkInterface is a standard tool for zero-knowledge interoperability between different ZK DSLs, gadget libraries, and proving systems.
4//! The zkInterface project was born in the [ZKProof](https://zkproof.org/) community.
5//!
6//! ## Introduction
7//!
8//! 
9//!
10//! *zkInterface* is specification and associated tools for enabling interoperability between implementations of general-purpose zero-knowledge proof systems. It aims to facilitate interoperability between zero knowledge proof implementations, at the level of the low-constraint systems that represent the statements to be proven. Such constraint systems are generated by _frontends_ (e.g., by compilation from higher-level specifications), and are consumed by cryptographic _backends_ which generate and verify the proofs. The goal is to enable decoupling of frontends from backends, allowing application writers to choose the frontend most convenient for their functional and development needs and combine it with the backend that best matches their performance and security needs.
11//!
12//! The standard specifies the protocol for communicating constraint systems, for communicating variable assignments (for production of proofs), and for constructing constraint systems out of smaller building blocks (_gadgets_). These are specified using language-agnostic calling conventions and formats, to enable interoperability between different authors, frameworks and languages.
13//! A simple special case is monolithic representation of a whole constraint system and its variable assignments. However, there are a need for more richer and more nuanced forms of interoperability:
14//!
15//! * Precisely-specified statement semantics, variable representation and variable mapping
16//! * Witness reduction, from high-level witnesses to variable assignments
17//! * Gadgets interoperability, allowing components of constraint systems to be packaged in reusable and interoperable form
18//! * Procedural interoperability, allowing execution of complex code to facilitate the above
19//!
20//! # Examples
21//!
22//! zkInterface does not force a serialization method, it should be provided by the user - `serialize_small()` in this example.
23//!
24//! Create a `CircuitHeader`
25//!
26//! ```
27//! use zkinterface::producers::examples::{serialize_small, NEG_ONE};
28//! use zkinterface::KeyValue;
29//!
30//! let (x,y,zz) = (3,4,25);
31//!
32//! // variables ids 1,2 and 3 are used as instances variables
33//! let header = zkinterface::CircuitHeader {
34//! instance_variables: zkinterface::Variables {
35//! variable_ids: vec![1, 2, 3], // x, y, zz
36//! values: Some(serialize_small(&[x, y, zz])),
37//! },
38//! free_variable_id: 6,
39//! field_maximum: Some(serialize_small(&[NEG_ONE])),
40//! configuration: Some(vec![
41//! KeyValue::from(("Name", "example")),
42//! ]),
43//! };
44//! ```
45//!
46//! Create a Circuit Header
47//!
48//! ```
49//! let (x,y) = (3,4);
50//!
51//! use zkinterface::producers::examples::serialize_small;
52//!
53//! //variables ids 4 and 5 are used as witness variables
54//! let witness = zkinterface::Witness {
55//! assigned_variables: zkinterface::Variables {
56//! variable_ids: vec![4, 5], // xx, yy
57//! values: Some(serialize_small(&[
58//! x * x, // var_4 = xx = x^2
59//! y * y, // var_5 = yy = y^2
60//! ])),
61//! }
62//! };
63//! ```
64//!
65//! Create a `ConstraintSystem` from an R1CS vector
66//!
67//! ```
68//! let constraints_vec: &[((Vec<u64>, Vec<u8>), (Vec<u64>, Vec<u8>), (Vec<u64>, Vec<u8>))] = &[
69//! // (A ids values) * (B ids values) = (C ids values)
70//! ((vec![1], vec![1]), (vec![1], vec![1]), (vec![4], vec![1])), // x * x = xx
71//! ((vec![2], vec![1]), (vec![2], vec![1]), (vec![5], vec![1])), // y * y = yy
72//! ((vec![0], vec![1]), (vec![4, 5], vec![1, 1]), (vec![3], vec![1])), // 1 * (xx + yy) = z
73//! ];
74//!
75//! let constraints = zkinterface::ConstraintSystem::from(constraints_vec);
76//! ```
77//!
78//! ## The Statement Builder
79//!
80//! zkInterface provides a `StatementBuilder` to assists with constructing and storing a statement in zkInterface format.
81//!
82//!```
83//! use zkinterface::{StatementBuilder, Sink, WorkspaceSink, CircuitHeader, ConstraintSystem, Witness};
84//!
85//! // Create a workspace where to write zkInterafce files.
86//! let sink = WorkspaceSink::new("local/test_builder").unwrap();
87//! let mut builder = StatementBuilder::new(sink);
88//!
89//! // Use variables, construct a constraint system, and a witness.
90//! let var_ids = builder.allocate_vars(3);
91//! let cs = ConstraintSystem::default();
92//! let witness = Witness::default();
93//!
94//! builder.finish_header().unwrap();
95//! builder.push_witness(witness).unwrap();
96//! builder.push_constraints(cs).unwrap();
97//!```
98//!
99//! ## The Simulator
100//!
101//! zkInterface provides a Simulator to check entire constraint system and output what constraints are violated, if any.
102//!
103//!```
104//! # use zkinterface::producers::examples::{example_circuit_header, example_witness, example_constraints};
105//! use zkinterface::consumers::simulator::Simulator;
106//!
107//! pub fn simulate() -> zkinterface::Result<()> {
108//! let header = example_circuit_header();
109//! let witness = example_witness();
110//! let cs = example_constraints();
111//!
112//! let mut simulator = Simulator::default();
113//! simulator.ingest_header(&header)?;
114//! simulator.ingest_witness(&witness)?;
115//! simulator.ingest_constraint_system(&cs)?;
116//! Ok(())
117//! }
118//!```
119//!
120//! ## The Validator
121//!
122//! zkInterface provides a Validator to check the syntax and the semantics of the provided parameters and return a list of violations, if any.
123//!
124//!```
125//! # use zkinterface::producers::examples::{example_circuit_header, example_witness, example_constraints};
126//! use zkinterface::consumers::validator::Validator;
127//!
128//! let header = example_circuit_header();
129//! let witness = example_witness();
130//! let constraints = example_constraints();
131//!
132//! let mut validator = Validator::new_as_prover();
133//! validator.ingest_header(&header);
134//! validator.ingest_witness(&witness);
135//! validator.ingest_constraint_system(&constraints);
136//!
137//! let violations = validator.get_violations();
138//! if violations.len() > 0 {
139//! eprintln!("Violations:\n- {}\n", violations.join("\n- "));
140//! }
141//!```
142//!
143//! In addition to the library, a CLI tool is provided. The CLI tool can execute the following commands:
144//! - `zkif example` Create example statements.
145//! - `zkif cat` Write .zkif files to stdout.
146//! - `zkif to-json` Convert to JSON on a single line.
147//! - `zkif to-yaml` Convert to YAML.
148//! - `zkif explain` Print the content in a human-readable form.
149//! - `zkif validate` Validate the format and semantics of a statement, as seen by a verifier.
150//! - `zkif simulate` Simulate a proving system as prover by verifying that the statement is true.
151//! - `zkif stats` Calculate statistics about the circuit.
152//! - `zkif clean` Clean workspace by deleting all *.zkif files in it.
153
154#[allow(unused_imports)]
155/// All CLI related logic.
156pub mod cli;
157
158/// Various zkInterface consumers including: validator, simulator, stats, reader and a workspace
159pub mod consumers;
160
161/// Various zkInterface producers including: examples, builder, gadget_caller and workspace
162pub mod producers;
163
164/// Fully-owned version of each data structure
165/// These structures may be easier to work with than the no-copy versions found in zkinterface_generated and Reader
166pub mod structs;
167
168/// Automatically generated by the FlatBuffers compiler
169#[allow(unused_imports)]
170pub mod zkinterface_generated;
171
172#[doc(hidden)]
173pub extern crate flatbuffers;
174pub extern crate serde;
175pub use consumers::{
176 reader::Reader,
177 workspace::Workspace,
178};
179pub use producers::{
180 builder::{Sink, StatementBuilder},
181 workspace::{WorkspaceSink, clean_workspace},
182};
183pub use structs::{
184 header::CircuitHeader,
185 command::Command,
186 constraints::{ConstraintSystem, BilinearConstraint},
187 keyvalue::KeyValue,
188 message::Message,
189 messages::Messages,
190 variables::Variables,
191 witness::Witness,
192};
193
194// Common definitions.
195use std::error::Error;
196
197/// A result type with a predefined error type
198pub type Result<T> = std::result::Result<T, Box<dyn Error>>;