Skip to content

Commit

Permalink
Fix secp256k1 compressed serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
davidnevadoc committed Nov 15, 2022
1 parent 83c72d4 commit b8627f9
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 7 deletions.
2 changes: 2 additions & 0 deletions src/bn256/curve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ new_curve_impl!(
G1,
G1Affine,
G1Compressed,
Fq::size(),
Fq,
Fr,
(G1_GENERATOR_X,G1_GENERATOR_Y),
Expand All @@ -37,6 +38,7 @@ new_curve_impl!(
G2,
G2Affine,
G2Compressed,
Fq2::size(),
Fq2,
Fr,
(G2_GENERATOR_X, G2_GENERATOR_Y),
Expand Down
18 changes: 11 additions & 7 deletions src/derive/curve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ macro_rules! new_curve_impl {
$name:ident,
$name_affine:ident,
$name_compressed:ident,
$compressed_size:expr,
$base:ident,
$scalar:ident,
$generator:expr,
Expand All @@ -161,7 +162,7 @@ macro_rules! new_curve_impl {
}

#[derive(Copy, Clone)]
$($privacy)* struct $name_compressed([u8; $base::size()]);
$($privacy)* struct $name_compressed([u8; $compressed_size]);


impl $name {
Expand Down Expand Up @@ -226,7 +227,7 @@ macro_rules! new_curve_impl {

impl Default for $name_compressed {
fn default() -> Self {
$name_compressed([0; $base::size()])
$name_compressed([0; $compressed_size])
}
}

Expand Down Expand Up @@ -563,10 +564,12 @@ macro_rules! new_curve_impl {
fn from_bytes(bytes: &Self::Repr) -> CtOption<Self> {
let bytes = &bytes.0;
let mut tmp = *bytes;
let ysign = Choice::from(tmp[$base::size() - 1] >> 7);
tmp[$base::size() - 1] &= 0b0111_1111;
let ysign = Choice::from(tmp[$compressed_size - 1] >> 7);
tmp[$compressed_size - 1] &= 0b0111_1111;
let mut xbytes = [0u8; $base::size()];
xbytes.copy_from_slice(&tmp[ ..$base::size()]);

$base::from_bytes(&tmp).and_then(|x| {
$base::from_bytes(&xbytes).and_then(|x| {
CtOption::new(Self::identity(), x.is_zero() & (!ysign)).or_else(|| {
let x3 = x.square() * x;
(x3 + $name::curve_constant_b()).sqrt().and_then(|y| {
Expand Down Expand Up @@ -596,8 +599,9 @@ macro_rules! new_curve_impl {
} else {
let (x, y) = (self.x, self.y);
let sign = (y.to_bytes()[0] & 1) << 7;
let mut xbytes = x.to_bytes();
xbytes[$base::size() - 1] |= sign;
let mut xbytes = [0u8; $compressed_size];
xbytes[..$base::size()].copy_from_slice(&x.to_bytes());
xbytes[$compressed_size - 1] |= sign;
$name_compressed(xbytes)
}
}
Expand Down
1 change: 1 addition & 0 deletions src/secp256k1/curve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ new_curve_impl!(
Secp256k1,
Secp256k1Affine,
Secp256k1Compressed,
33,
Fp,
Fq,
(SECP_GENERATOR_X,SECP_GENERATOR_Y),
Expand Down

0 comments on commit b8627f9

Please sign in to comment.