Fq2 serialization according to spec.
This commit is contained in:
parent
b20157fef1
commit
76344a7ae9
33
src/arith.rs
33
src/arith.rs
|
@ -77,6 +77,39 @@ impl U512 {
|
|||
}
|
||||
}
|
||||
|
||||
impl Encodable for U512 {
|
||||
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
|
||||
let mut buf = [0; (8 * 8)];
|
||||
|
||||
for (l, i) in (0..8).rev().zip((0..8).map(|i| i * 8)) {
|
||||
BigEndian::write_u64(&mut buf[i..], self.0[l]);
|
||||
}
|
||||
|
||||
for i in 0..(8 * 8) {
|
||||
try!(s.emit_u8(buf[i]));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Decodable for U512 {
|
||||
fn decode<S: Decoder>(s: &mut S) -> Result<U512, S::Error> {
|
||||
let mut buf = [0; (8 * 8)];
|
||||
|
||||
for i in 0..(8 * 8) {
|
||||
buf[i] = try!(s.read_u8());
|
||||
}
|
||||
|
||||
let mut n = [0; 8];
|
||||
for (l, i) in (0..8).rev().zip((0..8).map(|i| i * 8)) {
|
||||
n[l] = BigEndian::read_u64(&buf[i..]);
|
||||
}
|
||||
|
||||
Ok(U512(n))
|
||||
}
|
||||
}
|
||||
|
||||
impl Encodable for U256 {
|
||||
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
|
||||
let mut buf = [0; (4 * 8)];
|
||||
|
|
|
@ -68,6 +68,12 @@ macro_rules! field_impl {
|
|||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the modulus
|
||||
#[inline]
|
||||
pub fn modulus() -> U256 {
|
||||
U256($modulus)
|
||||
}
|
||||
}
|
||||
|
||||
impl FieldElement for $name {
|
||||
|
|
|
@ -2,6 +2,8 @@ use fields::{FieldElement, const_fq, Fq};
|
|||
use std::ops::{Add, Sub, Mul, Neg};
|
||||
use rand::Rng;
|
||||
|
||||
use arith::{U256, U512};
|
||||
|
||||
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
|
||||
|
||||
#[inline]
|
||||
|
@ -28,21 +30,25 @@ pub struct Fq2 {
|
|||
|
||||
impl Encodable for Fq2 {
|
||||
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
|
||||
// TODO: multiply c0 and c1 during encoding
|
||||
try!(self.c0.encode(s));
|
||||
try!(self.c1.encode(s));
|
||||
let c1: U256 = self.c1.into();
|
||||
let c0: U256 = self.c0.into();
|
||||
|
||||
Ok(())
|
||||
U512::from(&c1, &c0, &Fq::modulus()).encode(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl Decodable for Fq2 {
|
||||
fn decode<S: Decoder>(s: &mut S) -> Result<Fq2, S::Error> {
|
||||
// TODO: divrem to get c0 and c1
|
||||
let c0 = try!(Fq::decode(s));
|
||||
let c1 = try!(Fq::decode(s));
|
||||
let combined = try!(U512::decode(s));
|
||||
|
||||
Ok(Fq2::new(c0, c1))
|
||||
match combined.divrem(&Fq::modulus()) {
|
||||
Some((c1, c0)) => {
|
||||
Ok(Fq2::new(Fq::new(c0).unwrap(), Fq::new(c1).unwrap()))
|
||||
},
|
||||
None => {
|
||||
Err(s.error("integer not less than modulus squared"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
20005
tests/serialization.rs
20005
tests/serialization.rs
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue