Skip to main content

openvm_ecc_guest/
ecdsa.rs

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//
33// Signing implementations are placeholders to support patching compilation
34//
35
36/// This is placeholder struct for compatibility purposes with the `ecdsa` crate.
37/// Signing from private keys is not supported yet.
38#[derive(Clone)]
39pub struct SigningKey<C: IntrinsicCurve> {
40    /// ECDSA signing keys are non-zero elements of a given curve's scalar field.
41    #[allow(dead_code)]
42    secret_scalar: NonZeroScalar<C>,
43
44    /// Verifying key which corresponds to this signing key.
45    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// This struct is public because it is used by the VerifyPrimitive impl in the k256 and p256 guest
74// libraries.
75#[repr(C)]
76#[derive(Clone)]
77pub struct VerifyingKey<C: IntrinsicCurve> {
78    pub(crate) inner: PublicKey<C>,
79}
80
81// This struct is public because it is used by the VerifyPrimitive impl in the k256 and p256 guest
82#[repr(C)]
83#[derive(Clone)]
84pub struct PublicKey<C: IntrinsicCurve> {
85    /// Affine point
86    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    /// Convert an `AffinePoint` into a [`PublicKey`].
95    /// In addition, for `Coordinate<C>` implementing `IntMod`, this function will assert that the
96    /// affine coordinates of `point` are both in canonical form.
97    ///
98    /// This does not check that `point` is on the curve. Use this only with points that have
99    /// already been checked. For public keys from untrusted bytes, use [`Self::from_sec1_bytes`].
100    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    /// # Safety
112    /// - The uncompressed deserialization checks that the point is on the curve but does not
113    ///   perform any additional subgroup checks.
114    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        // Validate tag
123        let tag = Tag::from_u8(bytes[0]).map_err(|_| Error::new())?;
124
125        // Validate length
126        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                // Reject identity point, a PublicKey must be non-identity
134                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                // Decompressed point will never be identity
142                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    /// Convert an affine point into a verifying key.
209    ///
210    /// This has the same validation behavior as [`PublicKey::from_affine`].
211    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
229// Functions for compatibility with `ecdsa` crate
230impl<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    /// Recover a [`VerifyingKey`] from the given message, signature, and
242    /// [`RecoveryId`].
243    ///
244    /// The message is first hashed using this curve's [`DigestPrimitive`].
245    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    /// Recover a [`VerifyingKey`] from the given message [`Digest`],
257    /// signature, and [`RecoveryId`].
258    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    /// Recover a [`VerifyingKey`] from the given `prehash` of a message, the
270    /// signature over that prehashed message, and a [`RecoveryId`].
271    /// Note that this function does not verify the signature with the recovered key.
272    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
284/// To match the RustCrypto trait `VerifyPrimitive`. Certain curves have special verification logic
285/// outside of the general ECDSA verification algorithm. This trait provides a hook for such logic.
286///
287/// This trait is intended to be implemented on type which can access
288/// the affine point representing the public key via `&self`, such as a
289/// particular curve's `AffinePoint` type.
290pub trait VerifyCustomHook<C>: WeierstrassPoint
291where
292    C: IntrinsicCurve + PrimeCurve,
293    SignatureSize<C>: ArrayLength<u8>,
294{
295    /// This is **NOT** the full ECDSA signature verification algorithm. The implementer should only
296    /// add additional verification logic not contained in [verify_prehashed]. The default
297    /// implementation does nothing.
298    ///
299    /// Accepts the following arguments:
300    ///
301    /// - `z`: message digest to be verified. MUST BE OUTPUT OF A CRYPTOGRAPHICALLY SECURE DIGEST
302    ///   ALGORITHM!!!
303    /// - `sig`: signature to be verified against the key and message
304    fn verify_hook(&self, _z: &[u8], _sig: &Signature<C>) -> Result<()> {
305        Ok(())
306    }
307}
308
309//
310// `*Verifier` trait impls
311//
312
313impl<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
368//
369// copied from `ecdsa`
370//
371impl<C> VerifyingKey<C>
372where
373    C: CurveArithmetic + IntrinsicCurve,
374    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C> + Default + ConditionallySelectable,
375    FieldBytesSize<C>: ModulusSize,
376{
377    /// Initialize [`VerifyingKey`] from an [`EncodedPoint`].
378    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    /// Serialize this [`VerifyingKey`] as a SEC1 [`EncodedPoint`], optionally
385    /// applying point compression.
386    pub fn to_encoded_point(&self, compress: bool) -> EncodedPoint<C> {
387        self.inner.to_encoded_point(compress)
388    }
389}
390
391//
392// sec1 traits copied from elliptic_curve
393//
394impl<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    /// Initialize [`PublicKey`] from an [`EncodedPoint`]
401    fn from_encoded_point(encoded_point: &EncodedPoint<C>) -> CtOption<Self> {
402        AffinePoint::<C>::from_encoded_point(encoded_point).and_then(|point| {
403            // Defeating the point of `subtle`, but the use case is specifically a public key
404            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    /// Serialize this [`PublicKey`] as a SEC1 [`EncodedPoint`], optionally applying
417    /// point compression
418    fn to_encoded_point(&self, compress: bool) -> EncodedPoint<C> {
419        self.point.to_encoded_point(compress)
420    }
421}
422
423// Custom openvm implementations
424impl<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    /// ## Assumption
432    /// To use this implementation, the `Signature<C>`, `Coordinate<C>`, and `FieldBytes<C>` should
433    /// all be encoded in big endian bytes. The implementation also assumes that
434    /// `Scalar::<C>::NUM_LIMBS <= FieldBytesSize::<C>::USIZE <= Coordinate::<C>::NUM_LIMBS`.
435    ///
436    /// Ref: <https://github.com/RustCrypto/signatures/blob/85c984bcc9927c2ce70c7e15cbfe9c6936dd3521/ecdsa/src/recovery.rs#L297>
437    ///
438    /// Recovery does not require additional signature verification: <https://github.com/RustCrypto/signatures/pull/831>
439    #[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        // This should get compiled out:
450        assert!(Scalar::<C>::NUM_LIMBS <= Coordinate::<C>::NUM_LIMBS);
451        // IntMod limbs are currently always bytes
452        if sig.len() != <C as IntrinsicCurve>::Scalar::NUM_LIMBS * 2 {
453            return Err(Error::new());
454        }
455        // Signature is default encoded in big endian bytes
456        let (r_be, s_be) = sig.split_at(<C as IntrinsicCurve>::Scalar::NUM_LIMBS);
457        // Note: Scalar internally stores using little endian
458        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        // Perf: don't use bits2field from ::ecdsa
465        let prehash_bytes = bits2field::<C>(prehash)?;
466        // If prehash is longer than Scalar::NUM_LIMBS, take leftmost bytes
467        let trim = prehash_bytes.len().saturating_sub(Scalar::<C>::NUM_LIMBS);
468        // from_be_bytes_unchecked zero-pads if len < Scalar::NUM_LIMBS
469        // we don't need to reduce because IntMod is up to modular equivalence
470        let z = Scalar::<C>::from_be_bytes_unchecked(&prehash_bytes[..prehash_bytes.len() - trim]);
471
472        // `r` is in the Scalar field, we now possibly add C::ORDER to it to get `x`
473        // in the Coordinate field.
474        // We take some extra care for the case when FieldBytesSize<C> may be larger than
475        // Scalar::<C>::NUM_LIMBS.
476        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                // No reduction should happen here if r was reduced
489                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        // The point R decompressed from x-coordinate `r`
498        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/// Assumes that `sig` is proper encoding of `r, s`.
511// Ref: https://docs.rs/ecdsa/latest/src/ecdsa/hazmat.rs.html#270
512#[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    // This should get compiled out:
527    assert!(Scalar::<C>::NUM_LIMBS <= Coordinate::<C>::NUM_LIMBS);
528    // IntMod limbs are currently always bytes
529    if sig.len() != Scalar::<C>::NUM_LIMBS * 2 {
530        return Err(Error::new());
531    }
532    // Signature is default encoded in big endian bytes
533    let (r_be, s_be) = sig.split_at(<C as IntrinsicCurve>::Scalar::NUM_LIMBS);
534    // Note: Scalar internally stores using little endian
535    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    // Perf: don't use bits2field from ::ecdsa
542    let prehash_bytes = bits2field::<C>(prehash)?;
543    // If prehash is longer than Scalar::NUM_LIMBS, take leftmost bytes
544    let trim = prehash_bytes.len().saturating_sub(Scalar::<C>::NUM_LIMBS);
545    // from_be_bytes_unchecked zero-pads if len < Scalar::NUM_LIMBS
546    // we don't need to reduce because IntMod is up to modular equivalence
547    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    // public key
554    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    // Scalar and Coordinate may be different byte lengths, so we use an inefficient reduction
561    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}