Skip to content

Commit

Permalink
prove and verify can proceed
Browse files Browse the repository at this point in the history
  • Loading branch information
Shuang Wu authored and Shuang Wu committed Oct 24, 2024
1 parent 629b843 commit 6171568
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 29 deletions.
29 changes: 17 additions & 12 deletions backend/src/stwo/circuit_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,14 @@ use stwo_prover::core::ColumnVec;

pub type PowdrComponent<'a, F: FieldElement> = FrameworkComponent<PowdrEval<'a, F>>;



pub struct PowdrCircuitTrace<'a, T> {
analyzed: Arc<Analyzed<T>>,
/// Callback to augment the witness in the later stages.
witgen_callback: Option<WitgenCallback<T>>,
/// The value of the witness columns, if set
witness: Option<&'a [(String, Vec<T>)]>,
pub witness: Option<&'a [(String, Vec<T>)]>,

pub elements: Option<Vec<(String, BaseColumn)>>,
}
Expand Down Expand Up @@ -91,12 +93,17 @@ impl<'a, T: FieldElement> PowdrCircuitTrace<'a, T> {
pub fn gen_trace(
self,
) -> ColumnVec<CircleEvaluation<SimdBackend, BaseField, BitReversedOrder>> {
let domain = CanonicCoset::new(self.analyzed.degree() as u32).circle_domain();
println!("degree log 2 is {:?}", self.analyzed.degree().ilog2());
let domain = CanonicCoset::new(self.analyzed.degree().ilog2()).circle_domain();
println!("domain size is {:?}", domain.size());
self.elements
.map(|elements| {
elements
.iter()
.map(|(_, base_column)| CircleEvaluation::new(domain, base_column.clone()))
.map(|(_, base_column)| {
println!("base_column is {:?}", base_column);
CircleEvaluation::new(domain, base_column.clone())
})
.collect()
})
.unwrap()
Expand All @@ -123,11 +130,12 @@ pub(crate) struct PowdrEval<'a, T> {

impl<'a, T: FieldElement> PowdrEval<'a, T> {
pub(crate) fn new(analyzed: Arc<Analyzed<T>>) -> Self {
let degree_log = analyzed.degree().ilog2();
Self {
analyzed,
witgen_callback: None,
witness: None,
log_n_rows: 0,
log_n_rows: degree_log,
// lookup_elements: unimplemented!(),
// claimed_sum: unimplemented!(),
// total_sum: unimplemented!(),
Expand Down Expand Up @@ -179,14 +187,6 @@ impl<'a, T: FieldElement> FrameworkEval for PowdrEval<'a, T> {
eval.add_constraint(expr);
});
}
let mut a = eval.next_trace_mask();
let mut b = eval.next_trace_mask();
for _ in 2..7 {
let c = eval.next_trace_mask();
eval.add_constraint(c.clone() - (a + b));
a = b;
b = c;
}
eval
}
}
Expand All @@ -213,21 +213,26 @@ fn to_stwo_expression<T: FieldElement, E: EvalAtRow>(
op,
right: powdr_rhe,
}) => {
println!("coming to BinaryOperation: left is {:?} \n, op is {:?} \n, right is {:?} \n", lhe, op, powdr_rhe);
let mut lhe = to_stwo_expression(lhe, eval);
let mut rhe = to_stwo_expression(powdr_rhe, eval);
println!("after recursion: lhe is {:?} \n, op is {:?} \n, rhe is {:?} \n", lhe, op, rhe);

match op {
AlgebraicBinaryOperator::Add => {
println!(
"This is the addition, lhe is {:?}, and rhe is {:?}",
lhe, rhe
);
println!("lhe + rhe is {:?}", lhe + rhe);
lhe + rhe
}
AlgebraicBinaryOperator::Sub => {
println!(
"This is the substraction, lhe is {:?}, and rhe is {:?}",
lhe, rhe
);
println!("lhe - rhe is {:?}", lhe - rhe);
lhe - rhe
}
AlgebraicBinaryOperator::Mul => {
Expand Down
8 changes: 7 additions & 1 deletion backend/src/stwo/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ use powdr_executor::witgen::WitgenCallback;
use powdr_number::FieldElement;
use prover::StwoProver;


mod circuit_builder;
mod prover;

use circuit_builder::PowdrCircuitTrace;
#[allow(dead_code)]
pub(crate) struct StwoProverFactory;

Expand Down Expand Up @@ -56,6 +57,11 @@ impl<T: FieldElement> Backend<T> for StwoProver<T> {
if prev_proof.is_some() {
return Err(Error::NoAggregationAvailable);
}
let circuit = PowdrCircuitTrace::new(self.analyzed.clone())
.with_witgen_callback(witgen_callback.clone())
.with_witness(witness);
print!("witness from powdr at the beginning..............\n {:?}", circuit.witness );
println!("Proving with witness: {:?}", witness);
self.prove(witness, witgen_callback);
unimplemented!()
}
Expand Down
43 changes: 29 additions & 14 deletions backend/src/stwo/prover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ use stwo_prover::core::pcs::{
};
use stwo_prover::core::poly::circle::{CanonicCoset, CircleEvaluation, PolyOps};
use stwo_prover::core::vcs::poseidon252_merkle::Poseidon252MerkleChannel;
use stwo_prover::core::air::Component;

use powdr_number::FieldElement;


#[allow(unused_variables)]
pub struct StwoProver<T> {
analyzed: Arc<Analyzed<T>>,
pub analyzed: Arc<Analyzed<T>>,
_fixed: Arc<Vec<(String, Vec<T>)>>,
/// Proving key placeholder
_proving_key: Option<()>,
Expand Down Expand Up @@ -59,14 +61,13 @@ impl<F: FieldElement> StwoProver<F> {
.with_witgen_callback(witgen_callback.clone())
.with_witness(witness)
.generate_stwo_circuit_trace();
//print!("witness from powdr {:?}", witness );
print!("witness from powdr {:?}", circuit.witness );

let circuitEval = PowdrEval::new(self.analyzed.clone())
.with_witgen_callback(witgen_callback.clone())
.with_witness(witness);

//Constraints that are to be proved
let component = PowdrComponent::new(&mut TraceLocationAllocator::default(), circuitEval);


// Precompute twiddles.
let twiddles = SimdBackend::precompute_twiddles(
Expand All @@ -76,6 +77,7 @@ impl<F: FieldElement> StwoProver<F> {
.circle_domain()
.half_coset,
);
println!("canonic coset size: {:?}", (self.analyzed.degree() as u32) + 1 + config.fri_config.log_blowup_factor);
println!("generate twiddles");
// Setup protocol.
let prover_channel = &mut Poseidon252Channel::default();
Expand All @@ -84,19 +86,32 @@ impl<F: FieldElement> StwoProver<F> {
config, &twiddles,
);
println!("generate prover channel");

let pretest_trace = PowdrCircuitTrace::new(self.analyzed.clone())
.with_witgen_callback(witgen_callback.clone())
.with_witness(witness)
.generate_stwo_circuit_trace();
println!("\n the trace after convert to circle domain is {:?} \n", pretest_trace.elements);

let trace = PowdrCircuitTrace::new(self.analyzed.clone())
.with_witgen_callback(witgen_callback)
.with_witness(witness)
.generate_stwo_circuit_trace()
.gen_trace();


let mut tree_builder = commitment_scheme.tree_builder();
tree_builder.extend_evals(trace);
tree_builder.commit(prover_channel);

//Constraints that are to be proved
let component = PowdrComponent::new(&mut TraceLocationAllocator::default(), circuitEval);

println!("created component!");

// println!("component eval is like this \n {} ",component.log_n_rows);
println!("component eval is like this \n {} ",component.log_n_rows);



//let start = Instant::now();
let proof = stwo_prover::core::prover::prove::<SimdBackend, Poseidon252MerkleChannel>(
Expand All @@ -106,24 +121,24 @@ impl<F: FieldElement> StwoProver<F> {
)
.unwrap();

// println!("proof generated!");
println!("proof generated!");
// let duration = start.elapsed();

// // Verify.
// let verifier_channel = &mut Poseidon252Channel::default();
// let commitment_scheme =
// &mut CommitmentSchemeVerifier::<Poseidon252MerkleChannel>::new(config);
let verifier_channel = &mut Poseidon252Channel::default();
let commitment_scheme =
&mut CommitmentSchemeVerifier::<Poseidon252MerkleChannel>::new(config);

// // Retrieve the expected column sizes in each commitment interaction, from the AIR.
// let sizes = component.trace_log_degree_bounds();
// commitment_scheme.commit(proof.commitments[0], &sizes[0], verifier_channel);
// Retrieve the expected column sizes in each commitment interaction, from the AIR.
let sizes = component.trace_log_degree_bounds();
commitment_scheme.commit(proof.commitments[0], &sizes[0], verifier_channel);

// println!("proving time for fibo length of {:?} is {:?}",fibonacci_y_length, duration);
// println!("proof size is {:?} bytes",proof.size_estimate());

// let verifystart = Instant::now();
// stwo_prover::core::prover::verify(&[&component], verifier_channel, commitment_scheme, proof).unwrap();
// let verifyduration = verifystart.elapsed();
stwo_prover::core::prover::verify(&[&component], verifier_channel, commitment_scheme, proof).unwrap();

// println!("verify time is {:?} ",verifyduration);

println!("prove_stwo in prover.rs is not complete yet");
Expand Down
3 changes: 2 additions & 1 deletion pipeline/src/test_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -523,8 +523,9 @@ pub fn test_stwo(file_name: &str, inputs: Vec<Mersenne31Field>) {
let mut pipeline = Pipeline::default()
.with_tmp_output()
.from_file(resolve_test_file(file_name))
.with_prover_inputs(inputs)
.with_prover_inputs(inputs.clone())
.with_backend(backend, None);
println!("inputs from test file {:?}", inputs);

// Generate a proof
let _proof = pipeline.compute_proof().cloned().unwrap();
Expand Down
3 changes: 2 additions & 1 deletion pipeline/tests/pil.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#[cfg(feature = "halo2")]
use powdr_number::Bn254Field;
use powdr_number::Mersenne31Field;
use powdr_number::GoldilocksField;
use powdr_pipeline::test_util::{
assert_proofs_fail_for_invalid_witnesses, assert_proofs_fail_for_invalid_witnesses_estark,
Expand Down Expand Up @@ -247,7 +248,7 @@ fn add() {
#[test]
fn stwo_add() {
let f = "pil/add.pil";
test_stwo(f, Default::default());
test_stwo(f, [Mersenne31Field::from(3), Mersenne31Field::from(4),Mersenne31Field::from(2)].to_vec());
}
#[test]
fn simple_div() {
Expand Down

0 comments on commit 6171568

Please sign in to comment.