valida_vm_api_linux_x86/
lib.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
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
//! # Valida VM API
//!
//! Lita’s Valida zk-VM stack sets a new standard in zero-knowledge proving,
//! leading in speed, efficiency, modularity and development productivity.
//!
//! See [Valida documentation](https://lita.gitbook.io/lita-documentation)
//!
//! This crate is a wrapper around `valida` executable and facilitates
//! usage of `valida` by providing Rust API for
//! running, proving and verification of Valida programs.
//!
//! Two examples are attached.
//! The first one proves `program1`. The other one proves `program2`.
//! Their sources and prebuilt versions are included in the crate
//! in the folder `test_data`.
//!
//! `program1` reads an integer from stdin, increments it and prints result to stdout.
//!
//! `program2` just unconditionally terminates execution with `__valida_builtin_fail()`.
//!
//! **IMPORTANT**
//!
//! Before copying the examples change `valida_vm_api` to
//! `valida-vm-api-linux-x86` / `valida-vm-api-linux-arm` in use declarations
//!
//! # Example 1
//!
//! ```
//! use valida_vm_api::*;
//! use tempfile::NamedTempFile;
//! use tmpfile_helper::*;
//! use std::fs;
//! use std::path::Path;
//! use std::default;
//!
//! let program = Path::new("test_data").join("program1");
//!
//! let valida = create_valida().unwrap();
//!
//! // stdin is an ASCII representation of character 'a'
//! let stdin = bytes_to_temp_file("a".as_bytes()).unwrap();
//! let stdout = NamedTempFile::new().unwrap();
//!
//! let run_status = valida.run(
//!     &program,
//!     stdout.as_ref(),
//!     stdin.as_ref(),
//!     Default::default(),
//!     Default::default());
//!
//! // Check that program terminated with success, i.e. STOP opcode
//! assert_eq!(run_status, RunStatus::TerminatedWithStop);
//!
//! let stdout_content = fs::read_to_string(stdout.as_ref()).unwrap();
//! // Check that stdout contains ('a' + 1)
//! assert_eq!(stdout_content, "b");
//!
//! let proof = NamedTempFile::new().unwrap();
//! let prove_status = valida.prove(
//!     &program, proof.as_ref(),
//!     stdin.as_ref(),
//!     Default::default(),
//!     Default::default(),
//!     Default::default());
//!
//! // Proving of a program that terminates with STOP opcode must succeed
//! assert_eq!(prove_status, ProveStatus::Success);
//!
//! let verify_status_correct_statement = valida.verify(
//!     &program,
//!     proof.as_ref(),
//!     stdout.as_ref(),
//!     Default::default(),
//!     Default::default(),
//!     Default::default());
//!
//! // Verification of a program that terminates with STOP opcode and outputs 'b' must succeed
//! assert_eq!(verify_status_correct_statement, VerifyStatus::Success);
//!
//! let incorrect_stdout = bytes_to_temp_file("c".as_bytes()).unwrap();
//! let verify_status_incorrect_statement = valida.verify(
//!     &program,
//!     proof.as_ref(),
//!     incorrect_stdout.as_ref(),
//!     Default::default(),
//!     Default::default(),
//!     Default::default());
//!
//! // Verification of a program that terminates with STOP opcode
//! // and outputs something else than `b` must fail
//! assert_eq!(verify_status_incorrect_statement, VerifyStatus::Failure);
//! ```
//!
//! # Example 2
//!
//! ```
//! use valida_vm_api::*;
//! use tempfile::NamedTempFile;
//! use tmpfile_helper::*;
//! use std::fs;
//! use std::path::Path;
//! use std::default;
//!
//! let program = Path::new("test_data").join("program2");
//!
//! let valida = create_valida().unwrap();
//!
//! // stdin and stdout do not matter for this program
//! let stdin = bytes_to_temp_file("".as_bytes()).unwrap();
//! let stdout = NamedTempFile::new().unwrap();
//!
//! let run_status = valida.run(
//!     &program,
//!     stdout.as_ref(),
//!     stdin.as_ref(),
//!     Default::default(),
//!     Default::default());
//!
//! // Check that program terminated with failure, i.e. FAIL opcode
//! assert_eq!(run_status, RunStatus::TerminatedWithFail);
//!
//! let proof = NamedTempFile::new().unwrap();
//! let prove_status = valida.prove(
//!     &program,
//!     proof.as_ref(),
//!     stdin.as_ref(),
//!     Default::default(),
//!     Default::default(),
//!     Default::default());
//!
//! // Proving of a program that terminates with STOP opcode may succeed
//! assert!(prove_status == ProveStatus::Success || prove_status == ProveStatus::Failure);
//!
//! let verify_status = valida.verify(
//!     &program,
//!     proof.as_ref(),
//!     stdout.as_ref(),
//!     Default::default(),
//!     Default::default(),
//!     Default::default());
//!
//! // Verification of a program that terminates with FAIL opcode must fail
//! assert_eq!(verify_status, VerifyStatus::Failure);
//! ```

use std::fs::remove_file;
use std::io::{self};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};

pub mod optional_arg;
use optional_arg::*;

mod extract_executable;
use extract_executable::*;

pub mod tmpfile_helper;

pub use tempfile;

/// The key structure that supports methods for running, proving and verification.
pub struct Valida {
    path: PathBuf,
}

#[derive(PartialEq, Eq, Debug)]
pub enum RunStatus {
    TerminatedWithStop,
    TerminatedWithFail,
    VMError,
}

#[derive(PartialEq, Eq, Debug)]
pub enum ProveStatus {
    Success,
    Failure,
    VMError,
}

