#[cfg(feature = "rkyv-impl")]
use bytecheck::CheckBytes;
use dusk_bytes::{DeserializableSlice, Serializable};
use dusk_curves::bls12_381::{G1Affine, G1Projective};
#[cfg(feature = "rkyv-impl")]
use rkyv::{
Archive, Deserialize, Serialize,
ser::{ScratchSpace, Serializer},
};
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[cfg_attr(
feature = "rkyv-impl",
derive(Archive, Deserialize, Serialize),
archive(
bound(serialize = "__S: Serializer + ScratchSpace"),
bound(
deserialize = "<__D as rkyv::Fallible>::Error: crate::CurvesArchiveError"
)
),
archive_attr(derive(CheckBytes))
)]
pub(crate) struct Commitment(
#[cfg_attr(feature = "rkyv-impl", omit_bounds)]
pub(crate) G1Affine,
);
impl From<G1Affine> for Commitment {
fn from(point: G1Affine) -> Commitment {
Commitment(point)
}
}
impl From<G1Projective> for Commitment {
fn from(point: G1Projective) -> Commitment {
Commitment(point.into())
}
}
impl Serializable<{ G1Affine::SIZE }> for Commitment {
type Error = dusk_bytes::Error;
fn to_bytes(&self) -> [u8; Self::SIZE] {
self.0.to_bytes()
}
fn from_bytes(buf: &[u8; Self::SIZE]) -> Result<Self, Self::Error> {
let g1 = G1Affine::from_slice(buf)?;
Ok(Self(g1))
}
}
impl Commitment {
fn identity() -> Commitment {
Commitment(G1Affine::identity())
}
}
impl Default for Commitment {
fn default() -> Commitment {
Commitment::identity()
}
}
#[cfg(test)]
mod commitment_tests {
use super::*;
#[test]
fn commitment_dusk_bytes_serde() {
let commitment = Commitment(G1Affine::generator());
let bytes = commitment.to_bytes();
let obtained_comm = Commitment::from_slice(&bytes)
.expect("Error on the deserialization");
assert_eq!(commitment, obtained_comm);
}
#[test]
fn commitment_default_is_identity() {
let c = Commitment::default();
assert_eq!(c, Commitment(G1Affine::identity()));
let bytes = c.to_bytes();
let obtained = Commitment::from_slice(&bytes)
.expect("identity commitment should deserialize");
assert_eq!(c, obtained);
}
#[test]
fn commitment_from_projective_matches_affine() {
let projective = G1Projective::generator();
let from_proj: Commitment = projective.into();
let from_aff: Commitment = G1Affine::generator().into();
assert_eq!(from_proj, from_aff);
}
}