-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.rs
More file actions
556 lines (495 loc) · 16.4 KB
/
main.rs
File metadata and controls
556 lines (495 loc) · 16.4 KB
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! Lambda VM CLI - execute, prove, and verify RISC-V programs.
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Instant;
use clap::{Parser, Subcommand, ValueHint};
#[global_allocator]
static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
use executor::{
elf::{Elf, SymbolTable},
flamegraph::FlamegraphGenerator,
vm::execution::Executor,
};
use prover::VmProof;
use stark::proof::options::GoldilocksCubicProofOptions;
/// Polls jemalloc `stats.allocated` every 10ms from a background thread,
/// tracking the high-water mark. Near-zero overhead because jemalloc uses
/// thread-local caches — `epoch::advance()` just merges cached counters.
#[cfg(feature = "jemalloc-stats")]
mod heap_tracker {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::thread;
use std::time::Duration;
use tikv_jemalloc_ctl::{epoch, stats};
pub struct HeapTracker {
stop: Arc<AtomicBool>,
peak: Arc<AtomicUsize>,
handle: Option<thread::JoinHandle<()>>,
}
impl HeapTracker {
pub fn start() -> Self {
let stop = Arc::new(AtomicBool::new(false));
let peak = Arc::new(AtomicUsize::new(0));
let stop_clone = stop.clone();
let peak_clone = peak.clone();
let handle = thread::spawn(move || {
while !stop_clone.load(Ordering::Relaxed) {
// Refresh jemalloc's cached stats
epoch::advance().ok();
if let Ok(allocated) = stats::allocated::read() {
peak_clone.fetch_max(allocated, Ordering::Relaxed);
}
thread::sleep(Duration::from_millis(10));
}
// One final sample after stop signal
epoch::advance().ok();
if let Ok(allocated) = stats::allocated::read() {
peak_clone.fetch_max(allocated, Ordering::Relaxed);
}
});
Self {
stop,
peak,
handle: Some(handle),
}
}
pub fn stop(mut self) -> usize {
self.shutdown();
self.peak.load(Ordering::Relaxed)
}
fn shutdown(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(h) = self.handle.take() {
h.join().ok();
}
}
}
impl Drop for HeapTracker {
fn drop(&mut self) {
self.shutdown();
}
}
}
#[derive(Parser)]
#[command(author, version, about = "Lambda VM - RISC-V zkVM", long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Execute an ELF program without generating a proof
Execute {
/// Path to the ELF file
#[arg(value_parser, value_hint = ValueHint::FilePath)]
elf: PathBuf,
/// Path to the private input file
#[arg(long, value_hint = ValueHint::FilePath)]
private_input: Option<PathBuf>,
/// Generate flamegraph folded stacks to file
#[arg(long, value_hint = ValueHint::FilePath)]
flamegraph: Option<PathBuf>,
},
/// Generate a proof for an ELF program
Prove {
/// Path to the ELF file
#[arg(value_parser, value_hint = ValueHint::FilePath)]
elf: PathBuf,
/// Output path for the proof bundle
#[arg(short, long, value_hint = ValueHint::FilePath)]
output: PathBuf,
/// Path to the private input file
#[arg(long, value_hint = ValueHint::FilePath)]
private_input: Option<PathBuf>,
/// Blowup factor (power of 2). Higher = fewer queries, smaller proof, slower proving.
#[arg(long, default_value = "2")]
blowup: Option<u8>,
/// Print proving time
#[arg(long)]
time: bool,
/// Execute one pre-pass outside the timer and print dynamic instruction count
#[arg(long)]
cycles: bool,
/// Build traces and print total main-trace field elements (rows × columns summed across
/// all tables) and aux-trace field elements (committed EF columns × rows)
#[arg(long)]
elements: bool,
},
/// Verify a proof bundle
Verify {
/// Path to the proof bundle file
#[arg(value_parser, value_hint = ValueHint::FilePath)]
proof: PathBuf,
/// Path to the ELF file (required for DECODE table verification)
#[arg(value_parser, value_hint = ValueHint::FilePath)]
elf: PathBuf,
/// Blowup factor used during proving (must match)
#[arg(long, default_value = "2")]
blowup: Option<u8>,
/// Print verification time
#[arg(long)]
time: bool,
},
/// Count main-trace and aux-trace field elements without proving
CountElements {
/// Path to the ELF file
#[arg(value_parser, value_hint = ValueHint::FilePath)]
elf: PathBuf,
/// Path to the private input file
#[arg(long, value_hint = ValueHint::FilePath)]
private_input: Option<PathBuf>,
},
}
fn main() -> ExitCode {
env_logger::init();
let cli = Cli::parse();
match cli.command {
Commands::Execute {
elf,
private_input,
flamegraph,
} => cmd_execute(elf, private_input, flamegraph),
Commands::Prove {
elf,
output,
private_input,
blowup,
time,
cycles,
elements,
} => cmd_prove(elf, output, private_input, blowup, time, cycles, elements),
Commands::Verify {
proof,
elf,
blowup,
time,
} => cmd_verify(proof, elf, blowup, time),
Commands::CountElements { elf, private_input } => cmd_count_elements(elf, private_input),
}
}
fn read_private_input(path: Option<&PathBuf>) -> Result<Vec<u8>, String> {
match path {
Some(path) => {
eprintln!("Reading private input file...");
std::fs::read(path).map_err(|e| format!("Failed to read private input file: {e}"))
}
None => Ok(vec![]),
}
}
fn cmd_execute(
elf_path: PathBuf,
private_input_path: Option<PathBuf>,
flamegraph_path: Option<PathBuf>,
) -> ExitCode {
let elf_data = match std::fs::read(&elf_path) {
Ok(data) => data,
Err(e) => {
eprintln!("Failed to read ELF file: {}", e);
return ExitCode::FAILURE;
}
};
let program = match Elf::load(&elf_data) {
Ok(p) => p,
Err(e) => {
eprintln!("Failed to load ELF program: {:?}", e);
return ExitCode::FAILURE;
}
};
let private_inputs = match read_private_input(private_input_path.as_ref()) {
Ok(inputs) => inputs,
Err(e) => {
eprintln!("{e}");
return ExitCode::FAILURE;
}
};
let mut executor = match Executor::new(&program, private_inputs) {
Ok(e) => e,
Err(e) => {
eprintln!("Failed to create executor: {:?}", e);
return ExitCode::FAILURE;
}
};
// Set up flamegraph generator if requested
let mut generator = flamegraph_path.as_ref().map(|_| {
let symbols = SymbolTable::parse(&elf_data);
FlamegraphGenerator::new(symbols, program.entry_point)
});
// Execute in chunks, processing logs only if generating flamegraph
loop {
let logs = match executor.resume() {
Ok(logs) => logs,
Err(e) => {
eprintln!("Execution failed: {:?}", e);
return ExitCode::FAILURE;
}
};
match logs {
Some(logs) => {
if let Some(ref mut fg) = generator {
let logs: Vec<_> = logs.to_vec();
if let Err(e) = fg.process_logs(&logs, &executor.instructions) {
eprintln!("Failed to process logs for flamegraph: {:?}", e);
return ExitCode::FAILURE;
}
}
}
None => break,
}
}
if let Err(e) = executor.finish() {
eprintln!("Failed to finish execution: {:?}", e);
return ExitCode::FAILURE;
}
// Write flamegraph output if requested
if let (Some(output_path), Some(generator)) = (flamegraph_path, generator) {
let file = match File::create(&output_path) {
Ok(f) => f,
Err(e) => {
eprintln!("Failed to create flamegraph output file: {}", e);
return ExitCode::FAILURE;
}
};
let mut writer = BufWriter::new(file);
if let Err(e) = generator.write_folded(&mut writer) {
eprintln!("Failed to write flamegraph output: {:?}", e);
return ExitCode::FAILURE;
}
eprintln!(
"Flamegraph written to {:?} ({} instructions)",
output_path,
generator.total_instructions()
);
}
ExitCode::SUCCESS
}
fn cmd_prove(
elf_path: PathBuf,
output_path: PathBuf,
private_input_path: Option<PathBuf>,
blowup: Option<u8>,
time: bool,
cycles: bool,
elements: bool,
) -> ExitCode {
eprintln!("Reading ELF file...");
let elf_data = match std::fs::read(&elf_path) {
Ok(data) => data,
Err(e) => {
eprintln!("Failed to read ELF file: {}", e);
return ExitCode::FAILURE;
}
};
let private_inputs = match read_private_input(private_input_path.as_ref()) {
Ok(inputs) => inputs,
Err(e) => {
eprintln!("{e}");
return ExitCode::FAILURE;
}
};
// Pre-pass: execute once outside the timer to count dynamic instructions.
// Mirrors SP1's cycle-count pass so both provers report the same kind of
// number without inflating the measured proving time.
let cycle_count = if cycles {
let program = match Elf::load(&elf_data) {
Ok(p) => p,
Err(e) => {
eprintln!("Failed to load ELF for cycle count: {:?}", e);
return ExitCode::FAILURE;
}
};
let executor = match Executor::new(&program, private_inputs.clone()) {
Ok(e) => e,
Err(e) => {
eprintln!("Failed to create executor for cycle count: {:?}", e);
return ExitCode::FAILURE;
}
};
match executor.run() {
Ok(result) => Some(result.logs.len() as u64),
Err(e) => {
eprintln!("Execution failed during cycle count: {:?}", e);
return ExitCode::FAILURE;
}
}
} else {
None
};
// Pre-pass: build traces and count field elements without running the proof.
let element_count = if elements {
match prover::count_elements(&elf_data, &private_inputs) {
Ok(counts) => Some(counts),
Err(e) => {
eprintln!("Failed to count elements: {:?}", e);
return ExitCode::FAILURE;
}
}
} else {
None
};
#[cfg(feature = "jemalloc-stats")]
let tracker = heap_tracker::HeapTracker::start();
#[cfg(all(feature = "jemalloc-stats", feature = "instruments"))]
stark::instruments::set_heap_reader(|| {
tikv_jemalloc_ctl::epoch::advance().ok();
tikv_jemalloc_ctl::stats::allocated::read().ok()
});
let start = Instant::now();
let proof = match blowup {
Some(b) => {
let opts = match GoldilocksCubicProofOptions::with_blowup(b) {
Ok(opts) => opts,
Err(e) => {
eprintln!("Invalid proof options: {e}");
return ExitCode::FAILURE;
}
};
eprintln!(
"Generating proof (blowup={b}, queries={})...",
opts.fri_number_of_queries
);
prover::prove_with_options_and_inputs(
&elf_data,
&private_inputs,
&opts,
&Default::default(),
)
}
None => {
eprintln!("Generating proof...");
prover::prove_with_inputs(&elf_data, &private_inputs)
}
};
let prove_elapsed = start.elapsed();
let proof = match proof {
Ok(proof) => proof,
Err(e) => {
eprintln!("Proof generation failed: {}", e);
return ExitCode::FAILURE;
}
};
eprintln!("Writing proof...");
let file = match File::create(&output_path) {
Ok(f) => f,
Err(e) => {
eprintln!("Failed to create output file: {}", e);
return ExitCode::FAILURE;
}
};
let mut writer = BufWriter::new(file);
let bytes = match bincode::serialize(&proof) {
Ok(b) => b,
Err(e) => {
eprintln!("Failed to serialize proof: {}", e);
return ExitCode::FAILURE;
}
};
if let Err(e) = writer.write_all(&bytes) {
eprintln!("Failed to write proof: {}", e);
return ExitCode::FAILURE;
}
eprintln!("Proof written to {:?}", output_path);
if let Some(c) = cycle_count {
println!("Cycles: {}", c);
}
if let Some((main, aux)) = element_count {
println!("Elements: {}", main);
println!("Aux elements (EF-cols): {}", aux);
}
if time {
println!("Proving time: {:.3}s", prove_elapsed.as_secs_f64());
}
#[cfg(feature = "jemalloc-stats")]
{
let peak_bytes = tracker.stop();
println!("Peak heap: {} MB", peak_bytes / (1024 * 1024));
}
ExitCode::SUCCESS
}
fn cmd_verify(proof_path: PathBuf, elf_path: PathBuf, blowup: Option<u8>, time: bool) -> ExitCode {
eprintln!("Reading ELF file...");
let elf_data = match std::fs::read(&elf_path) {
Ok(data) => data,
Err(e) => {
eprintln!("Failed to read ELF file: {}", e);
return ExitCode::FAILURE;
}
};
eprintln!("Reading proof...");
let proof_bytes = match std::fs::read(&proof_path) {
Ok(b) => b,
Err(e) => {
eprintln!("Failed to read proof file: {}", e);
return ExitCode::FAILURE;
}
};
let proof: VmProof = match bincode::deserialize(&proof_bytes) {
Ok(p) => p,
Err(e) => {
eprintln!("Failed to deserialize proof: {}", e);
return ExitCode::FAILURE;
}
};
eprintln!("Verifying proof...");
let start = Instant::now();
let result = match blowup {
Some(b) => {
let opts = match GoldilocksCubicProofOptions::with_blowup(b) {
Ok(opts) => opts,
Err(e) => {
eprintln!("Invalid proof options: {e}");
return ExitCode::FAILURE;
}
};
prover::verify_with_options(&proof, &elf_data, &opts, None)
}
None => prover::verify(&proof, &elf_data),
};
let verify_elapsed = start.elapsed();
let result = match result {
Ok(valid) => valid,
Err(e) => {
eprintln!("Verification error: {}", e);
return ExitCode::FAILURE;
}
};
if result {
eprintln!("Verification succeeded!");
if time {
println!("Verification time: {:.3}s", verify_elapsed.as_secs_f64());
}
ExitCode::SUCCESS
} else {
eprintln!("Verification failed!");
ExitCode::FAILURE
}
}
fn cmd_count_elements(elf_path: PathBuf, private_input_path: Option<PathBuf>) -> ExitCode {
let elf_data = match std::fs::read(&elf_path) {
Ok(data) => data,
Err(e) => {
eprintln!("Failed to read ELF file: {}", e);
return ExitCode::FAILURE;
}
};
let private_inputs = match read_private_input(private_input_path.as_ref()) {
Ok(inputs) => inputs,
Err(e) => {
eprintln!("{e}");
return ExitCode::FAILURE;
}
};
match prover::count_elements(&elf_data, &private_inputs) {
Ok((main, aux)) => {
println!("Elements: {}", main);
println!("Aux elements (EF-cols): {}", aux);
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("Failed to count elements: {:?}", e);
ExitCode::FAILURE
}
}
}