Skip to main content

spongefish/drivers/
secp256k1_impl.rs

1//! secp256k1 (k256) codec implementations
2use k256::{
3    elliptic_curve::{
4        bigint::U512,
5        ff::{Field, PrimeField},
6        sec1::{FromEncodedPoint, ToEncodedPoint},
7    },
8    AffinePoint, EncodedPoint, ProjectivePoint, Scalar,
9};
10
11use crate::{
12    codecs::{Decoding, Encoding},
13    error::VerificationError,
14    io::NargDeserialize,
15    VerificationResult,
16};
17
18// Make k256 Scalar a valid Unit type
19impl crate::Unit for Scalar {
20    const ZERO: Self = <Self as Field>::ZERO;
21}
22
23// Implement Decoding for k256 Scalar
24impl Decoding<[u8]> for Scalar {
25    type Repr = super::Array64;
26
27    fn decode(buf: Self::Repr) -> Self {
28        use k256::elliptic_curve::ops::Reduce;
29        Self::reduce(U512::from_be_slice(&buf.0))
30    }
31}
32
33// Implement Deserialize for k256 Scalar using OS2IP (big-endian)
34impl NargDeserialize for Scalar {
35    fn deserialize_from_narg(buf: &mut &[u8]) -> VerificationResult<Self> {
36        let mut repr = <Self as PrimeField>::Repr::default();
37        let n = repr.len();
38        if buf.len() < n {
39            return Err(VerificationError);
40        }
41
42        repr.copy_from_slice(&buf[..n]);
43        Self::from_repr(repr)
44            .into_option()
45            .inspect(|_| *buf = &buf[n..])
46            .ok_or(VerificationError)
47    }
48}
49
50// Implement Deserialize for ProjectivePoint
51impl NargDeserialize for ProjectivePoint {
52    fn deserialize_from_narg(buf: &mut &[u8]) -> VerificationResult<Self> {
53        // Compressed points are 33 bytes
54        if buf.len() < 33 {
55            return Err(VerificationError);
56        }
57
58        let encoded = EncodedPoint::from_bytes(&buf[..33]).map_err(|_| VerificationError)?;
59        let point = Option::from(Self::from_encoded_point(&encoded)).ok_or(VerificationError)?;
60        *buf = &buf[33..];
61        Ok(point)
62    }
63}
64
65// Implement Encoding for k256 Scalar using I2OSP (big-endian)
66impl Encoding<[u8]> for Scalar {
67    fn encode(&self) -> impl AsRef<[u8]> {
68        self.to_bytes()
69    }
70}
71
72// Implement Encoding for ProjectivePoint
73impl Encoding<[u8]> for ProjectivePoint {
74    fn encode(&self) -> impl AsRef<[u8]> {
75        self.to_affine().to_encoded_point(true)
76    }
77}
78
79impl Encoding<[u8]> for AffinePoint {
80    fn encode(&self) -> impl AsRef<[u8]> {
81        self.to_encoded_point(true)
82    }
83}
84
85#[cfg(test)]
86mod tests {
87    use alloc::vec::Vec;
88
89    use super::*;
90    use crate::io::NargSerialize;
91
92    #[test]
93    fn test_scalar_serialize_deserialize() {
94        let scalar = Scalar::random(&mut rand::thread_rng());
95
96        let mut buf = Vec::new();
97        scalar.serialize_into_narg(&mut buf);
98
99        let mut buf_slice = &buf[..];
100        let deserialized = Scalar::deserialize_from_narg(&mut buf_slice).unwrap();
101        assert_eq!(scalar, deserialized);
102    }
103
104    #[test]
105    fn test_point_serialize_deserialize() {
106        use k256::elliptic_curve::Group;
107
108        let point = ProjectivePoint::random(&mut rand::thread_rng());
109
110        let mut buf = Vec::new();
111        point.serialize_into_narg(&mut buf);
112
113        let mut buf_slice = &buf[..];
114        let deserialized = ProjectivePoint::deserialize_from_narg(&mut buf_slice).unwrap();
115        assert_eq!(point, deserialized);
116    }
117
118    #[test]
119    fn test_scalar_encoding() {
120        let scalar = Scalar::random(&mut rand::thread_rng());
121
122        let encoded = scalar.encode();
123        let encoded_bytes = encoded.as_ref();
124
125        let mut buf_slice = encoded_bytes;
126        let deserialized = Scalar::deserialize_from_narg(&mut buf_slice).unwrap();
127        assert_eq!(scalar, deserialized);
128    }
129
130    #[test]
131    fn test_decoding() {
132        let buf = super::super::Array64::default();
133        let scalar = Scalar::decode(buf);
134        assert_eq!(scalar, Scalar::ZERO);
135    }
136}