/ fedimint-core / src / encoding / bls12_381.rs
bls12_381.rs
 1  use bls12_381::{G1Affine, G2Affine, Scalar};
 2  
 3  use crate::encoding::{Decodable, DecodeError, Encodable};
 4  use crate::module::registry::ModuleDecoderRegistry;
 5  
 6  impl Encodable for Scalar {
 7      fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<usize, std::io::Error> {
 8          self.to_bytes().consensus_encode(writer)
 9      }
10  }
11  
12  impl Decodable for Scalar {
13      fn consensus_decode<D: std::io::Read>(
14          d: &mut D,
15          modules: &ModuleDecoderRegistry,
16      ) -> Result<Self, DecodeError> {
17          let byte_array = <[u8; 32]>::consensus_decode(d, modules)?;
18  
19          Option::from(Scalar::from_bytes(&byte_array))
20              .ok_or(DecodeError::from_str("Error decoding Scalar"))
21      }
22  }
23  
24  impl Encodable for G1Affine {
25      fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<usize, std::io::Error> {
26          self.to_compressed().consensus_encode(writer)
27      }
28  }
29  
30  impl Decodable for G1Affine {
31      fn consensus_decode<D: std::io::Read>(
32          d: &mut D,
33          modules: &ModuleDecoderRegistry,
34      ) -> Result<Self, DecodeError> {
35          let byte_array = <[u8; 48]>::consensus_decode(d, modules)?;
36  
37          Option::from(G1Affine::from_compressed(&byte_array))
38              .ok_or(DecodeError::from_str("Error decoding G1Affine"))
39      }
40  }
41  
42  impl Encodable for G2Affine {
43      fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<usize, std::io::Error> {
44          self.to_compressed().consensus_encode(writer)
45      }
46  }
47  
48  impl Decodable for G2Affine {
49      fn consensus_decode<D: std::io::Read>(
50          d: &mut D,
51          modules: &ModuleDecoderRegistry,
52      ) -> Result<Self, DecodeError> {
53          let byte_array = <[u8; 96]>::consensus_decode(d, modules)?;
54  
55          Option::from(G2Affine::from_compressed(&byte_array))
56              .ok_or(DecodeError::from_str("Error decoding G2Affine"))
57      }
58  }