Skip to content

Commit

Permalink
make vm::simulate() return Result<_> instead of (_, _, maybe_err)
Browse files Browse the repository at this point in the history
  • Loading branch information
jan-ferdinand committed Jun 14, 2023
1 parent 809f9b1 commit f52e4a9
Show file tree
Hide file tree
Showing 9 changed files with 89 additions and 219 deletions.
5 changes: 1 addition & 4 deletions triton-vm/benches/prove_fib_100.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,8 @@ fn prove_fib_100(criterion: &mut Criterion) {
prof_stop!(maybe_profiler, "parse program");
let public_input = [100].map(BFieldElement::new).to_vec();
prof_start!(maybe_profiler, "generate AET");
let (aet, output, err) = simulate(&program, public_input.clone(), vec![]);
let (aet, output) = simulate(&program, public_input.clone(), vec![]).unwrap();
prof_stop!(maybe_profiler, "generate AET");
if let Some(error) = err {
panic!("The VM encountered the following problem: {error}");
}

let parameters = StarkParameters::default();
let claim = Claim {
Expand Down
5 changes: 1 addition & 4 deletions triton-vm/benches/prove_halt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,8 @@ fn prove_halt(_criterion: &mut Criterion) {

// witness
prof_start!(maybe_profiler, "generate AET");
let (aet, output, err) = simulate(&program, vec![], vec![]);
let (aet, output) = simulate(&program, vec![], vec![]).unwrap();
prof_stop!(maybe_profiler, "generate AET");
if let Some(error) = err {
panic!("The VM encountered the following problem: {error}");
}

let cycle_count = aet.processor_trace.nrows();
let parameters = StarkParameters::default();
Expand Down
5 changes: 1 addition & 4 deletions triton-vm/benches/verify_halt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,7 @@ fn verify_halt(criterion: &mut Criterion) {
.map_err(|e| panic!("Could not load proof from disk: {e:?}"))
.unwrap()
} else {
let (aet, _, err) = simulate(&program, vec![], vec![]);
if let Some(error) = err {
panic!("The VM encountered the following problem: {error}");
}
let (aet, _) = simulate(&program, vec![], vec![]).unwrap();
maybe_cycle_count = Some(aet.processor_trace.nrows());
let proof = Stark::prove(&parameters, &claim, &aet, &mut None);
save_proof(filename, proof.clone())
Expand Down
51 changes: 22 additions & 29 deletions triton-vm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,18 +46,16 @@ pub fn prove_from_source(
source_code: &str,
public_input: &[u64],
secret_input: &[u64],
) -> (StarkParameters, Proof) {
) -> Result<(StarkParameters, Proof)> {
let canonical_representation_error =
"input must contain only elements in canonical representation, i.e., \
elements smaller than the prime field's modulus 2^64 - 2^32 + 1.";
assert!(
public_input.iter().all(|&e| e <= BFieldElement::MAX),
"Public {canonical_representation_error}"
);
assert!(
secret_input.iter().all(|&e| e <= BFieldElement::MAX),
"Secret {canonical_representation_error}"
);
if public_input.iter().any(|&e| e > BFieldElement::MAX) {
bail!("Public {canonical_representation_error})");
}
if secret_input.iter().any(|&e| e > BFieldElement::MAX) {
bail!("Secret {canonical_representation_error}");
}

// Convert the public and secret inputs to BFieldElements.
let public_input = public_input
Expand All @@ -70,22 +68,20 @@ pub fn prove_from_source(
.collect::<Vec<_>>();

// Parse the Triton assembly into a program.
let program = Program::from_code(source_code).unwrap();
let program = Program::from_code(source_code)?;

// Generate
// - the witness required for proof generation, i.e., the Algebraic Execution Trace (AET),
// - the (public) output of the program, and
// - an error, if the program crashes.
let (aet, public_output, maybe_error) =
vm::simulate(&program, public_input.clone(), secret_input);

// Check for VM crashes, for example due to failing `assert` instructions or an out-of-bounds
// instruction pointer. Crashes can occur if any of the two inputs does not conform to the
// program, or because of a bug in the program, among other things.
// - the witness required for proof generation, i.e., the Algebraic Execution Trace (AET), and
// - the (public) output of the program.
//
// Crashes in the VM can occur for many reasons. For example:
// - due to failing `assert` instructions,
// - due to an out-of-bounds instruction pointer,
// - if the program does not terminate gracefully, _i.e._, with instruction `halt`,
// - if any of the two inputs does not conform to the program,
// - because of a bug in the program, among other things.
// If the VM crashes, proof generation will fail.
if let Some(error) = maybe_error {
panic!("Execution error: {error}");
}
let (aet, public_output) = vm::simulate(&program, public_input.clone(), secret_input)?;

// Hash the program to obtain its digest.
let program_digest = Tip5::hash(&program);
Expand All @@ -104,7 +100,7 @@ pub fn prove_from_source(
// Generate the proof.
let proof = Stark::prove(&parameters, &claim, &aet, &mut None);

(parameters, proof)
Ok((parameters, proof))
}

/// A convenience function for proving a [`Claim`] and the program that claim corresponds to.
Expand All @@ -119,11 +115,7 @@ pub fn prove(
if program_digest != claim.program_digest {
bail!("Program digest must match claimed program digest.");
}
let (aet, public_output, maybe_error) =
vm::simulate(program, claim.input.clone(), secret_input.to_vec());
if let Some(error) = maybe_error {
bail!("Execution error: {error}");
}
let (aet, public_output) = vm::simulate(program, claim.input.clone(), secret_input.to_vec())?;
if public_output != claim.output {
bail!("Program output must match claimed program output.");
}
Expand Down Expand Up @@ -174,7 +166,8 @@ mod public_interface_tests {
17174585125955027015,
];

let (parameters, proof) = prove_from_source(source_code, &public_input, &secret_input);
let (parameters, proof) =
prove_from_source(source_code, &public_input, &secret_input).unwrap();
assert_eq!(
StarkParameters::default(),
parameters,
Expand Down
17 changes: 2 additions & 15 deletions triton-vm/src/shared_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,7 @@ pub fn parse_setup_simulate(
let program = program.expect("Program must parse.");

prof_start!(maybe_profiler, "simulate");
let (aet, stdout, err) = simulate(&program, public_input, secret_input);
if let Some(error) = err {
panic!("The VM encountered the following problem: {error}");
}
let (aet, stdout) = simulate(&program, public_input, secret_input).unwrap();
prof_stop!(maybe_profiler, "simulate");

(aet, stdout)
Expand Down Expand Up @@ -94,17 +91,7 @@ impl SourceCodeAndInput {
.collect()
}

#[deprecated(since = "0.19.0", note = "use `simulate` instead")]
pub fn run(&self) -> Vec<BFieldElement> {
let program = Program::from_code(&self.source_code).expect("Could not load source code");
let (_, output, err) = simulate(&program, self.public_input(), self.secret_input());
if let Some(e) = err {
panic!("Running the program failed: {e}")
}
output
}

pub fn simulate(&self) -> (AlgebraicExecutionTrace, Vec<BFieldElement>, Option<Error>) {
pub fn simulate(&self) -> Result<(AlgebraicExecutionTrace, Vec<BFieldElement>)> {
let program = Program::from_code(&self.source_code).expect("Could not load source code.");
simulate(&program, self.public_input(), self.secret_input())
}
Expand Down
13 changes: 2 additions & 11 deletions triton-vm/src/stark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -957,17 +957,8 @@ pub(crate) mod triton_stark_tests {
public_input: Vec<BFieldElement>,
secret_input: Vec<BFieldElement>,
) -> (AlgebraicExecutionTrace, Vec<BFieldElement>) {
let program = Program::from_code(code);

assert!(program.is_ok(), "program parses correctly");
let program = program.unwrap();

let (aet, stdout, err) = simulate(&program, public_input, secret_input);
if let Some(error) = err {
panic!("The VM encountered the following problem: {error}");
}

(aet, stdout)
let program = Program::from_code(code).unwrap();
simulate(&program, public_input, secret_input).unwrap()
}

pub fn parse_simulate_pad(
Expand Down
2 changes: 1 addition & 1 deletion triton-vm/src/table/master_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1407,7 +1407,7 @@ mod master_table_tests {

#[test]
fn smallest_possible_padded_height_is_correct_test() {
let (_, proof) = crate::prove_from_source("halt", &[], &[]);
let (_, proof) = crate::prove_from_source("halt", &[], &[]).unwrap();
let parameters = StarkParameters::default();
let smallest_padded_height_exp = proof.padded_height(&parameters).ilog2();
let smallest_padded_height_exp: usize = smallest_padded_height_exp.try_into().unwrap();
Expand Down
4 changes: 2 additions & 2 deletions triton-vm/src/table/processor_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2965,7 +2965,7 @@ mod constraint_polynomial_tests {
fn print_simple_processor_table_row_test() {
let code = "push 2 push -1 add assert halt";
let program = Program::from_code(code).unwrap();
let (aet, _, _) = simulate(&program, vec![], vec![]);
let (aet, _) = simulate(&program, vec![], vec![]).unwrap();
println!();
for row in aet.processor_trace.rows() {
println!("{}", ProcessorTraceRow { row });
Expand Down Expand Up @@ -3291,7 +3291,7 @@ mod constraint_polynomial_tests {

#[test]
fn division_by_zero_is_impossible_test() {
let (_aet, _out, err) = SourceCodeAndInput::without_input("div").simulate();
let err = SourceCodeAndInput::without_input("div").simulate().err();
let Some(err) = err else {
panic!("Dividing by 0 must fail.");
};
Expand Down
Loading

0 comments on commit f52e4a9

Please sign in to comment.