#[derive(PartialEq, Eq, Debug)]
pub enum VerifyStatus {
    Success,
    Failure,
    VMError,
}

#[derive(PartialEq, Eq, Debug)]
pub enum PreprocessStatus {
    Success,
    Failure,
    VMError,
}

impl Valida {
    fn execute(
        &self,
        command: &str,
        optional_args: &[&str],
        mandatory_args: &[&str],
    ) -> std::io::Result<ExitStatus> {
        let args = [&[command], optional_args, mandatory_args];

        Command::new(self.path.as_os_str())
            .args(args.to_vec().concat())
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .status()
    }

    /// This is a wrapper for [valida run --fast](https://lita.gitbook.io/lita-documentation/quick-start/valida-zk-vm#executing-input-from-a-file)
    /// See `create_valida` documentation for example usage.
    pub fn run(
        &self,
        program: &Path,
        stdout: &Path,
        stdin: &Path,
        initial_fp: Option<InitialFp>,
        memory_backend: Option<MemoryBackend>,
    ) -> RunStatus {
        let binding = prepare_args(&[
            as_dyn_arg(&initial_fp),
            as_dyn_arg(&Some(FastMode(true))),
            as_dyn_arg(&memory_backend),
        ]);
        let optional_args: Vec<_> = binding.iter().map(String::as_str).collect();

        let status = self
            .execute(
                "run",
                &optional_args,
                &[
                    program.to_str().unwrap(),
                    stdout.to_str().unwrap(),
                    stdin.to_str().unwrap(),
                ],
            )
            .map(|t| t.code());

        match status {
            Ok(Some(code)) => match code {
                0 => RunStatus::TerminatedWithStop,
                1 => RunStatus::TerminatedWithFail,
                _ => RunStatus::VMError,
            },
            _ => RunStatus::VMError,
        }
    }

    /// This is a wrapper for [valida prove](https://lita.gitbook.io/lita-documentation/quick-start/valida-zk-vm#proving-input-from-a-file)
    /// See `create_valida` documentation for example usage.
    pub fn prove(
        &self,
        program: &Path,
        proof: &Path,
        stdin: &Path,
        proving_key: Option<ProvingKey>,
        initial_fp: Option<InitialFp>,
        memory_backend: Option<MemoryBackend>,
    ) -> ProveStatus {
        let binding = prepare_args(&[
            as_dyn_arg(&proving_key),
            as_dyn_arg(&initial_fp),
            as_dyn_arg(&memory_backend),
        ]);
        let optional_args: Vec<_> = binding.iter().map(String::as_str).collect();

        let status = self
            .execute(
                "prove",
                &optional_args,
                &[
                    program.to_str().unwrap(),
                    proof.to_str().unwrap(),
                    stdin.to_str().unwrap(),
                ],
            )
            .map(|t| t.code());

        match status {
            Ok(Some(code)) => match code {
                0 => ProveStatus::Success,
                _ => ProveStatus::Failure,
            },
            _ => ProveStatus::VMError,
        }
    }

    /// This is a wrapper for [valida verify](https://lita.gitbook.io/lita-documentation/quick-start/valida-zk-vm#verifying-a-proof)
    /// See `create_valida` documentation for example usage.
    pub fn verify(
        &self,
        program: &Path,
        proof: &Path,
        stdout: &Path,
        verifying_key: Option<VerifyingKey>,
        initial_fp: Option<InitialFp>,
        memory_backend: Option<MemoryBackend>,
    ) -> VerifyStatus {
        let binding = prepare_args(&[
            as_dyn_arg(&verifying_key),
            as_dyn_arg(&initial_fp),
            as_dyn_arg(&memory_backend),
        ]);
        let optional_args: Vec<_> = binding.iter().map(String::as_str).collect();

        let status = self
            .execute(
                "verify",
                &optional_args,
                &[
                    program.to_str().unwrap(),
                    proof.to_str().unwrap(),
                    stdout.to_str().unwrap(),
                ],
            )
            .map(|t| t.code());

        match status {
            Ok(Some(code)) => match code {
                0 => VerifyStatus::Success,
                _ => VerifyStatus::Failure,
            },
            _ => VerifyStatus::VMError,
        }
    }

    /// This is a wrapper for [valida preprocess](https://lita.gitbook.io/lita-documentation/advanced-usage/zk-vm-advanced-usage#separate-preprocessing-stage)
    pub fn preprocess(
        &self,
        program: &Path,
        name: String,
        memory_backend: Option<MemoryBackend>,
    ) -> PreprocessStatus {
        let binding = prepare_args(&[as_dyn_arg(&memory_backend)]);
        let optional_args: Vec<_> = binding.iter().map(String::as_str).collect();

        let status = self
            .execute(
                "verify",
                &optional_args,
                &[program.to_str().unwrap(), name.as_str()],
            )
            .map(|t| t.code());

        match status {
            Ok(Some(code)) => match code {
                0 => PreprocessStatus::Success,
                _ => PreprocessStatus::Failure,
            },
            _ => PreprocessStatus::VMError,
        }
    }
}

/// This function creates a wrapper for `valida` executable.
///
/// Call this function just once in your program.
/// Calling it is expensive because it extracts the bundled `valida binary`
/// and decompresses it to a temporary file.
pub fn create_valida() -> io::Result<Valida> {
    let pathbuf = extract_executable()?;

    Ok(Valida { path: pathbuf })
}

impl Drop for Valida {
    fn drop(&mut self) {
        remove_file(self.path.as_mut_os_str()).unwrap();
    }
}