Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion g16ckt/src/gadgets/bn254/fq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,14 +297,24 @@ impl Fq {
&BigUint::from_str(Self::MODULUS_ADD_1_DIV_4).unwrap(),
)
}

/// Return a>b in standard form given inputs in montgomery form
pub fn greater_than<C: CircuitContext>(circuit: &mut C, a: &Fq, b: &Fq) -> WireId {
// First convert the inputs 'a' and 'b' back to standard form
let a = Fq::mul_by_constant_montgomery(circuit, a, &ark_bn254::Fq::ONE);
let b = Fq::mul_by_constant_montgomery(circuit, b, &ark_bn254::Fq::ONE);
// only now perform comparison
bigint::greater_than(circuit, &a, &b)
}
}

#[cfg(test)]
pub(super) mod tests {
use std::{array, iter};

use ark_ff::AdditiveGroup;
use rand::Rng;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha20Rng;
use test_log::test;
use tracing::trace;

Expand Down Expand Up @@ -680,6 +690,29 @@ pub(super) mod tests {
assert_eq!(result.output_value.value, expected_c);
}

#[test]
fn test_fq_sqrt_montgomery_roundtrip() {
let mut rng = ChaCha20Rng::seed_from_u64(42);
for _ in 0..5 {
let aa_v = Fq::random(&mut rng);
let sqrt_exists = aa_v.sqrt().is_some();

let aa_montgomery = Fq::as_montgomery(aa_v);
let input = FqInput::new([aa_montgomery]);

let result =
CircuitBuilder::streaming_execute::<_, _, FqOutput>(input, 10_000, |ctx, input| {
let [aa_wire] = input;
let sqrt = Fq::sqrt_montgomery(ctx, aa_wire);
Fq::square_montgomery(ctx, &sqrt)
});

let calc_aa_montgomery = result.output_value.value;

assert_eq!(sqrt_exists, calc_aa_montgomery == aa_montgomery);
}
}

#[test]
fn test_fq_multiplexer() {
let w = 1;
Expand Down
11 changes: 10 additions & 1 deletion g16ckt/src/gadgets/bn254/fq2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ use crate::{
CircuitContext, Gate, WireId,
circuit::WiresObject,
gadgets::{
bigint::{BigIntWires, select},
basic,
bigint::{self, BigIntWires, select},
bn254::{fp254impl::Fp254Impl, fq::Fq},
},
};
Expand Down Expand Up @@ -444,6 +445,14 @@ impl Fq2 {

Fq2::from_components(c0_final, c1_final)
}

/// Return a>b in standard form given inputs in montgomery form
pub fn greater_than<C: CircuitContext>(circuit: &mut C, a: &Fq2, b: &Fq2) -> WireId {
let c1_equal = bigint::equal(circuit, a.c1(), b.c1());
let c1_greater = Fq::greater_than(circuit, a.c1(), b.c1());
let c0_greater = Fq::greater_than(circuit, a.c0(), b.c0());
basic::selector(circuit, c0_greater, c1_greater, c1_equal)
}
}

#[cfg(test)]
Expand Down
Loading
Loading