mithril_stm/bls_multi_signature/
proof_of_possession.rs

1use blst::{blst_p1, min_sig::Signature as BlstSig};
2
3use crate::bls_multi_signature::{
4    helper::unsafe_helpers::{compress_p1, scalar_to_pk_in_g1, uncompress_p1},
5    SigningKey, POP,
6};
7use crate::error::{blst_err_to_mithril, MultiSignatureError};
8
9/// MultiSig proof of possession, which contains two elements from G1. However,
10/// the two elements have different types: `k1` is represented as a BlstSig
11/// as it has the same structure, and this facilitates its verification. On
12/// the other hand, `k2` is a G1 point, as it does not share structure with
13/// the BLS signature, and we need to have an ad-hoc verification mechanism.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct ProofOfPossession {
16    k1: BlstSig,
17    k2: blst_p1,
18}
19
20impl ProofOfPossession {
21    /// Convert to a 96 byte string.
22    ///
23    /// # Layout
24    /// The layout of a `MspPoP` encoding is
25    /// * K1 (G1 point)
26    /// * K2 (G1 point)
27    pub fn to_bytes(self) -> [u8; 96] {
28        let mut pop_bytes = [0u8; 96];
29        pop_bytes[..48].copy_from_slice(&self.k1.to_bytes());
30
31        pop_bytes[48..].copy_from_slice(&compress_p1(&self.k2)[..]);
32        pop_bytes
33    }
34
35    /// Deserialize a byte string to a `PublicKeyPoP`.
36    pub fn from_bytes(bytes: &[u8]) -> Result<Self, MultiSignatureError> {
37        let k1 = match BlstSig::from_bytes(
38            bytes
39                .get(..48)
40                .ok_or(MultiSignatureError::SerializationError)?,
41        ) {
42            Ok(key) => key,
43            Err(e) => {
44                return Err(blst_err_to_mithril(e, None, None)
45                    .expect_err("If it passed, blst returns and error different to SUCCESS."))
46            }
47        };
48
49        let k2 = uncompress_p1(
50            bytes
51                .get(48..96)
52                .ok_or(MultiSignatureError::SerializationError)?,
53        )?;
54
55        Ok(Self { k1, k2 })
56    }
57
58    pub(crate) fn to_k1(self) -> BlstSig {
59        self.k1
60    }
61
62    pub(crate) fn to_k2(self) -> blst_p1 {
63        self.k2
64    }
65}
66
67impl From<&SigningKey> for ProofOfPossession {
68    /// Convert a secret key into an `MspPoP`. This is performed by computing
69    /// `k1 =  H_G1(b"PoP" || mvk)` and `k2 = g1 * sk` where `H_G1` hashes into
70    /// `G1` and `g1` is the generator in `G1`.
71    fn from(sk: &SigningKey) -> Self {
72        let k1 = sk.to_blst_sk().sign(POP, &[], &[]);
73        let k2 = scalar_to_pk_in_g1(&sk.to_blst_sk());
74        Self { k1, k2 }
75    }
76}