Skip to content

Commit

Permalink
test: add small circuit testing U128x128Var::round_down_to_amount
Browse files Browse the repository at this point in the history
  • Loading branch information
redshiftzero authored and cronokirby committed Dec 8, 2023
1 parent d990822 commit 3eaea83
Showing 1 changed file with 72 additions and 0 deletions.
72 changes: 72 additions & 0 deletions crates/core/num/src/fixpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -729,6 +729,8 @@ mod test {
use proptest::prelude::*;
use rand_core::OsRng;

use crate::Amount;

use super::*;

proptest! {
Expand Down Expand Up @@ -1313,4 +1315,74 @@ mod test {
panic!("should not be able to verify proof");
}
}

proptest! {
#![proptest_config(ProptestConfig::with_cases(5))]
#[test]
fn round_down_to_amount(
a_int in any::<u128>(),
a_frac in any::<u128>(),
) {
let a = U128x128(
U256([a_frac, a_int])
);

let expected_c = a.round_down().try_into().expect("should be able to round down OOC");

let circuit = TestRoundDownCircuit {
a,
c: expected_c,
};

let (pk, vk) = TestRoundDownCircuit::generate_test_parameters();
let mut rng = OsRng;

let proof = Groth16::<Bls12_377, LibsnarkReduction>::prove(&pk, circuit, &mut rng)
.expect("should be able to form proof");

let proof_result = Groth16::<Bls12_377, LibsnarkReduction>::verify(
&vk,
&expected_c.to_field_elements().unwrap(),
&proof,
);
assert!(proof_result.is_ok());
}
}

struct TestRoundDownCircuit {
a: U128x128,

// `c` is expected to be `a` rounded down to an `Amount`
pub c: Amount,
}

impl ConstraintSynthesizer<Fq> for TestRoundDownCircuit {
fn generate_constraints(
self,
cs: ConstraintSystemRef<Fq>,
) -> ark_relations::r1cs::Result<()> {
let a_var = U128x128Var::new_witness(cs.clone(), || Ok(self.a))?;
let c_public_var = AmountVar::new_input(cs, || Ok(self.c))?;
let c_var = a_var.round_down_to_amount()?;
c_var.enforce_equal(&c_public_var)?;
Ok(())
}
}

impl TestRoundDownCircuit {
fn generate_test_parameters() -> (ProvingKey<Bls12_377>, VerifyingKey<Bls12_377>) {
let num: [u8; 32] = [0u8; 32];
let a = U128x128::from_bytes(num);
let c: Amount = a
.round_down()
.try_into()
.expect("should be able to round down OOC");
let circuit = TestRoundDownCircuit { a, c };
let (pk, vk) = Groth16::<Bls12_377, LibsnarkReduction>::circuit_specific_setup(
circuit, &mut OsRng,
)
.expect("can perform circuit specific setup");
(pk, vk)
}
}
}

0 comments on commit 3eaea83

Please sign in to comment.