mul works

This commit is contained in:
Dmitry Vagner 2023-04-26 18:10:40 -07:00
parent 6599c90a6e
commit 13c653bc53
3 changed files with 47 additions and 22 deletions

View File

@ -29,6 +29,15 @@ impl<T: FieldExt> Add for Curve<T> {
type Output = Self;
fn add(self, other: Self) -> Self {
if self == Curve::<T>::unit() {
return other;
}
if other == Curve::<T>::unit() {
return self;
}
if self == -other {
return Curve::<T>::unit();
}
let m = if self == other {
T::new(3) * self.x * self.x / (T::new(2) * self.y)
} else {
@ -69,26 +78,39 @@ impl CurveGroup for Curve<BN254> {
};
}
// impl<T: FieldExt: Add> Mul<i32> for Curve {
// type Output = Curve;
impl<T> Mul<i32> for Curve<T>
where
T: FieldExt,
Curve<T>: CurveGroup,
{
type Output = Curve<T>;
// fn mul(self, other: i32) -> Self {
// let mut result: Curve = self;
// if other.is_negative() {
// result = -result;
// }
// let mut multiplier = result;
// let mut exp = other.unsigned_abs() as usize;
// while exp > 0 {
// if exp % 2 == 1 {
// result = result + multiplier;
// }
// exp >>= 1;
// multiplier = multiplier + multiplier;
// }
// result
// }
// }
fn mul(self, other: i32) -> Self {
if other == 0 {
return Curve::<T>::unit();
}
if self == Curve::<T>::unit() {
return Curve::<T>::unit();
}
let mut x: Curve<T> = self;
if other.is_negative() {
x = -x;
}
let mut result = Curve::<T>::unit();
let mut exp = other.unsigned_abs() as usize;
while exp > 0 {
if exp % 2 == 1 {
result = result + x;
}
exp >>= 1;
x = x + x;
}
println!("result: {:?}", result);
result
}
}
/// The twisted curve consists of pairs
/// (x, y): (Fp2<BN254>, Fp2<BN254>) | y^2 = x^3 + 3/(9 + i)

View File

@ -202,7 +202,7 @@ fn test_bn_final_exponent() -> Result<()> {
}
fn pairing_input() -> Vec<U256> {
let curve_gen: [U256; 2] = unsafe { transmute(Curve::<BN254>::GENERATOR) };
let curve_gen: [U256; 2] = unsafe { transmute(Curve::<BN254>::GENERATOR * 1) };
let twisted_gen: [U256; 4] = unsafe { transmute(Curve::<Fp2<BN254>>::GENERATOR) };
let mut input = curve_gen.to_vec();
input.extend_from_slice(&twisted_gen);
@ -223,7 +223,8 @@ fn test_bn_miller() -> Result<()> {
};
let interpreter = run_interpreter_with_memory(setup).unwrap();
let output: Vec<U256> = interpreter.extract_kernel_memory(BnPairing, out..out + 12);
let expected = miller_loop(Curve::<BN254>::GENERATOR, Curve::<Fp2<BN254>>::GENERATOR).on_stack();
let expected =
miller_loop(Curve::<BN254>::GENERATOR, Curve::<Fp2<BN254>>::GENERATOR).on_stack();
assert_eq!(output, expected);

View File

@ -1,3 +1,4 @@
use std::fmt::Debug;
use std::mem::transmute;
use std::ops::{Add, Div, Mul, Neg, Sub};
@ -7,6 +8,7 @@ use rand::Rng;
pub trait FieldExt:
Copy
+ std::fmt::Debug
+ std::cmp::PartialEq
+ std::ops::Add<Output = Self>
+ std::ops::Neg<Output = Self>
@ -980,7 +982,7 @@ where
t1: Fp2::<T>::ZERO,
t2: Fp2::<T>::ZERO,
};
fn new(val: usize) -> Fp6<T> {
Fp6 {
t0: Fp2::<T>::new(val),