1use alloc::vec::Vec;
2use core::ops::{Add, Mul};
3
4use ecdsa_core::{
5 self,
6 hazmat::{bits2field, DigestPrimitive},
7 signature::{
8 digest::{Digest, FixedOutput},
9 hazmat::PrehashVerifier,
10 DigestVerifier, Verifier,
11 },
12 EncodedPoint, Error, RecoveryId, Result, Signature, SignatureSize,
13};
14use elliptic_curve::{
15 bigint::CheckedAdd,
16 generic_array::{typenum::Unsigned, ArrayLength},
17 sec1::{FromEncodedPoint, ModulusSize, Tag, ToEncodedPoint},
18 subtle::{Choice, ConditionallySelectable, CtOption},
19 CurveArithmetic, FieldBytes, FieldBytesEncoding, FieldBytesSize, PrimeCurve,
20};
21use openvm_algebra_guest::{DivUnsafe, IntMod, Reduce};
22
23use crate::{
24 weierstrass::{FromCompressed, IntrinsicCurve, WeierstrassPoint},
25 CyclicGroup, Group,
26};
27
28type Coordinate<C> = <<C as IntrinsicCurve>::Point as WeierstrassPoint>::Coordinate;
29type Scalar<C> = <C as IntrinsicCurve>::Scalar;
30type AffinePoint<C> = <C as IntrinsicCurve>::Point;
31
32#[derive(Clone)]
39pub struct SigningKey<C: IntrinsicCurve> {
40 #[allow(dead_code)]
42 secret_scalar: NonZeroScalar<C>,
43
44 verifying_key: VerifyingKey<C>,
46}
47
48#[allow(dead_code)]
49#[derive(Clone)]
50pub struct NonZeroScalar<C: IntrinsicCurve> {
51 scalar: Scalar<C>,
52}
53
54impl<C: IntrinsicCurve> SigningKey<C> {
55 pub fn from_slice(_bytes: &[u8]) -> Result<Self> {
56 todo!("signing is not yet implemented")
57 }
58
59 pub fn verifying_key(&self) -> &VerifyingKey<C> {
60 &self.verifying_key
61 }
62}
63
64impl<C> SigningKey<C>
65where
66 C: IntrinsicCurve + PrimeCurve,
67{
68 pub fn sign_prehash_recoverable(&self, _prehash: &[u8]) -> Result<(Signature<C>, RecoveryId)> {
69 todo!("signing is not yet implemented")
70 }
71}
72
73#[repr(C)]
76#[derive(Clone)]
77pub struct VerifyingKey<C: IntrinsicCurve> {
78 pub(crate) inner: PublicKey<C>,
79}
80
81#[repr(C)]
83#[derive(Clone)]
84pub struct PublicKey<C: IntrinsicCurve> {
85 point: AffinePoint<C>,
87}
88
89impl<C: IntrinsicCurve> PublicKey<C>
90where
91 C::Point: WeierstrassPoint + Group + FromCompressed<Coordinate<C>>,
92 Coordinate<C>: IntMod,
93{
94 pub fn from_affine(point: AffinePoint<C>) -> Result<Self> {
101 point.x().assert_reduced();
102 point.y().assert_reduced();
103
104 if point.is_identity() {
105 Err(Error::new())
106 } else {
107 Ok(Self { point })
108 }
109 }
110
111 pub fn from_sec1_bytes(bytes: &[u8]) -> Result<Self>
115 where
116 for<'a> &'a Coordinate<C>: Mul<&'a Coordinate<C>, Output = Coordinate<C>>,
117 {
118 if bytes.is_empty() {
119 return Err(Error::new());
120 }
121
122 let tag = Tag::from_u8(bytes[0]).map_err(|_| Error::new())?;
124
125 let expected_len = tag.message_len(Coordinate::<C>::NUM_LIMBS);
127 if bytes.len() != expected_len {
128 return Err(Error::new());
129 }
130
131 match tag {
132 Tag::Identity => {
133 Err(Error::new())
135 }
136
137 Tag::CompressedEvenY | Tag::CompressedOddY => {
138 let x = Coordinate::<C>::from_be_bytes(&bytes[1..]).ok_or_else(Error::new)?;
139 let rec_id = bytes[0] & 1;
140 let point = FromCompressed::decompress(x, &rec_id).ok_or_else(Error::new)?;
141 Ok(Self { point })
143 }
144
145 Tag::Uncompressed => {
146 let (x_bytes, y_bytes) = bytes[1..].split_at(Coordinate::<C>::NUM_LIMBS);
147 let x = Coordinate::<C>::from_be_bytes(x_bytes).ok_or_else(Error::new)?;
148 let y = Coordinate::<C>::from_be_bytes(y_bytes).ok_or_else(Error::new)?;
149 let point =
150 unsafe { <C as IntrinsicCurve>::Point::from_xy(x, y).ok_or_else(Error::new)? };
151 Self::from_affine(point)
152 }
153
154 _ => Err(Error::new()),
155 }
156 }
157
158 pub fn to_sec1_bytes(&self, compress: bool) -> Vec<u8> {
159 if self.point.is_identity() {
160 return vec![0x00];
161 }
162
163 let (x, y) = self.point.clone().into_coords();
164
165 if compress {
166 let mut bytes = Vec::<u8>::with_capacity(1 + Coordinate::<C>::NUM_LIMBS);
167 let tag = if y.as_le_bytes()[0] & 1 == 1 {
168 Tag::CompressedOddY
169 } else {
170 Tag::CompressedEvenY
171 };
172 bytes.push(tag.into());
173 bytes.extend_from_slice(x.to_be_bytes().as_ref());
174 bytes
175 } else {
176 let mut bytes = Vec::<u8>::with_capacity(1 + Coordinate::<C>::NUM_LIMBS * 2);
177 bytes.push(Tag::Uncompressed.into());
178 bytes.extend_from_slice(x.to_be_bytes().as_ref());
179 bytes.extend_from_slice(y.to_be_bytes().as_ref());
180 bytes
181 }
182 }
183
184 pub fn as_affine(&self) -> &AffinePoint<C> {
185 &self.point
186 }
187
188 pub fn into_affine(self) -> AffinePoint<C> {
189 self.point
190 }
191}
192
193impl<C: IntrinsicCurve> VerifyingKey<C>
194where
195 C::Point: WeierstrassPoint + Group + FromCompressed<Coordinate<C>>,
196 Coordinate<C>: IntMod,
197 for<'a> &'a Coordinate<C>: Mul<&'a Coordinate<C>, Output = Coordinate<C>>,
198{
199 pub fn new(public_key: PublicKey<C>) -> Self {
200 Self { inner: public_key }
201 }
202
203 pub fn from_sec1_bytes(bytes: &[u8]) -> Result<Self> {
204 let public_key = PublicKey::<C>::from_sec1_bytes(bytes)?;
205 Ok(Self::new(public_key))
206 }
207
208 pub fn from_affine(point: <C as IntrinsicCurve>::Point) -> Result<Self> {
212 let public_key = PublicKey::<C>::from_affine(point)?;
213 Ok(Self::new(public_key))
214 }
215
216 pub fn to_sec1_bytes(&self, compress: bool) -> Vec<u8> {
217 self.inner.to_sec1_bytes(compress)
218 }
219
220 pub fn as_affine(&self) -> &<C as IntrinsicCurve>::Point {
221 self.inner.as_affine()
222 }
223
224 pub fn into_affine(self) -> <C as IntrinsicCurve>::Point {
225 self.inner.into_affine()
226 }
227}
228
229impl<C> VerifyingKey<C>
231where
232 C: IntrinsicCurve + PrimeCurve,
233 C::Point: WeierstrassPoint + CyclicGroup + FromCompressed<Coordinate<C>> + VerifyCustomHook<C>,
234 Coordinate<C>: IntMod,
235 C::Scalar: IntMod + Reduce,
236 for<'a> &'a C::Point: Add<&'a C::Point, Output = C::Point>,
237 for<'a> &'a Coordinate<C>: Mul<&'a Coordinate<C>, Output = Coordinate<C>>,
238 FieldBytesSize<C>: ModulusSize,
239 SignatureSize<C>: ArrayLength<u8>,
240{
241 pub fn recover_from_msg(
246 msg: &[u8],
247 signature: &Signature<C>,
248 recovery_id: RecoveryId,
249 ) -> Result<Self>
250 where
251 C: DigestPrimitive,
252 {
253 Self::recover_from_digest(C::Digest::new_with_prefix(msg), signature, recovery_id)
254 }
255
256 pub fn recover_from_digest<D>(
259 msg_digest: D,
260 signature: &Signature<C>,
261 recovery_id: RecoveryId,
262 ) -> Result<Self>
263 where
264 D: Digest,
265 {
266 Self::recover_from_prehash(&msg_digest.finalize(), signature, recovery_id)
267 }
268
269 pub fn recover_from_prehash(
273 prehash: &[u8],
274 signature: &Signature<C>,
275 recovery_id: RecoveryId,
276 ) -> Result<Self> {
277 let sig = signature.to_bytes();
278 let vk = Self::recover_from_prehash_noverify(prehash, &sig, recovery_id)?;
279 vk.inner.as_affine().verify_hook(prehash, signature)?;
280 Ok(vk)
281 }
282}
283
284pub trait VerifyCustomHook<C>: WeierstrassPoint
291where
292 C: IntrinsicCurve + PrimeCurve,
293 SignatureSize<C>: ArrayLength<u8>,
294{
295 fn verify_hook(&self, _z: &[u8], _sig: &Signature<C>) -> Result<()> {
305 Ok(())
306 }
307}
308
309impl<C, D> DigestVerifier<D, Signature<C>> for VerifyingKey<C>
314where
315 C: PrimeCurve + IntrinsicCurve,
316 D: Digest + FixedOutput<OutputSize = FieldBytesSize<C>>,
317 SignatureSize<C>: ArrayLength<u8>,
318 C::Point: WeierstrassPoint + CyclicGroup + FromCompressed<Coordinate<C>> + VerifyCustomHook<C>,
319 Coordinate<C>: IntMod,
320 <C as IntrinsicCurve>::Scalar: IntMod + Reduce,
321 for<'a> &'a C::Point: Add<&'a C::Point, Output = C::Point>,
322 for<'a> &'a Scalar<C>: DivUnsafe<&'a Scalar<C>, Output = Scalar<C>>,
323{
324 fn verify_digest(&self, msg_digest: D, signature: &Signature<C>) -> Result<()> {
325 PrehashVerifier::<Signature<C>>::verify_prehash(
326 self,
327 &msg_digest.finalize_fixed(),
328 signature,
329 )
330 }
331}
332
333impl<C> PrehashVerifier<Signature<C>> for VerifyingKey<C>
334where
335 C: PrimeCurve + IntrinsicCurve,
336 SignatureSize<C>: ArrayLength<u8>,
337 C::Point: WeierstrassPoint + CyclicGroup + FromCompressed<Coordinate<C>> + VerifyCustomHook<C>,
338 Coordinate<C>: IntMod,
339 C::Scalar: IntMod + Reduce,
340 for<'a> &'a C::Point: Add<&'a C::Point, Output = C::Point>,
341 for<'a> &'a Scalar<C>: DivUnsafe<&'a Scalar<C>, Output = Scalar<C>>,
342{
343 fn verify_prehash(&self, prehash: &[u8], signature: &Signature<C>) -> Result<()> {
344 self.inner.as_affine().verify_hook(prehash, signature)?;
345 verify_prehashed::<C>(
346 self.inner.as_affine().clone(),
347 prehash,
348 &signature.to_bytes(),
349 )
350 }
351}
352
353impl<C> Verifier<Signature<C>> for VerifyingKey<C>
354where
355 C: PrimeCurve + CurveArithmetic + DigestPrimitive + IntrinsicCurve,
356 SignatureSize<C>: ArrayLength<u8>,
357 C::Point: WeierstrassPoint + CyclicGroup + FromCompressed<Coordinate<C>> + VerifyCustomHook<C>,
358 Coordinate<C>: IntMod,
359 <C as IntrinsicCurve>::Scalar: IntMod + Reduce,
360 for<'a> &'a C::Point: Add<&'a C::Point, Output = C::Point>,
361 for<'a> &'a Scalar<C>: DivUnsafe<&'a Scalar<C>, Output = Scalar<C>>,
362{
363 fn verify(&self, msg: &[u8], signature: &Signature<C>) -> Result<()> {
364 self.verify_digest(C::Digest::new_with_prefix(msg), signature)
365 }
366}
367
368impl<C> VerifyingKey<C>
372where
373 C: CurveArithmetic + IntrinsicCurve,
374 AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C> + Default + ConditionallySelectable,
375 FieldBytesSize<C>: ModulusSize,
376{
377 pub fn from_encoded_point(public_key: &EncodedPoint<C>) -> Result<Self> {
379 Option::from(PublicKey::<C>::from_encoded_point(public_key))
380 .map(|public_key| Self { inner: public_key })
381 .ok_or_else(Error::new)
382 }
383
384 pub fn to_encoded_point(&self, compress: bool) -> EncodedPoint<C> {
387 self.inner.to_encoded_point(compress)
388 }
389}
390
391impl<C> FromEncodedPoint<C> for PublicKey<C>
395where
396 C: CurveArithmetic + IntrinsicCurve,
397 AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C> + Default + ConditionallySelectable,
398 FieldBytesSize<C>: ModulusSize,
399{
400 fn from_encoded_point(encoded_point: &EncodedPoint<C>) -> CtOption<Self> {
402 AffinePoint::<C>::from_encoded_point(encoded_point).and_then(|point| {
403 let is_identity = Choice::from(u8::from(encoded_point.is_identity()));
405 CtOption::new(PublicKey { point }, !is_identity)
406 })
407 }
408}
409
410impl<C> ToEncodedPoint<C> for PublicKey<C>
411where
412 C: CurveArithmetic + IntrinsicCurve,
413 AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
414 FieldBytesSize<C>: ModulusSize,
415{
416 fn to_encoded_point(&self, compress: bool) -> EncodedPoint<C> {
419 self.point.to_encoded_point(compress)
420 }
421}
422
423impl<C> VerifyingKey<C>
425where
426 C: IntrinsicCurve + PrimeCurve,
427 C::Point: WeierstrassPoint + CyclicGroup + FromCompressed<Coordinate<C>>,
428 Coordinate<C>: IntMod,
429 C::Scalar: IntMod + Reduce,
430{
431 #[allow(non_snake_case)]
440 pub fn recover_from_prehash_noverify(
441 prehash: &[u8],
442 sig: &[u8],
443 recovery_id: RecoveryId,
444 ) -> Result<Self>
445 where
446 for<'a> &'a C::Point: Add<&'a C::Point, Output = C::Point>,
447 for<'a> &'a Coordinate<C>: Mul<&'a Coordinate<C>, Output = Coordinate<C>>,
448 {
449 assert!(Scalar::<C>::NUM_LIMBS <= Coordinate::<C>::NUM_LIMBS);
451 if sig.len() != <C as IntrinsicCurve>::Scalar::NUM_LIMBS * 2 {
453 return Err(Error::new());
454 }
455 let (r_be, s_be) = sig.split_at(<C as IntrinsicCurve>::Scalar::NUM_LIMBS);
457 let r = Scalar::<C>::from_be_bytes(r_be).ok_or_else(Error::new)?;
459 let s = Scalar::<C>::from_be_bytes(s_be).ok_or_else(Error::new)?;
460 if r == Scalar::<C>::ZERO || s == Scalar::<C>::ZERO {
461 return Err(Error::new());
462 }
463
464 let prehash_bytes = bits2field::<C>(prehash)?;
466 let trim = prehash_bytes.len().saturating_sub(Scalar::<C>::NUM_LIMBS);
468 let z = Scalar::<C>::from_be_bytes_unchecked(&prehash_bytes[..prehash_bytes.len() - trim]);
471
472 let mut r_bytes = {
477 let mut r_bytes = FieldBytes::<C>::default();
478 assert!(FieldBytesSize::<C>::USIZE >= Scalar::<C>::NUM_LIMBS);
479 let offset = r_bytes.len().saturating_sub(r_be.len());
480 r_bytes[offset..].copy_from_slice(r_be);
481 r_bytes
482 };
483 if recovery_id.is_x_reduced() {
484 match Option::<C::Uint>::from(
485 C::Uint::decode_field_bytes(&r_bytes).checked_add(&C::ORDER),
486 ) {
487 Some(restored) => r_bytes = restored.encode_field_bytes(),
488 None => {
490 return Err(Error::new());
491 }
492 };
493 }
494 assert!(FieldBytesSize::<C>::USIZE <= Coordinate::<C>::NUM_LIMBS);
495 let x = Coordinate::<C>::from_be_bytes(&r_bytes).ok_or_else(Error::new)?;
496 let rec_id = recovery_id.to_byte();
497 let R: C::Point = FromCompressed::decompress(x, &rec_id).ok_or_else(Error::new)?;
499
500 let neg_u1 = z.div_unsafe(&r);
501 let u2 = s.div_unsafe(&r);
502 let NEG_G = C::Point::NEG_GENERATOR;
503 let point = <C as IntrinsicCurve>::msm(&[neg_u1, u2], &[NEG_G, R]);
504 let vk = VerifyingKey::from_affine(point)?;
505
506 Ok(vk)
507 }
508}
509
510#[allow(non_snake_case)]
513pub fn verify_prehashed<C>(pubkey: AffinePoint<C>, prehash: &[u8], sig: &[u8]) -> Result<()>
514where
515 C: IntrinsicCurve + PrimeCurve,
516 C::Point: WeierstrassPoint + CyclicGroup + FromCompressed<Coordinate<C>>,
517 Coordinate<C>: IntMod,
518 C::Scalar: IntMod + Reduce,
519 for<'a> &'a C::Point: Add<&'a C::Point, Output = C::Point>,
520 for<'a> &'a Scalar<C>: DivUnsafe<&'a Scalar<C>, Output = Scalar<C>>,
521{
522 if pubkey.is_identity() {
523 return Err(Error::new());
524 }
525
526 assert!(Scalar::<C>::NUM_LIMBS <= Coordinate::<C>::NUM_LIMBS);
528 if sig.len() != Scalar::<C>::NUM_LIMBS * 2 {
530 return Err(Error::new());
531 }
532 let (r_be, s_be) = sig.split_at(<C as IntrinsicCurve>::Scalar::NUM_LIMBS);
534 let r = Scalar::<C>::from_be_bytes(r_be).ok_or_else(Error::new)?;
536 let s = Scalar::<C>::from_be_bytes(s_be).ok_or_else(Error::new)?;
537 if r == Scalar::<C>::ZERO || s == Scalar::<C>::ZERO {
538 return Err(Error::new());
539 }
540
541 let prehash_bytes = bits2field::<C>(prehash)?;
543 let trim = prehash_bytes.len().saturating_sub(Scalar::<C>::NUM_LIMBS);
545 let z = Scalar::<C>::from_be_bytes_unchecked(&prehash_bytes[..prehash_bytes.len() - trim]);
548
549 let u1 = z.div_unsafe(&s);
550 let u2 = (&r).div_unsafe(&s);
551
552 let G = C::Point::GENERATOR;
553 let Q = pubkey;
555 let R = <C as IntrinsicCurve>::msm(&[u1, u2], &[G, Q]);
556 if R.is_identity() {
557 return Err(Error::new());
558 }
559 let (x_1, _) = R.into_coords();
560 let x_mod_n = Scalar::<C>::reduce_le_bytes(x_1.as_le_bytes());
562 if x_mod_n == r {
563 Ok(())
564 } else {
565 Err(Error::new())
566 }
567}
568
569impl<C: IntrinsicCurve> AsRef<AffinePoint<C>> for VerifyingKey<C> {
570 fn as_ref(&self) -> &AffinePoint<C> {
571 &self.inner.point
572 }
573}
574
575impl<C: IntrinsicCurve> AsRef<AffinePoint<C>> for PublicKey<C> {
576 fn as_ref(&self) -> &AffinePoint<C> {
577 &self.point
578 }
579}