use alloc::vec::Vec;
use core::ops::{Add, Mul};
use ecdsa_core::{
self,
hazmat::{bits2field, DigestPrimitive},
signature::{
digest::{Digest, FixedOutput},
hazmat::PrehashVerifier,
DigestVerifier, Verifier,
},
EncodedPoint, Error, RecoveryId, Result, Signature, SignatureSize,
};
use elliptic_curve::{
bigint::CheckedAdd,
generic_array::{typenum::Unsigned, ArrayLength},
sec1::{FromEncodedPoint, ModulusSize, Tag, ToEncodedPoint},
subtle::{Choice, ConditionallySelectable, CtOption},
CurveArithmetic, FieldBytes, FieldBytesEncoding, FieldBytesSize, PrimeCurve,
};
use openvm_algebra_guest::{DivUnsafe, IntMod, Reduce};
use crate::{
weierstrass::{FromCompressed, IntrinsicCurve, WeierstrassPoint},
CyclicGroup, Group,
};
type Coordinate<C> = <<C as IntrinsicCurve>::Point as WeierstrassPoint>::Coordinate;
type Scalar<C> = <C as IntrinsicCurve>::Scalar;
type AffinePoint<C> = <C as IntrinsicCurve>::Point;
#[derive(Clone)]
pub struct SigningKey<C: IntrinsicCurve> {
#[allow(dead_code)]
secret_scalar: NonZeroScalar<C>,
verifying_key: VerifyingKey<C>,
}
#[allow(dead_code)]
#[derive(Clone)]
pub struct NonZeroScalar<C: IntrinsicCurve> {
scalar: Scalar<C>,
}
impl<C: IntrinsicCurve> SigningKey<C> {
pub fn from_slice(_bytes: &[u8]) -> Result<Self> {
todo!("signing is not yet implemented")
}
pub fn verifying_key(&self) -> &VerifyingKey<C> {
&self.verifying_key
}
}
impl<C> SigningKey<C>
where
C: IntrinsicCurve + PrimeCurve,
{
pub fn sign_prehash_recoverable(&self, _prehash: &[u8]) -> Result<(Signature<C>, RecoveryId)> {
todo!("signing is not yet implemented")
}
}
#[repr(C)]
#[derive(Clone)]
pub struct VerifyingKey<C: IntrinsicCurve> {
pub(crate) inner: PublicKey<C>,
}
#[repr(C)]
#[derive(Clone)]
pub struct PublicKey<C: IntrinsicCurve> {
point: AffinePoint<C>,
}
impl<C: IntrinsicCurve> PublicKey<C>
where
C::Point: WeierstrassPoint + Group + FromCompressed<Coordinate<C>>,
Coordinate<C>: IntMod,
{
pub fn from_affine(point: AffinePoint<C>) -> Result<Self> {
if point.is_identity() {
Err(Error::new())
} else {
Ok(Self { point })
}
}
pub fn from_sec1_bytes(bytes: &[u8]) -> Result<Self>
where
for<'a> &'a Coordinate<C>: Mul<&'a Coordinate<C>, Output = Coordinate<C>>,
{
if bytes.is_empty() {
return Err(Error::new());
}
let tag = Tag::from_u8(bytes[0]).map_err(|_| Error::new())?;
let expected_len = tag.message_len(Coordinate::<C>::NUM_LIMBS);
if bytes.len() != expected_len {
return Err(Error::new());
}
match tag {
Tag::Identity => {
Err(Error::new())
}
Tag::CompressedEvenY | Tag::CompressedOddY => {
let x = Coordinate::<C>::from_be_bytes(&bytes[1..]).ok_or_else(Error::new)?;
let rec_id = bytes[0] & 1;
let point = FromCompressed::decompress(x, &rec_id).ok_or_else(Error::new)?;
Ok(Self { point })
}
Tag::Uncompressed => {
let (x_bytes, y_bytes) = bytes[1..].split_at(Coordinate::<C>::NUM_LIMBS);
let x = Coordinate::<C>::from_be_bytes(x_bytes).ok_or_else(Error::new)?;
let y = Coordinate::<C>::from_be_bytes(y_bytes).ok_or_else(Error::new)?;
let point =
unsafe { <C as IntrinsicCurve>::Point::from_xy(x, y).ok_or_else(Error::new)? };
Self::from_affine(point)
}
_ => Err(Error::new()),
}
}
pub fn to_sec1_bytes(&self, compress: bool) -> Vec<u8> {
if self.point.is_identity() {
return vec![0x00];
}
let (x, y) = self.point.clone().into_coords();
if compress {
let mut bytes = Vec::<u8>::with_capacity(1 + Coordinate::<C>::NUM_LIMBS);
let tag = if y.as_le_bytes()[0] & 1 == 1 {
Tag::CompressedOddY
} else {
Tag::CompressedEvenY
};
bytes.push(tag.into());
bytes.extend_from_slice(x.to_be_bytes().as_ref());
bytes
} else {
let mut bytes = Vec::<u8>::with_capacity(1 + Coordinate::<C>::NUM_LIMBS * 2);
bytes.push(Tag::Uncompressed.into());
bytes.extend_from_slice(x.to_be_bytes().as_ref());
bytes.extend_from_slice(y.to_be_bytes().as_ref());
bytes
}
}
pub fn as_affine(&self) -> &AffinePoint<C> {
&self.point
}
pub fn into_affine(self) -> AffinePoint<C> {
self.point
}
}
impl<C: IntrinsicCurve> VerifyingKey<C>
where
C::Point: WeierstrassPoint + Group + FromCompressed<Coordinate<C>>,
Coordinate<C>: IntMod,
for<'a> &'a Coordinate<C>: Mul<&'a Coordinate<C>, Output = Coordinate<C>>,
{
pub fn new(public_key: PublicKey<C>) -> Self {
Self { inner: public_key }
}
pub fn from_sec1_bytes(bytes: &[u8]) -> Result<Self> {
let public_key = PublicKey::<C>::from_sec1_bytes(bytes)?;
Ok(Self::new(public_key))
}
pub fn from_affine(point: <C as IntrinsicCurve>::Point) -> Result<Self> {
let public_key = PublicKey::<C>::from_affine(point)?;
Ok(Self::new(public_key))
}
pub fn to_sec1_bytes(&self, compress: bool) -> Vec<u8> {
self.inner.to_sec1_bytes(compress)
}
pub fn as_affine(&self) -> &<C as IntrinsicCurve>::Point {
self.inner.as_affine()
}
pub fn into_affine(self) -> <C as IntrinsicCurve>::Point {
self.inner.into_affine()
}
}
impl<C> VerifyingKey<C>
where
C: IntrinsicCurve + PrimeCurve,
C::Point: WeierstrassPoint + CyclicGroup + FromCompressed<Coordinate<C>> + VerifyCustomHook<C>,
Coordinate<C>: IntMod,
C::Scalar: IntMod + Reduce,
for<'a> &'a C::Point: Add<&'a C::Point, Output = C::Point>,
for<'a> &'a Coordinate<C>: Mul<&'a Coordinate<C>, Output = Coordinate<C>>,
FieldBytesSize<C>: ModulusSize,
SignatureSize<C>: ArrayLength<u8>,
{
pub fn recover_from_msg(
msg: &[u8],
signature: &Signature<C>,
recovery_id: RecoveryId,
) -> Result<Self>
where
C: DigestPrimitive,
{
Self::recover_from_digest(C::Digest::new_with_prefix(msg), signature, recovery_id)
}
pub fn recover_from_digest<D>(
msg_digest: D,
signature: &Signature<C>,
recovery_id: RecoveryId,
) -> Result<Self>
where
D: Digest,
{
Self::recover_from_prehash(&msg_digest.finalize(), signature, recovery_id)
}
pub fn recover_from_prehash(
prehash: &[u8],
signature: &Signature<C>,
recovery_id: RecoveryId,
) -> Result<Self> {
let sig = signature.to_bytes();
let vk = Self::recover_from_prehash_noverify(prehash, &sig, recovery_id)?;
vk.inner.as_affine().verify_hook(prehash, signature)?;
Ok(vk)
}
}
pub trait VerifyCustomHook<C>: WeierstrassPoint
where
C: IntrinsicCurve + PrimeCurve,
SignatureSize<C>: ArrayLength<u8>,
{
fn verify_hook(&self, _z: &[u8], _sig: &Signature<C>) -> Result<()> {
Ok(())
}
}
impl<C, D> DigestVerifier<D, Signature<C>> for VerifyingKey<C>
where
C: PrimeCurve + IntrinsicCurve,
D: Digest + FixedOutput<OutputSize = FieldBytesSize<C>>,
SignatureSize<C>: ArrayLength<u8>,
C::Point: WeierstrassPoint + CyclicGroup + FromCompressed<Coordinate<C>> + VerifyCustomHook<C>,
Coordinate<C>: IntMod,
<C as IntrinsicCurve>::Scalar: IntMod + Reduce,
for<'a> &'a C::Point: Add<&'a C::Point, Output = C::Point>,
for<'a> &'a Scalar<C>: DivUnsafe<&'a Scalar<C>, Output = Scalar<C>>,
{
fn verify_digest(&self, msg_digest: D, signature: &Signature<C>) -> Result<()> {
PrehashVerifier::<Signature<C>>::verify_prehash(
self,
&msg_digest.finalize_fixed(),
signature,
)
}
}
impl<C> PrehashVerifier<Signature<C>> for VerifyingKey<C>
where
C: PrimeCurve + IntrinsicCurve,
SignatureSize<C>: ArrayLength<u8>,
C::Point: WeierstrassPoint + CyclicGroup + FromCompressed<Coordinate<C>> + VerifyCustomHook<C>,
Coordinate<C>: IntMod,
C::Scalar: IntMod + Reduce,
for<'a> &'a C::Point: Add<&'a C::Point, Output = C::Point>,
for<'a> &'a Scalar<C>: DivUnsafe<&'a Scalar<C>, Output = Scalar<C>>,
{
fn verify_prehash(&self, prehash: &[u8], signature: &Signature<C>) -> Result<()> {
self.inner.as_affine().verify_hook(prehash, signature)?;
verify_prehashed::<C>(
self.inner.as_affine().clone(),
prehash,
&signature.to_bytes(),
)
}
}
impl<C> Verifier<Signature<C>> for VerifyingKey<C>
where
C: PrimeCurve + CurveArithmetic + DigestPrimitive + IntrinsicCurve,
SignatureSize<C>: ArrayLength<u8>,
C::Point: WeierstrassPoint + CyclicGroup + FromCompressed<Coordinate<C>> + VerifyCustomHook<C>,
Coordinate<C>: IntMod,
<C as IntrinsicCurve>::Scalar: IntMod + Reduce,
for<'a> &'a C::Point: Add<&'a C::Point, Output = C::Point>,
for<'a> &'a Scalar<C>: DivUnsafe<&'a Scalar<C>, Output = Scalar<C>>,
{
fn verify(&self, msg: &[u8], signature: &Signature<C>) -> Result<()> {
self.verify_digest(C::Digest::new_with_prefix(msg), signature)
}
}
impl<C> VerifyingKey<C>
where
C: CurveArithmetic + IntrinsicCurve,
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C> + Default + ConditionallySelectable,
FieldBytesSize<C>: ModulusSize,
{
pub fn from_encoded_point(public_key: &EncodedPoint<C>) -> Result<Self> {
Option::from(PublicKey::<C>::from_encoded_point(public_key))
.map(|public_key| Self { inner: public_key })
.ok_or_else(Error::new)
}
pub fn to_encoded_point(&self, compress: bool) -> EncodedPoint<C> {
self.inner.to_encoded_point(compress)
}
}
impl<C> FromEncodedPoint<C> for PublicKey<C>
where
C: CurveArithmetic + IntrinsicCurve,
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C> + Default + ConditionallySelectable,
FieldBytesSize<C>: ModulusSize,
{
fn from_encoded_point(encoded_point: &EncodedPoint<C>) -> CtOption<Self> {
AffinePoint::<C>::from_encoded_point(encoded_point).and_then(|point| {
let is_identity = Choice::from(u8::from(encoded_point.is_identity()));
CtOption::new(PublicKey { point }, !is_identity)
})
}
}
impl<C> ToEncodedPoint<C> for PublicKey<C>
where
C: CurveArithmetic + IntrinsicCurve,
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
FieldBytesSize<C>: ModulusSize,
{
fn to_encoded_point(&self, compress: bool) -> EncodedPoint<C> {
self.point.to_encoded_point(compress)
}
}
impl<C> VerifyingKey<C>
where
C: IntrinsicCurve + PrimeCurve,
C::Point: WeierstrassPoint + CyclicGroup + FromCompressed<Coordinate<C>>,
Coordinate<C>: IntMod,
C::Scalar: IntMod + Reduce,
{
#[allow(non_snake_case)]
pub fn recover_from_prehash_noverify(
prehash: &[u8],
sig: &[u8],
recovery_id: RecoveryId,
) -> Result<Self>
where
for<'a> &'a C::Point: Add<&'a C::Point, Output = C::Point>,
for<'a> &'a Coordinate<C>: Mul<&'a Coordinate<C>, Output = Coordinate<C>>,
{
assert!(Scalar::<C>::NUM_LIMBS <= Coordinate::<C>::NUM_LIMBS);
if sig.len() != <C as IntrinsicCurve>::Scalar::NUM_LIMBS * 2 {
return Err(Error::new());
}
let (r_be, s_be) = sig.split_at(<C as IntrinsicCurve>::Scalar::NUM_LIMBS);
let r = Scalar::<C>::from_be_bytes(r_be).ok_or_else(Error::new)?;
let s = Scalar::<C>::from_be_bytes(s_be).ok_or_else(Error::new)?;
if r == Scalar::<C>::ZERO || s == Scalar::<C>::ZERO {
return Err(Error::new());
}
let prehash_bytes = bits2field::<C>(prehash)?;
let trim = prehash_bytes.len().saturating_sub(Scalar::<C>::NUM_LIMBS);
let z = Scalar::<C>::from_be_bytes_unchecked(&prehash_bytes[..prehash_bytes.len() - trim]);
let mut r_bytes = {
let mut r_bytes = FieldBytes::<C>::default();
assert!(FieldBytesSize::<C>::USIZE >= Scalar::<C>::NUM_LIMBS);
let offset = r_bytes.len().saturating_sub(r_be.len());
r_bytes[offset..].copy_from_slice(r_be);
r_bytes
};
if recovery_id.is_x_reduced() {
match Option::<C::Uint>::from(
C::Uint::decode_field_bytes(&r_bytes).checked_add(&C::ORDER),
) {
Some(restored) => r_bytes = restored.encode_field_bytes(),
None => {
return Err(Error::new());
}
};
}
assert!(FieldBytesSize::<C>::USIZE <= Coordinate::<C>::NUM_LIMBS);
let x = Coordinate::<C>::from_be_bytes(&r_bytes).ok_or_else(Error::new)?;
let rec_id = recovery_id.to_byte();
let R: C::Point = FromCompressed::decompress(x, &rec_id).ok_or_else(Error::new)?;
let neg_u1 = z.div_unsafe(&r);
let u2 = s.div_unsafe(&r);
let NEG_G = C::Point::NEG_GENERATOR;
let point = <C as IntrinsicCurve>::msm(&[neg_u1, u2], &[NEG_G, R]);
let vk = VerifyingKey::from_affine(point)?;
Ok(vk)
}
}
#[allow(non_snake_case)]
pub fn verify_prehashed<C>(pubkey: AffinePoint<C>, prehash: &[u8], sig: &[u8]) -> Result<()>
where
C: IntrinsicCurve + PrimeCurve,
C::Point: WeierstrassPoint + CyclicGroup + FromCompressed<Coordinate<C>>,
Coordinate<C>: IntMod,
C::Scalar: IntMod + Reduce,
for<'a> &'a C::Point: Add<&'a C::Point, Output = C::Point>,
for<'a> &'a Scalar<C>: DivUnsafe<&'a Scalar<C>, Output = Scalar<C>>,
{
if pubkey.is_identity() {
return Err(Error::new());
}
assert!(Scalar::<C>::NUM_LIMBS <= Coordinate::<C>::NUM_LIMBS);
if sig.len() != Scalar::<C>::NUM_LIMBS * 2 {
return Err(Error::new());
}
let (r_be, s_be) = sig.split_at(<C as IntrinsicCurve>::Scalar::NUM_LIMBS);
let r = Scalar::<C>::from_be_bytes(r_be).ok_or_else(Error::new)?;
let s = Scalar::<C>::from_be_bytes(s_be).ok_or_else(Error::new)?;
if r == Scalar::<C>::ZERO || s == Scalar::<C>::ZERO {
return Err(Error::new());
}
let prehash_bytes = bits2field::<C>(prehash)?;
let trim = prehash_bytes.len().saturating_sub(Scalar::<C>::NUM_LIMBS);
let z = Scalar::<C>::from_be_bytes_unchecked(&prehash_bytes[..prehash_bytes.len() - trim]);
let u1 = z.div_unsafe(&s);
let u2 = (&r).div_unsafe(&s);
let G = C::Point::GENERATOR;
let Q = pubkey;
let R = <C as IntrinsicCurve>::msm(&[u1, u2], &[G, Q]);
if R.is_identity() {
return Err(Error::new());
}
let (x_1, _) = R.into_coords();
let x_mod_n = Scalar::<C>::reduce_le_bytes(x_1.as_le_bytes());
if x_mod_n == r {
Ok(())
} else {
Err(Error::new())
}
}
impl<C: IntrinsicCurve> AsRef<AffinePoint<C>> for VerifyingKey<C> {
fn as_ref(&self) -> &AffinePoint<C> {
&self.inner.point
}
}
impl<C: IntrinsicCurve> AsRef<AffinePoint<C>> for PublicKey<C> {
fn as_ref(&self) -> &AffinePoint<C> {
&self.point
}
}