midnight_transient_crypto/
curve.rs1use crate::macros::{fr_display, wrap_display, wrap_field_arith, wrap_group_arith};
22use base_crypto::fab::{Aligned, Alignment, AlignmentAtom, AlignmentSegment};
23use fake::{Dummy, Faker};
24use ff::{Field, FromUniformBytes, PrimeField};
25use group::Group;
26use group::GroupEncoding;
27use midnight_circuits::ecc::curves::CircuitCurve;
28#[cfg(feature = "proptest")]
29use proptest::prelude::Arbitrary;
30use rand::Rng;
31use rand::distributions::Standard;
32use rand::prelude::Distribution;
33use serde::{Deserialize, Deserializer, Serialize, Serializer, ser::Error as SerError};
34use serialize::ScaleBigInt;
35use serialize::Tagged;
36use serialize::tag_enforcement_test;
37use serialize::{Deserializable, Serializable};
38#[cfg(feature = "proptest")]
39use serialize::{NoStrategy, randomised_serialization_test, simple_arbitrary};
40use std::cmp::Ordering;
41use std::hash::Hasher;
42use std::io::{self, Read, Write};
43#[cfg(feature = "proptest")]
44use std::marker::PhantomData;
45use std::mem::size_of;
46use std::ops::Mul;
47use storage_core::{Storable, arena::ArenaKey, db::DB, storable::Loader};
48use zeroize::DefaultIsZeroes;
49
50pub mod outer {
52 pub type Base = midnight_curves::Fp;
54 pub type Scalar = midnight_curves::Fq;
56 pub type Affine = midnight_curves::G1Affine;
58 pub const POINT_BYTES: usize = Affine::compressed_size();
60}
61
62pub mod embedded {
64 pub type Base = midnight_curves::Fq;
66 pub type Scalar = midnight_curves::Fr;
68 pub type AffineExtended = midnight_curves::JubjubExtended;
71 pub type Affine = midnight_curves::JubjubSubgroup;
73}
74
75macro_rules! field_serialize {
88 ($name:ident, $wrapped:ty, $to_bytes:ident) => {
89 impl Serialize for $name {
90 fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
91 let mut vec = Vec::new();
92 <$name as Serializable>::serialize(self, &mut vec).map_err(S::Error::custom)?;
93 ser.serialize_bytes(&vec)
94 }
95 }
96
97 impl<'de> Deserialize<'de> for $name {
98 fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
99 let bytes = serde_bytes::ByteBuf::deserialize(de)?;
100 <$name as Deserializable>::deserialize(&mut &bytes[..], 0)
101 .map_err(serde::de::Error::custom)
102 }
103 }
104
105 impl From<$name> for ScaleBigInt {
106 fn from(val: $name) -> ScaleBigInt {
107 let mut res = ScaleBigInt::default();
108 let repr = val.0.to_repr();
109 res.0[..repr.len()].copy_from_slice(&repr);
110 res
111 }
112 }
113
114 impl TryFrom<ScaleBigInt> for $name {
115 type Error = std::io::Error;
116 fn try_from(val: ScaleBigInt) -> std::io::Result<$name> {
117 if val.0[FR_BYTES..].iter().any(|b| *b != 0) {
118 return Err(std::io::Error::new(
119 std::io::ErrorKind::InvalidData,
120 concat!("out of range for ", stringify!($ty)),
121 ));
122 }
123 let cont_buf: [u8; FR_BYTES] = val.0[..FR_BYTES]
124 .try_into()
125 .expect("slice of known size must coerce to array");
126 Ok($name(
127 <Option<_>>::from(<$wrapped>::from_repr(cont_buf.into())).ok_or_else(|| {
128 io::Error::new(
129 io::ErrorKind::InvalidData,
130 concat!("out of range for ", stringify!($name)),
131 )
132 })?,
133 ))
134 }
135 }
136
137 impl Serializable for $name {
138 fn serialize(&self, writer: &mut impl Write) -> io::Result<()> {
139 ScaleBigInt::from(*self).serialize(writer)
140 }
141
142 fn serialized_size(&self) -> usize {
143 ScaleBigInt::from(*self).serialized_size()
144 }
145 }
146
147 impl Deserializable for $name {
148 fn deserialize(reader: &mut impl Read, recursion_depth: u32) -> io::Result<Self> {
149 <$name>::try_from(ScaleBigInt::deserialize(reader, recursion_depth)?)
150 }
151 }
152 };
153}
154
155#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Storable)]
157#[storable(base)]
158pub struct Fr(pub outer::Scalar);
159wrap_field_arith!(Fr);
160fr_display!(Fr);
161field_serialize!(Fr, outer::Scalar, to_bytes_le);
162#[cfg(feature = "proptest")]
163randomised_serialization_test!(Fr);
164#[cfg(feature = "proptest")]
165simple_arbitrary!(Fr);
166
167impl DefaultIsZeroes for Fr {}
168
169impl Tagged for Fr {
170 fn tag() -> std::borrow::Cow<'static, str> {
171 std::borrow::Cow::Borrowed("fr-bls")
172 }
173 fn tag_unique_factor() -> String {
174 "fr-bls".into()
175 }
176}
177tag_enforcement_test!(Fr);
178
179impl std::hash::Hash for Fr {
180 fn hash<H: Hasher>(&self, state: &mut H) {
181 state.write(&self.0.to_bytes_le()[..]);
182 }
183}
184
185impl Distribution<Fr> for Standard {
186 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Fr {
187 Fr(outer::Scalar::random(rng))
188 }
189}
190
191pub const FR_BITS: usize = <outer::Scalar as PrimeField>::NUM_BITS as usize;
193pub const FR_BYTES: usize = FR_BITS.div_ceil(8);
195pub const FR_BYTES_STORED: usize = FR_BYTES - 1;
197
198impl Dummy<Faker> for Fr {
199 fn dummy_with_rng<R: Rng + ?Sized>(_: &Faker, rng: &mut R) -> Self {
200 rng.r#gen()
201 }
202}
203
204#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Storable)]
206#[storable(base)]
207pub struct EmbeddedFr(pub embedded::Scalar);
208wrap_field_arith!(EmbeddedFr);
209fr_display!(EmbeddedFr);
210field_serialize!(EmbeddedFr, embedded::Scalar, to_bytes);
211#[cfg(feature = "proptest")]
212randomised_serialization_test!(EmbeddedFr);
213#[cfg(feature = "proptest")]
214simple_arbitrary!(EmbeddedFr);
215
216impl Tagged for EmbeddedFr {
217 fn tag() -> std::borrow::Cow<'static, str> {
218 std::borrow::Cow::Borrowed("embedded-fr[v1]")
219 }
220 fn tag_unique_factor() -> String {
221 "embedded-fr[v1]".into()
222 }
223}
224tag_enforcement_test!(EmbeddedFr);
225
226impl DefaultIsZeroes for EmbeddedFr {}
227
228impl Distribution<EmbeddedFr> for Standard {
229 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> EmbeddedFr {
230 EmbeddedFr(embedded::Scalar::random(rng))
231 }
232}
233
234impl Dummy<Faker> for EmbeddedFr {
235 fn dummy_with_rng<R: Rng + ?Sized>(_: &Faker, rng: &mut R) -> Self {
236 rng.r#gen()
237 }
238}
239
240macro_rules! derive_via {
241 ($base:ty, $via:ty, $($ty:ty),*) => {
242 $(
243 impl From<$ty> for $base {
244 fn from(val: $ty) -> $base {
245 (val as $via).into()
246 }
247 }
248 )*
249 }
250}
251
252macro_rules! derive_signed {
253 ($base:ty, $($ty:ty, $via:ty),*) => {
254 $(
255 impl From<$ty> for $base {
256 fn from(val: $ty) -> $base {
257 if val < 0 {
258 -<$base>::from(val.unsigned_abs())
259 } else {
260 (val as $via).into()
261 }
262 }
263 }
264 )*
265 }
266}
267
268impl From<bool> for Fr {
269 fn from(val: bool) -> Fr {
270 Fr(outer::Scalar::from(u64::from(val)))
271 }
272}
273
274derive_via!(Fr, u64, u8, u16, u32);
275derive_signed!(Fr, i8, u8, i16, u16, i32, u32, i64, u64, i128, u128);
276derive_via!(EmbeddedFr, u64, u8, u16, u32);
277derive_signed!(EmbeddedFr, i8, u8, i16, u16, i32, u32, i64, u64, i128, u128);
278
279impl From<u64> for Fr {
280 fn from(val: u64) -> Fr {
281 Fr(outer::Scalar::from(val))
282 }
283}
284
285impl From<u128> for Fr {
286 fn from(val: u128) -> Fr {
287 Fr(outer::Scalar::from_u128(val))
288 }
289}
290
291impl Aligned for Fr {
292 fn alignment() -> Alignment {
293 Alignment::singleton(AlignmentAtom::Field)
294 }
295}
296
297impl Aligned for EmbeddedFr {
298 fn alignment() -> Alignment {
299 Alignment::singleton(AlignmentAtom::Field)
300 }
301}
302
303impl Aligned for EmbeddedGroupAffine {
304 fn alignment() -> Alignment {
305 Alignment(vec![
306 AlignmentSegment::Atom(AlignmentAtom::Field),
307 AlignmentSegment::Atom(AlignmentAtom::Field),
308 ])
309 }
310}
311
312impl From<bool> for EmbeddedFr {
313 fn from(val: bool) -> EmbeddedFr {
314 EmbeddedFr(embedded::Scalar::from(u64::from(val)))
315 }
316}
317
318impl From<u64> for EmbeddedFr {
319 fn from(val: u64) -> EmbeddedFr {
320 EmbeddedFr(embedded::Scalar::from(val))
321 }
322}
323
324impl From<u128> for EmbeddedFr {
325 fn from(val: u128) -> EmbeddedFr {
326 EmbeddedFr(embedded::Scalar::from_u128(val))
327 }
328}
329
330impl TryFrom<EmbeddedFr> for Fr {
331 type Error = ();
332 fn try_from(val: EmbeddedFr) -> Result<Fr, Self::Error> {
333 Fr::from_le_bytes(&val.as_le_bytes()).ok_or(())
334 }
335}
336
337impl TryFrom<Fr> for EmbeddedFr {
338 type Error = ();
339 fn try_from(val: Fr) -> Result<EmbeddedFr, Self::Error> {
340 EmbeddedFr::from_le_bytes(&val.as_le_bytes()).ok_or(())
341 }
342}
343
344impl Fr {
345 pub fn from_le_bytes(bytes: &[u8]) -> Option<Self> {
347 let mut repr = [0u8; FR_BYTES];
348 if bytes.len() <= repr.len() {
349 repr[..bytes.len()].copy_from_slice(bytes)
350 } else {
351 return None;
352 }
353 outer::Scalar::from_repr(repr).map(Fr).into()
354 }
355
356 pub fn from_uniform_bytes(bytes: &[u8; 64]) -> Self {
359 Fr(outer::Scalar::from_uniform_bytes(bytes))
360 }
361
362 pub fn as_le_bytes(&self) -> Vec<u8> {
371 self.0.to_bytes_le().to_vec()
372 }
373}
374
375impl EmbeddedFr {
376 pub fn from_le_bytes(bytes: &[u8]) -> Option<Self> {
378 let mut repr = [0u8; FR_BYTES];
379 if bytes.len() <= repr.len() {
380 repr[..bytes.len()].copy_from_slice(bytes)
381 } else {
382 return None;
383 }
384 embedded::Scalar::from_repr(repr).map(EmbeddedFr).into()
385 }
386
387 pub fn from_le_bytes_wide(bytes: &[u8]) -> Option<Self> {
392 if bytes.len() > FR_BYTES {
393 return None;
394 }
395 let mut wide = [0u8; 64];
396 wide[..bytes.len()].copy_from_slice(bytes);
397 Some(EmbeddedFr(embedded::Scalar::from_bytes_wide(&wide)))
398 }
399
400 pub fn as_le_bytes(&self) -> Vec<u8> {
402 self.0.to_bytes().to_vec()
403 }
404}
405
406#[derive(Default, Copy, Clone, Storable)]
408#[storable(base)]
409pub struct EmbeddedGroupAffine(pub embedded::Affine);
410
411wrap_group_arith!(EmbeddedGroupAffine, EmbeddedFr);
412wrap_display!(EmbeddedGroupAffine);
413#[cfg(feature = "proptest")]
414randomised_serialization_test!(EmbeddedGroupAffine);
415#[cfg(feature = "proptest")]
416simple_arbitrary!(EmbeddedGroupAffine);
417
418impl Distribution<EmbeddedGroupAffine> for Standard {
419 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> EmbeddedGroupAffine {
420 EmbeddedGroupAffine(embedded::Affine::random(rng))
421 }
422}
423
424impl Mul<Fr> for EmbeddedGroupAffine {
425 type Output = EmbeddedGroupAffine;
426
427 fn mul(self, mut rhs: Fr) -> EmbeddedGroupAffine {
428 let embedded_m1 = EmbeddedFr::from(0u64) - EmbeddedFr::from(1u64);
429 let embedded_modulus = Fr::from_le_bytes(&embedded_m1.as_le_bytes())
430 .expect("embedded modulus should fit in scalar field")
431 + Fr::from(1);
432 while rhs >= embedded_modulus {
433 rhs = rhs - embedded_modulus;
434 }
435 self * EmbeddedFr::try_from(rhs).expect("after reducing, rhs should fit in embedded scalar")
436 }
437}
438
439impl From<embedded::Affine> for EmbeddedGroupAffine {
440 fn from(g: embedded::Affine) -> Self {
441 Self(g)
442 }
443}
444
445impl Dummy<Faker> for EmbeddedGroupAffine {
446 fn dummy_with_rng<R: Rng + ?Sized>(f: &Faker, rng: &mut R) -> Self {
447 EmbeddedGroupAffine::generator() * EmbeddedFr::dummy_with_rng(f, rng)
448 }
449}
450
451impl serde::Serialize for EmbeddedGroupAffine {
452 fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
453 let mut vec = Vec::new();
454 <EmbeddedGroupAffine as Serializable>::serialize(self, &mut vec)
455 .map_err(<S::Error as serde::ser::Error>::custom)?;
456 ser.serialize_bytes(&vec)
457 }
458}
459
460impl Serializable for EmbeddedGroupAffine {
461 fn serialize(&self, writer: &mut impl Write) -> std::io::Result<()> {
462 writer.write_all(self.0.to_bytes().as_ref())
463 }
464
465 fn serialized_size(&self) -> usize {
466 size_of::<<embedded::Affine as GroupEncoding>::Repr>()
467 }
468}
469
470impl Deserializable for EmbeddedGroupAffine {
471 fn deserialize(reader: &mut impl Read, _recursion_depth: u32) -> std::io::Result<Self> {
472 let mut data = <<embedded::AffineExtended as GroupEncoding>::Repr>::default();
473 reader.read_exact(data.as_mut())?;
474 <Option<_>>::from(embedded::Affine::from_bytes(&data).map(EmbeddedGroupAffine)).ok_or_else(
475 || {
476 std::io::Error::new(
477 std::io::ErrorKind::InvalidData,
478 "invalid group element encoding",
479 )
480 },
481 )
482 }
483}
484
485impl Tagged for EmbeddedGroupAffine {
486 fn tag() -> std::borrow::Cow<'static, str> {
487 std::borrow::Cow::Borrowed("embedded-group-affine[v1]")
488 }
489 fn tag_unique_factor() -> String {
490 "embedded-group-affine[v1]".into()
491 }
492}
493tag_enforcement_test!(EmbeddedGroupAffine);
494
495impl EmbeddedGroupAffine {
496 pub fn new(x: Fr, y: Fr) -> Option<Self> {
499 embedded::AffineExtended::from_xy(x.0, y.0).map(|p| EmbeddedGroupAffine(p.into_subgroup()))
500 }
501
502 pub fn x(&self) -> Option<Fr> {
505 Into::<embedded::AffineExtended>::into(self.0)
506 .coordinates()
507 .map(|c| Fr(c.0))
508 }
509
510 pub fn y(&self) -> Option<Fr> {
513 Into::<embedded::AffineExtended>::into(self.0)
514 .coordinates()
515 .map(|c| Fr(c.1))
516 }
517
518 pub fn generator() -> Self {
520 EmbeddedGroupAffine(embedded::Affine::generator())
521 }
522
523 pub fn identity() -> Self {
525 EmbeddedGroupAffine(embedded::Affine::identity())
526 }
527
528 pub fn is_identity(&self) -> bool {
530 self.0.is_identity().into()
531 }
532
533 pub fn is_infinity(&self) -> bool {
535 false
536 }
537
538 pub const HAS_INFINITY: bool = false;
540}
541
542impl PartialOrd for EmbeddedGroupAffine {
543 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
544 Some(self.cmp(other))
545 }
546}
547
548impl std::hash::Hash for EmbeddedGroupAffine {
549 fn hash<H: Hasher>(&self, state: &mut H) {
550 self.x().hash(state);
551 self.y().hash(state);
552 }
553}
554
555impl PartialEq for EmbeddedGroupAffine {
556 fn eq(&self, other: &EmbeddedGroupAffine) -> bool {
557 (self.x(), self.y()) == (other.x(), other.y())
558 }
559}
560
561impl Eq for EmbeddedGroupAffine {}
562
563impl Ord for EmbeddedGroupAffine {
564 fn cmp(&self, other: &Self) -> Ordering {
565 let a: Option<(embedded::Base, embedded::Base)> =
566 Into::<embedded::AffineExtended>::into(self.0).coordinates();
567 let b: Option<(embedded::Base, embedded::Base)> =
568 Into::<embedded::AffineExtended>::into(other.0).coordinates();
569 a.cmp(&b)
570 }
571}
572
573impl AsRef<outer::Scalar> for Fr {
574 fn as_ref(&self) -> &outer::Scalar {
575 &self.0
576 }
577}
578
579impl AsRef<embedded::Scalar> for EmbeddedFr {
580 fn as_ref(&self) -> &embedded::Scalar {
581 &self.0
582 }
583}
584
585impl AsRef<embedded::Affine> for EmbeddedGroupAffine {
586 fn as_ref(&self) -> &embedded::Affine {
587 &self.0
588 }
589}
590
591macro_rules! impl_smaller_ints {
592 ($($ty:ty),* => $via:ty) => {
593 $(
594 impl TryFrom<Fr> for $ty {
595 type Error = ();
596 fn try_from(f: Fr) -> Result<$ty, ()> {
597 <$via>::try_from(f)?.try_into().map_err(|_| ())
598 }
599 }
600 )*
601 }
602}
603
604impl TryFrom<Fr> for u128 {
605 type Error = ();
606 fn try_from(f: Fr) -> Result<u128, ()> {
607 let repr = f.0.to_repr();
608 let limbs = repr.as_ref();
609 if limbs[16..].iter().any(|limb| limb != &0) {
610 Err(())
611 } else {
612 Ok(limbs[..16].iter().enumerate().fold(0, |acc, (i, byte)| {
613 acc + ((*byte as u128) << (8 * i as u128))
614 }))
615 }
616 }
617}
618
619impl_smaller_ints!(u8, u16, u32, u64 => u128);
620
621impl TryFrom<Fr> for i128 {
622 type Error = ();
623 fn try_from(f: Fr) -> Result<i128, ()> {
624 let positive_attempt = u128::try_from(f)
625 .ok()
626 .and_then(|uint| i128::try_from(uint).ok());
627 if let Some(pos) = positive_attempt {
628 return Ok(pos);
629 }
630 let negative_attempt = u128::try_from(-f)
631 .ok()
632 .and_then(|uint| i128::checked_sub_unsigned(0i128, uint));
633 if let Some(neg) = negative_attempt {
634 return Ok(neg);
635 }
636 Err(())
637 }
638}
639
640impl_smaller_ints!(i8, i16, i32, i64 => i128);
641
642impl TryFrom<Fr> for bool {
643 type Error = ();
644 fn try_from(f: Fr) -> Result<bool, ()> {
645 match u64::try_from(f)? {
646 0 => Ok(false),
647 1 => Ok(true),
648 _ => Err(()),
649 }
650 }
651}
652
653#[cfg(test)]
654mod tests {
655 use super::*;
656
657 #[test]
658 fn test_fr_le_bytes() {
659 let val = 0x1234u16;
660 let val_le = val.to_le_bytes();
661 assert_eq!(val_le, [0x34, 0x12]);
662 assert_eq!(Fr::from_le_bytes(&val_le).unwrap(), val.into());
663 let restored = Fr::from(val).as_le_bytes();
664 assert_eq!(&restored[..2], &val_le);
665 assert_eq!(&restored[2..], &[0u8; 30]);
666 }
667
668 #[test]
669 fn test_identity_point() {
670 let id = EmbeddedGroupAffine::identity();
671 assert_eq!((id.x(), id.y()), (Some(0.into()), Some(1.into())));
672 assert!(!id.is_infinity());
673 }
674
675 #[test]
676 fn test_identity() {
677 let id = EmbeddedGroupAffine::identity();
678 assert_eq!(id * Fr::from(42), id);
679 }
680
681 #[test]
682 fn embedded_fr_within_fr() {
683 let embedded_m1 = EmbeddedFr::from(0) - EmbeddedFr::from(1);
684 assert!(Fr::try_from(embedded_m1).is_ok());
685 let outer_m1 = Fr::from(0) - Fr::from(1);
686 assert!(EmbeddedFr::try_from(outer_m1).is_err());
687 }
688
689 #[test]
690 fn test_embedded_group_ser() {
691 let elem = EmbeddedGroupAffine::identity();
692 let mut writer = Vec::new();
693 Serializable::serialize(&elem, &mut writer).unwrap();
694 assert_eq!(
695 elem,
696 <EmbeddedGroupAffine as Deserializable>::deserialize(&mut writer.as_slice(), 0)
697 .unwrap()
698 );
699 }
700}