pairing_plus/
serdes.rs

1use bls12_381::{self, *};
2use ff::{PrimeField, PrimeFieldRepr};
3use std::io::{Error, ErrorKind, Read, Result, Write};
4use CurveAffine;
5use CurveProjective;
6use EncodedPoint;
7type Compressed = bool;
8
9/// Serialization support for group elements.
10pub trait SerDes: Sized {
11    /// Serialize a struct to a writer with a flag of compressness.
12    fn serialize<W: Write>(&self, writer: &mut W, compressed: Compressed) -> Result<()>;
13
14    /// Deserialize a struct; give an indicator if the element was compressed or not.
15    /// Returns an error is the encoding does not match the indicator.
16    fn deserialize<R: Read>(reader: &mut R, compressed: Compressed) -> Result<Self>;
17}
18
19impl SerDes for Fr {
20    /// The compressed parameter has no effect since Fr element will always be compressed.
21    fn serialize<W: Write>(&self, writer: &mut W, _compressed: Compressed) -> Result<()> {
22        self.into_repr().write_be(writer)
23    }
24
25    /// The compressed parameter has no effect since Fr element will always be compressed.
26    fn deserialize<R: Read>(reader: &mut R, _compressed: Compressed) -> Result<Self> {
27        let mut r = FrRepr::default();
28        r.read_be(reader)?;
29        match Fr::from_repr(r) {
30            Err(e) => Err(Error::new(ErrorKind::Other, e)),
31            Ok(p) => Ok(p),
32        }
33    }
34}
35
36impl SerDes for Fq12 {
37    /// The compressed parameter has no effect since Fr element will always be compressed.
38    fn serialize<W: Write>(&self, writer: &mut W, _compressed: Compressed) -> Result<()> {
39        let mut buf: Vec<u8> = vec![];
40
41        match self.c0.c0.c0.into_repr().write_be(&mut buf) {
42            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
43            Ok(p) => p,
44        };
45        match self.c0.c0.c1.into_repr().write_be(&mut buf) {
46            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
47            Ok(p) => p,
48        };
49        match self.c0.c1.c0.into_repr().write_be(&mut buf) {
50            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
51            Ok(p) => p,
52        };
53        match self.c0.c1.c1.into_repr().write_be(&mut buf) {
54            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
55            Ok(p) => p,
56        };
57        match self.c0.c2.c0.into_repr().write_be(&mut buf) {
58            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
59            Ok(p) => p,
60        };
61        match self.c0.c2.c1.into_repr().write_be(&mut buf) {
62            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
63            Ok(p) => p,
64        };
65        match self.c1.c0.c0.into_repr().write_be(&mut buf) {
66            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
67            Ok(p) => p,
68        };
69
70        match self.c1.c0.c1.into_repr().write_be(&mut buf) {
71            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
72            Ok(p) => p,
73        };
74        match self.c1.c1.c0.into_repr().write_be(&mut buf) {
75            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
76            Ok(p) => p,
77        };
78        match self.c1.c1.c1.into_repr().write_be(&mut buf) {
79            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
80            Ok(p) => p,
81        };
82        match self.c1.c2.c0.into_repr().write_be(&mut buf) {
83            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
84            Ok(p) => p,
85        };
86        match self.c1.c2.c1.into_repr().write_be(&mut buf) {
87            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
88            Ok(p) => p,
89        };
90        writer.write_all(&buf)?;
91        Ok(())
92    }
93
94    /// The compressed parameter has no effect since Fr element will always be compressed.
95    fn deserialize<R: Read>(mut reader: &mut R, _compressed: Compressed) -> Result<Self> {
96        let mut q = FqRepr::default();
97        q.read_be(&mut reader)?;
98        let c000 = match Fq::from_repr(q) {
99            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
100            Ok(q) => q,
101        };
102        q.read_be(&mut reader)?;
103        let c001 = match Fq::from_repr(q) {
104            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
105            Ok(q) => q,
106        };
107        q.read_be(&mut reader)?;
108        let c010 = match Fq::from_repr(q) {
109            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
110            Ok(q) => q,
111        };
112        q.read_be(&mut reader)?;
113        let c011 = match Fq::from_repr(q) {
114            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
115            Ok(q) => q,
116        };
117        q.read_be(&mut reader)?;
118        let c020 = match Fq::from_repr(q) {
119            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
120            Ok(q) => q,
121        };
122        q.read_be(&mut reader)?;
123        let c021 = match Fq::from_repr(q) {
124            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
125            Ok(q) => q,
126        };
127        q.read_be(&mut reader)?;
128        let c100 = match Fq::from_repr(q) {
129            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
130            Ok(q) => q,
131        };
132        q.read_be(&mut reader)?;
133        let c101 = match Fq::from_repr(q) {
134            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
135            Ok(q) => q,
136        };
137        q.read_be(&mut reader)?;
138        let c110 = match Fq::from_repr(q) {
139            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
140            Ok(q) => q,
141        };
142        q.read_be(&mut reader)?;
143        let c111 = match Fq::from_repr(q) {
144            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
145            Ok(q) => q,
146        };
147        q.read_be(&mut reader)?;
148        let c120 = match Fq::from_repr(q) {
149            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
150            Ok(q) => q,
151        };
152        q.read_be(&mut reader)?;
153        let c121 = match Fq::from_repr(q) {
154            Err(e) => return Err(Error::new(ErrorKind::Other, e)),
155            Ok(q) => q,
156        };
157        Ok(Fq12 {
158            c0: Fq6 {
159                c0: Fq2 { c0: c000, c1: c001 },
160
161                c1: Fq2 { c0: c010, c1: c011 },
162
163                c2: Fq2 { c0: c020, c1: c021 },
164            },
165            c1: Fq6 {
166                c0: Fq2 { c0: c100, c1: c101 },
167
168                c1: Fq2 { c0: c110, c1: c111 },
169
170                c2: Fq2 { c0: c120, c1: c121 },
171            },
172        })
173    }
174}
175
176impl SerDes for G1 {
177    /// Convert a G1 point to a blob.
178    fn serialize<W: Write>(&self, writer: &mut W, compressed: Compressed) -> Result<()> {
179        let t = self.into_affine();
180
181        // convert element into an (un)compressed byte string
182        let buf = {
183            if compressed {
184                let tmp = bls12_381::G1Compressed::from_affine(t);
185                tmp.as_ref().to_vec()
186            } else {
187                let tmp = bls12_381::G1Uncompressed::from_affine(t);
188                tmp.as_ref().to_vec()
189            }
190        };
191
192        // format the output
193        writer.write_all(&buf)?;
194        Ok(())
195    }
196
197    /// Deserialize a G1 element from a blob.
198    /// Returns an error if deserialization fails.
199    fn deserialize<R: Read>(reader: &mut R, compressed: Compressed) -> Result<Self> {
200        // read into buf of compressed size
201        let mut buf = vec![0u8; G1Compressed::size()];
202        reader.read_exact(&mut buf)?;
203
204        // check the first bit of buf[0] to decide if the point is compressed
205        // or not
206        // first bit is 1 => compressed mode
207        // first bit is 0 => uncompressed mode
208        if ((buf[0] & 0x80) == 0x80) != compressed {
209            return Err(Error::new(ErrorKind::InvalidData, "Invalid compressness"));
210        }
211
212        if compressed {
213            // convert the blob into a group element
214            let mut g_buf = G1Compressed::empty();
215            g_buf.as_mut().copy_from_slice(&buf);
216            let g = match g_buf.into_affine() {
217                Ok(p) => p.into_projective(),
218                Err(e) => return Err(Error::new(ErrorKind::InvalidData, e)),
219            };
220            Ok(g)
221        } else {
222            // read the next uncompressed - compressed size
223            let mut buf2 = vec![0u8; G1Uncompressed::size() - G1Compressed::size()];
224            reader.read_exact(&mut buf2)?;
225            // now buf holds the whole uncompressed bytes
226            buf.append(&mut buf2);
227            // convert the buf into a group element
228            let mut g_buf = G1Uncompressed::empty();
229            g_buf.as_mut().copy_from_slice(&buf);
230            let g = match g_buf.into_affine() {
231                Ok(p) => p.into_projective(),
232                Err(e) => return Err(Error::new(ErrorKind::InvalidData, e)),
233            };
234            Ok(g)
235        }
236    }
237}
238
239impl SerDes for G2 {
240    /// Convert a G2 point to a blob.
241    fn serialize<W: Write>(&self, writer: &mut W, compressed: Compressed) -> Result<()> {
242        let t = self.into_affine();
243        // convert element into an (un)compressed byte string
244        let buf = {
245            if compressed {
246                let tmp = bls12_381::G2Compressed::from_affine(t);
247                tmp.as_ref().to_vec()
248            } else {
249                let tmp = bls12_381::G2Uncompressed::from_affine(t);
250                tmp.as_ref().to_vec()
251            }
252        };
253
254        // format the output
255        writer.write_all(&buf)?;
256        Ok(())
257    }
258
259    /// Deserialize a G2 element from a blob.
260    /// Returns an error if deserialization fails.
261    fn deserialize<R: Read>(reader: &mut R, compressed: Compressed) -> Result<Self> {
262        // read into buf of compressed size
263        let mut buf = vec![0u8; G2Compressed::size()];
264        reader.read_exact(&mut buf)?;
265
266        // check the first bit of buf[0] to decide if the point is compressed
267        // or not
268        // first bit is 1 => compressed mode
269        // first bit is 0 => uncompressed mode
270        if ((buf[0] & 0x80) == 0x80) != compressed {
271            return Err(Error::new(ErrorKind::InvalidData, "Invalid compressness"));
272        }
273
274        if compressed {
275            // convert the buf into a group element
276            let mut g_buf = G2Compressed::empty();
277            g_buf.as_mut().copy_from_slice(&buf);
278            let g = match g_buf.into_affine() {
279                Ok(p) => p.into_projective(),
280                Err(e) => return Err(Error::new(ErrorKind::InvalidData, e)),
281            };
282            Ok(g)
283        } else {
284            // read the next uncompressed - compressed size
285            let mut buf2 = vec![0u8; G2Uncompressed::size() - G2Compressed::size()];
286            reader.read_exact(&mut buf2)?;
287            // now buf holds the whole uncompressed bytes
288            buf.append(&mut buf2);
289            // convert the buf into a group element
290            let mut g_buf = G2Uncompressed::empty();
291            g_buf.as_mut().copy_from_slice(&buf);
292            let g = match g_buf.into_affine() {
293                Ok(p) => p.into_projective(),
294                Err(e) => return Err(Error::new(ErrorKind::InvalidData, e)),
295            };
296            Ok(g)
297        }
298    }
299}
300
301impl SerDes for G1Affine {
302    /// Convert a G1 point to a blob.
303    fn serialize<W: Write>(&self, writer: &mut W, compressed: Compressed) -> Result<()> {
304        // convert element into an (un)compressed byte string
305        let buf = {
306            if compressed {
307                let tmp = bls12_381::G1Compressed::from_affine(*self);
308                tmp.as_ref().to_vec()
309            } else {
310                let tmp = bls12_381::G1Uncompressed::from_affine(*self);
311                tmp.as_ref().to_vec()
312            }
313        };
314
315        // format the output
316        writer.write_all(&buf)?;
317        Ok(())
318    }
319
320    /// Deserialize a G1 element from a blob.
321    /// Returns an error if deserialization fails.
322    fn deserialize<R: Read>(reader: &mut R, compressed: Compressed) -> Result<Self> {
323        // read into buf of compressed size
324        let mut buf = vec![0u8; G1Compressed::size()];
325        reader.read_exact(&mut buf)?;
326
327        // check the first bit of buf[0] to decide if the point is compressed
328        // or not
329        // first bit is 1 => compressed mode
330        // first bit is 0 => uncompressed mode
331        if ((buf[0] & 0x80) == 0x80) != compressed {
332            return Err(Error::new(ErrorKind::InvalidData, "Invalid compressness"));
333        }
334
335        if compressed {
336            // convert the blob into a group element
337            let mut g_buf = G1Compressed::empty();
338            g_buf.as_mut().copy_from_slice(&buf);
339            let g = match g_buf.into_affine() {
340                Ok(p) => p,
341                Err(e) => return Err(Error::new(ErrorKind::InvalidData, e)),
342            };
343            Ok(g)
344        } else {
345            // read the next uncompressed - compressed size
346            let mut buf2 = vec![0u8; G1Uncompressed::size() - G1Compressed::size()];
347            reader.read_exact(&mut buf2)?;
348            // now buf holds the whole uncompressed bytes
349            buf.append(&mut buf2);
350            // convert the buf into a group element
351            let mut g_buf = G1Uncompressed::empty();
352            g_buf.as_mut().copy_from_slice(&buf);
353            let g = match g_buf.into_affine() {
354                Ok(p) => p,
355                Err(e) => return Err(Error::new(ErrorKind::InvalidData, e)),
356            };
357            Ok(g)
358        }
359    }
360}
361
362impl SerDes for G2Affine {
363    /// Convert a G2 point to a blob.
364    fn serialize<W: Write>(&self, writer: &mut W, compressed: Compressed) -> Result<()> {
365        // convert element into an (un)compressed byte string
366        let buf = {
367            if compressed {
368                let tmp = bls12_381::G2Compressed::from_affine(*self);
369                tmp.as_ref().to_vec()
370            } else {
371                let tmp = bls12_381::G2Uncompressed::from_affine(*self);
372                tmp.as_ref().to_vec()
373            }
374        };
375
376        // format the output
377        writer.write_all(&buf)?;
378        Ok(())
379    }
380
381    /// Deserialize a G2 element from a blob.
382    /// Returns an error if deserialization fails.
383    fn deserialize<R: Read>(reader: &mut R, compressed: Compressed) -> Result<Self> {
384        // read into buf of compressed size
385        let mut buf = vec![0u8; G2Compressed::size()];
386        reader.read_exact(&mut buf)?;
387
388        // check the first bit of buf[0] to decide if the point is compressed
389        // or not
390        // first bit is 1 => compressed mode
391        // first bit is 0 => uncompressed mode
392        if ((buf[0] & 0x80) == 0x80) != compressed {
393            return Err(Error::new(ErrorKind::InvalidData, "Invalid compressness"));
394        }
395
396        if compressed {
397            // convert the buf into a group element
398            let mut g_buf = G2Compressed::empty();
399            g_buf.as_mut().copy_from_slice(&buf);
400            let g = match g_buf.into_affine() {
401                Ok(p) => p,
402                Err(e) => return Err(Error::new(ErrorKind::InvalidData, e)),
403            };
404            Ok(g)
405        } else {
406            // read the next uncompressed - compressed size
407            let mut buf2 = vec![0u8; G2Uncompressed::size() - G2Compressed::size()];
408            reader.read_exact(&mut buf2)?;
409            // now buf holds the whole uncompressed bytes
410            buf.append(&mut buf2);
411            // convert the buf into a group element
412            let mut g_buf = G2Uncompressed::empty();
413            g_buf.as_mut().copy_from_slice(&buf);
414            let g = match g_buf.into_affine() {
415                Ok(p) => p,
416                Err(e) => return Err(Error::new(ErrorKind::InvalidData, e)),
417            };
418            Ok(g)
419        }
420    }
421}
422
423#[cfg(test)]
424mod serdes_test {
425    use super::*;
426    use rand_core::SeedableRng;
427    #[test]
428    fn test_g1_serialization_rand() {
429        let mut rng = rand_xorshift::XorShiftRng::from_seed([
430            0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06,
431            0xbc, 0xe5,
432        ]);
433
434        // G1::zero, compressed
435        let g1_zero = G1::zero();
436        let mut buf: Vec<u8> = vec![];
437        // serialize a G1 element into buffer
438        assert!(g1_zero.serialize(&mut buf, true).is_ok());
439        assert_eq!(buf.len(), 48, "length of blob is incorrect");
440        let g1_zero_recover = G1::deserialize(&mut buf[..].as_ref(), true).unwrap();
441        assert_eq!(g1_zero, g1_zero_recover);
442
443        // G1::one, compressed
444        let g1_one = G1::one();
445        let mut buf: Vec<u8> = vec![];
446        // serialize a G1 element into buffer
447        assert!(g1_one.serialize(&mut buf, true).is_ok());
448        assert_eq!(buf.len(), 48, "length of blob is incorrect");
449        let g1_one_recover = G1::deserialize(&mut buf[..].as_ref(), true).unwrap();
450        assert_eq!(g1_one, g1_one_recover);
451
452        // G1::rand, compressed
453        let g1_rand = G1::random(&mut rng);
454        let mut buf: Vec<u8> = vec![];
455        // serialize a G1 element into buffer
456        assert!(g1_rand.serialize(&mut buf, true).is_ok());
457        assert_eq!(buf.len(), 48, "length of blob is incorrect");
458        let g1_rand_recover = G1::deserialize(&mut buf[..].as_ref(), true).unwrap();
459
460        assert_eq!(g1_rand, g1_rand_recover);
461
462        // G1::zero, uncompressed
463        let mut buf: Vec<u8> = vec![];
464        // serialize a G1 element into buffer
465        assert!(g1_zero.serialize(&mut buf, false).is_ok());
466        assert_eq!(buf.len(), 96, "length of blob is incorrect");
467        let g1_zero_recover = G1::deserialize(&mut buf[..].as_ref(), false).unwrap();
468        assert_eq!(g1_zero, g1_zero_recover);
469
470        // G1::one, uncompressed
471        let mut buf: Vec<u8> = vec![];
472        // serialize a G1 element into buffer
473        assert!(g1_one.serialize(&mut buf, false).is_ok());
474        assert_eq!(buf.len(), 96, "length of blob is incorrect");
475        let g1_one_recover = G1::deserialize(&mut buf[..].as_ref(), false).unwrap();
476        assert_eq!(g1_one, g1_one_recover);
477
478        // G1::rand, uncompressed
479        let g1_rand = G1::random(&mut rng);
480        let mut buf: Vec<u8> = vec![];
481        // serialize a G1 element into buffer
482        assert!(g1_rand.serialize(&mut buf, false).is_ok());
483        assert_eq!(buf.len(), 96, "length of blob is incorrect");
484        let g1_rand_recover = G1::deserialize(&mut buf[..].as_ref(), false).unwrap();
485        assert_eq!(g1_rand, g1_rand_recover);
486    }
487
488    #[test]
489    fn test_g2_serialization_rand() {
490        let mut rng = rand_xorshift::XorShiftRng::from_seed([
491            0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06,
492            0xbc, 0xe5,
493        ]);
494        // G2::zero, compressed
495        let g2_zero = G2::zero();
496        let mut buf: Vec<u8> = vec![];
497        // serialize a G2 element into buffer
498        assert!(g2_zero.serialize(&mut buf, true).is_ok());
499        assert_eq!(buf.len(), 96, "length of blob is incorrect");
500        let g2_zero_recover = G2::deserialize(&mut buf[..].as_ref(), true).unwrap();
501        assert_eq!(g2_zero, g2_zero_recover);
502
503        // G2::one, compressed
504        let g2_one = G2::one();
505        let mut buf: Vec<u8> = vec![];
506        // serialize a G2 element into buffer
507        assert!(g2_one.serialize(&mut buf, true).is_ok());
508        assert_eq!(buf.len(), 96, "length of blob is incorrect");
509        let g2_one_recover = G2::deserialize(&mut buf[..].as_ref(), true).unwrap();
510        assert_eq!(g2_one, g2_one_recover);
511
512        // G2::rand, compressed
513        let g2_rand = G2::random(&mut rng);
514        let mut buf: Vec<u8> = vec![];
515        // serialize a G2 element into buffer
516        assert!(g2_rand.serialize(&mut buf, true).is_ok());
517        assert_eq!(buf.len(), 96, "length of blob is incorrect");
518        let g2_rand_recover = G2::deserialize(&mut buf[..].as_ref(), true).unwrap();
519        assert_eq!(g2_rand, g2_rand_recover);
520
521        // G2::zero, uncompressed
522        let mut buf: Vec<u8> = vec![];
523        // serialize a G2 element into buffer
524        assert!(g2_zero.serialize(&mut buf, false).is_ok());
525        assert_eq!(buf.len(), 192, "length of blob is incorrect");
526        let g2_zero_recover = G2::deserialize(&mut buf[..].as_ref(), false).unwrap();
527        assert_eq!(g2_zero, g2_zero_recover);
528
529        // G2::one, uncompressed
530        let mut buf: Vec<u8> = vec![];
531        // serialize a G2 element into buffer
532        assert!(g2_one.serialize(&mut buf, false).is_ok());
533        assert_eq!(buf.len(), 192, "length of blob is incorrect");
534        let g2_one_recover = G2::deserialize(&mut buf[..].as_ref(), false).unwrap();
535        assert_eq!(g2_one, g2_one_recover);
536
537        // G2::rand uncompressed
538        let g2_rand = G2::random(&mut rng);
539        let mut buf: Vec<u8> = vec![];
540        // serialize a G2 element into buffer
541        assert!(g2_rand.serialize(&mut buf, false).is_ok());
542        assert_eq!(buf.len(), 192, "length of blob is incorrect");
543        let g2_rand_recover = G2::deserialize(&mut buf[..].as_ref(), false).unwrap();
544        assert_eq!(g2_rand, g2_rand_recover);
545    }
546
547    #[test]
548    fn test_g1affine_serialization_rand() {
549        let mut rng = rand_xorshift::XorShiftRng::from_seed([
550            0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06,
551            0xbc, 0xe5,
552        ]);
553
554        // G1::zero, compressed
555        let g1_zero = G1::zero().into_affine();
556        let mut buf: Vec<u8> = vec![];
557        // serialize a G1 element into buffer
558        assert!(g1_zero.serialize(&mut buf, true).is_ok());
559        assert_eq!(buf.len(), 48, "length of blob is incorrect");
560        let g1_zero_recover = G1Affine::deserialize(&mut buf[..].as_ref(), true).unwrap();
561        assert_eq!(g1_zero, g1_zero_recover);
562
563        // G1::one, compressed
564        let g1_one = G1::one().into_affine();
565        let mut buf: Vec<u8> = vec![];
566        // serialize a G1 element into buffer
567        assert!(g1_one.serialize(&mut buf, true).is_ok());
568        assert_eq!(buf.len(), 48, "length of blob is incorrect");
569        let g1_one_recover = G1Affine::deserialize(&mut buf[..].as_ref(), true).unwrap();
570        assert_eq!(g1_one, g1_one_recover);
571
572        // G1::rand, compressed
573        let g1_rand = G1::random(&mut rng).into_affine();
574        let mut buf: Vec<u8> = vec![];
575        // serialize a G1 element into buffer
576        assert!(g1_rand.serialize(&mut buf, true).is_ok());
577        assert_eq!(buf.len(), 48, "length of blob is incorrect");
578        let g1_rand_recover = G1Affine::deserialize(&mut buf[..].as_ref(), true).unwrap();
579
580        assert_eq!(g1_rand, g1_rand_recover);
581
582        // G1::zero, uncompressed
583        let mut buf: Vec<u8> = vec![];
584        // serialize a G1 element into buffer
585        assert!(g1_zero.serialize(&mut buf, false).is_ok());
586        assert_eq!(buf.len(), 96, "length of blob is incorrect");
587        let g1_zero_recover = G1Affine::deserialize(&mut buf[..].as_ref(), false).unwrap();
588        assert_eq!(g1_zero, g1_zero_recover);
589
590        // G1::one, uncompressed
591        let mut buf: Vec<u8> = vec![];
592        // serialize a G1 element into buffer
593        assert!(g1_one.serialize(&mut buf, false).is_ok());
594        assert_eq!(buf.len(), 96, "length of blob is incorrect");
595        let g1_one_recover = G1Affine::deserialize(&mut buf[..].as_ref(), false).unwrap();
596        assert_eq!(g1_one, g1_one_recover);
597
598        // G1::rand, uncompressed
599        let g1_rand = G1::random(&mut rng).into_affine();
600        let mut buf: Vec<u8> = vec![];
601        // serialize a G1 element into buffer
602        assert!(g1_rand.serialize(&mut buf, false).is_ok());
603        assert_eq!(buf.len(), 96, "length of blob is incorrect");
604        let g1_rand_recover = G1Affine::deserialize(&mut buf[..].as_ref(), false).unwrap();
605        assert_eq!(g1_rand, g1_rand_recover);
606    }
607
608    #[test]
609    fn test_g2affine_serialization_rand() {
610        let mut rng = rand_xorshift::XorShiftRng::from_seed([
611            0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06,
612            0xbc, 0xe5,
613        ]);
614        // G2::zero, compressed
615        let g2_zero = G2::zero().into_affine();
616        let mut buf: Vec<u8> = vec![];
617        // serialize a G2 element into buffer
618        assert!(g2_zero.serialize(&mut buf, true).is_ok());
619        assert_eq!(buf.len(), 96, "length of blob is incorrect");
620        let g2_zero_recover = G2Affine::deserialize(&mut buf[..].as_ref(), true).unwrap();
621        assert_eq!(g2_zero, g2_zero_recover);
622
623        // G2::one, compressed
624        let g2_one = G2::one().into_affine();
625        let mut buf: Vec<u8> = vec![];
626        // serialize a G2 element into buffer
627        assert!(g2_one.serialize(&mut buf, true).is_ok());
628        assert_eq!(buf.len(), 96, "length of blob is incorrect");
629        let g2_one_recover = G2Affine::deserialize(&mut buf[..].as_ref(), true).unwrap();
630        assert_eq!(g2_one, g2_one_recover);
631
632        // G2::rand, compressed
633        let g2_rand = G2::random(&mut rng).into_affine();
634        let mut buf: Vec<u8> = vec![];
635        // serialize a G2 element into buffer
636        assert!(g2_rand.serialize(&mut buf, true).is_ok());
637        assert_eq!(buf.len(), 96, "length of blob is incorrect");
638        let g2_rand_recover = G2Affine::deserialize(&mut buf[..].as_ref(), true).unwrap();
639        assert_eq!(g2_rand, g2_rand_recover);
640
641        // G2::zero, uncompressed
642        let mut buf: Vec<u8> = vec![];
643        // serialize a G2 element into buffer
644        assert!(g2_zero.serialize(&mut buf, false).is_ok());
645        assert_eq!(buf.len(), 192, "length of blob is incorrect");
646        let g2_zero_recover = G2Affine::deserialize(&mut buf[..].as_ref(), false).unwrap();
647        assert_eq!(g2_zero, g2_zero_recover);
648
649        // G2::one, uncompressed
650        let mut buf: Vec<u8> = vec![];
651        // serialize a G2 element into buffer
652        assert!(g2_one.serialize(&mut buf, false).is_ok());
653        assert_eq!(buf.len(), 192, "length of blob is incorrect");
654        let g2_one_recover = G2Affine::deserialize(&mut buf[..].as_ref(), false).unwrap();
655        assert_eq!(g2_one, g2_one_recover);
656
657        // G2::rand uncompressed
658        let g2_rand = G2::random(&mut rng).into_affine();
659        let mut buf: Vec<u8> = vec![];
660        // serialize a G2 element into buffer
661        assert!(g2_rand.serialize(&mut buf, false).is_ok());
662        assert_eq!(buf.len(), 192, "length of blob is incorrect");
663        let g2_rand_recover = G2Affine::deserialize(&mut buf[..].as_ref(), false).unwrap();
664        assert_eq!(g2_rand, g2_rand_recover);
665    }
666
667    #[test]
668    fn test_fr_serialization_rand() {
669        use ff::Field;
670        let mut rng = rand_xorshift::XorShiftRng::from_seed([
671            0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06,
672            0xbc, 0xe5,
673        ]);
674        // fr::zero
675        let fr_zero = Fr::zero();
676        let mut buf: Vec<u8> = vec![];
677        // serialize a G1 element into buffer
678        assert!(fr_zero.serialize(&mut buf, true).is_ok());
679        assert_eq!(buf.len(), 32, "length of blob is incorrect");
680        let fr_zero_recover = Fr::deserialize(&mut buf[..].as_ref(), true).unwrap();
681        assert_eq!(fr_zero, fr_zero_recover);
682
683        // fr::one
684        let fr_one = Fr::one();
685        let mut buf: Vec<u8> = vec![];
686        // serialize a G1 element into buffer
687        assert!(fr_one.serialize(&mut buf, true).is_ok());
688        assert_eq!(buf.len(), 32, "length of blob is incorrect");
689        let fr_one_recover = Fr::deserialize(&mut buf[..].as_ref(), true).unwrap();
690        assert_eq!(fr_one, fr_one_recover);
691
692        // fr::rand
693        let fr_rand = Fr::random(&mut rng);
694        let mut buf: Vec<u8> = vec![];
695        // serialize a G1 element into buffer
696        assert!(fr_rand.serialize(&mut buf, true).is_ok());
697        assert_eq!(buf.len(), 32, "length of blob is incorrect");
698        let fr_rand_recover = Fr::deserialize(&mut buf[..].as_ref(), true).unwrap();
699        assert_eq!(fr_rand, fr_rand_recover);
700    }
701
702    #[test]
703    fn test_fq12_serialization_rand() {
704        use ff::Field;
705        let mut rng = rand_xorshift::XorShiftRng::from_seed([
706            0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06,
707            0xbc, 0xe5,
708        ]);
709        // fq12::zero
710        let fq12_zero = Fq12::zero();
711        let mut buf: Vec<u8> = vec![];
712        // serialize a G1 element into buffer
713        assert!(fq12_zero.serialize(&mut buf, true).is_ok());
714        assert_eq!(buf.len(), 48 * 12, "length of blob is incorrect");
715        let fq12_zero_recover = Fq12::deserialize(&mut buf[..].as_ref(), true).unwrap();
716        assert_eq!(fq12_zero, fq12_zero_recover);
717
718        // fq12::one
719        let fq12_one = Fq12::one();
720        let mut buf: Vec<u8> = vec![];
721        // serialize a G1 element into buffer
722        assert!(fq12_one.serialize(&mut buf, true).is_ok());
723        assert_eq!(buf.len(), 48 * 12, "length of blob is incorrect");
724        let fq12_one_recover = Fq12::deserialize(&mut buf[..].as_ref(), true).unwrap();
725        assert_eq!(fq12_one, fq12_one_recover);
726
727        // fr::rand
728        let fq12_rand = Fq12::random(&mut rng);
729        let mut buf: Vec<u8> = vec![];
730        // serialize a G1 element into buffer
731        assert!(fq12_rand.serialize(&mut buf, true).is_ok());
732        assert_eq!(buf.len(), 48 * 12, "length of blob is incorrect");
733        let fq12_rand_recover = Fq12::deserialize(&mut buf[..].as_ref(), true).unwrap();
734        assert_eq!(fq12_rand, fq12_rand_recover);
735    }
736}