-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.rs
More file actions
391 lines (345 loc) · 11.4 KB
/
Copy pathmain.rs
File metadata and controls
391 lines (345 loc) · 11.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
//! 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,
/// 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,
/// Blowup factor (power of 2). Higher = fewer queries, smaller proof, slower proving.
#[arg(long)]
blowup: Option<u8>,
/// Print timing breakdown
#[arg(long)]
time: 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)]
blowup: Option<u8>,
/// Print timing breakdown
#[arg(long)]
time: bool,
},
}
fn main() -> ExitCode {
let cli = Cli::parse();
match cli.command {
Commands::Execute { elf, flamegraph } => cmd_execute(elf, flamegraph),
Commands::Prove {
elf,
output,
blowup,
time,
} => cmd_prove(elf, output, blowup, time),
Commands::Verify {
proof,
elf,
blowup,
time,
} => cmd_verify(proof, elf, blowup, time),
}
}
fn cmd_execute(elf_path: 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 mut executor = match Executor::new(&program, vec![]) {
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, 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;
}
};
#[cfg(feature = "jemalloc-stats")]
let tracker = heap_tracker::HeapTracker::start();
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(&elf_data, vec![], &opts, &Default::default())
}
None => {
eprintln!("Generating proof...");
prover::prove(&elf_data)
}
};
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 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 => 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
}
}