1use std::{
2 cmp::Ordering,
3 fmt::{Display, Formatter},
4 hash::{Hash, Hasher},
5 iter::Sum,
6};
7
8use blst::{
9 BLST_ERROR,
10 min_sig::{AggregatePublicKey, PublicKey as BlstVk},
11};
12use serde::{Deserialize, Serialize};
13
14use crate::bls_multi_signature::{
15 BlsProofOfPossession, BlsSigningKey, POP, helper::unsafe_helpers::verify_pairing,
16};
17use crate::error::{MultiSignatureError, blst_err_to_mithril};
18
19#[derive(Debug, Clone, Copy, Default)]
22pub struct BlsVerificationKey(pub BlstVk);
23
24impl BlsVerificationKey {
25 pub fn to_bytes(self) -> [u8; 96] {
27 self.0.to_bytes()
28 }
29
30 pub fn from_bytes(bytes: &[u8]) -> Result<Self, MultiSignatureError> {
36 let bytes = bytes.get(..96).ok_or(MultiSignatureError::SerializationError)?;
37 match BlstVk::key_validate(bytes) {
38 Ok(vk) => Ok(Self(vk)),
39 Err(e) => Err(blst_err_to_mithril(e, None, None)
40 .expect_err("If deserialization is not successful, blst returns and error different to SUCCESS."))
41 }
42 }
43
44 fn compare_verification_keys(&self, other: &BlsVerificationKey) -> Ordering {
47 let self_bytes = self.to_bytes();
48 let other_bytes = other.to_bytes();
49 let mut result = Ordering::Equal;
50
51 for (i, j) in self_bytes.iter().zip(other_bytes.iter()) {
52 result = i.cmp(j);
53 if result != Ordering::Equal {
54 return result;
55 }
56 }
57
58 result
59 }
60
61 pub(crate) fn to_blst_verification_key(self) -> BlstVk {
62 self.0
63 }
64}
65
66impl Display for BlsVerificationKey {
67 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
68 write!(f, "{:?}", self.to_bytes())
69 }
70}
71
72impl Hash for BlsVerificationKey {
73 fn hash<H: Hasher>(&self, state: &mut H) {
74 Hash::hash_slice(&self.to_bytes(), state)
75 }
76}
77
78impl PartialEq for BlsVerificationKey {
79 fn eq(&self, other: &Self) -> bool {
80 self.0 == other.0
81 }
82}
83
84impl Eq for BlsVerificationKey {}
85
86impl PartialOrd for BlsVerificationKey {
87 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
88 Some(std::cmp::Ord::cmp(self, other))
89 }
90}
91
92impl Ord for BlsVerificationKey {
93 fn cmp(&self, other: &Self) -> Ordering {
94 self.compare_verification_keys(other)
95 }
96}
97
98impl<'a> Sum<&'a Self> for BlsVerificationKey {
99 fn sum<I>(iter: I) -> Self
100 where
101 I: Iterator<Item = &'a Self>,
102 {
103 let keys: Vec<&BlstVk> = iter.map(|x| &x.0).collect();
104
105 assert!(!keys.is_empty(), "One cannot add an empty vector");
106 let aggregate_key = AggregatePublicKey::aggregate(&keys, false)
107 .expect("An MspMvk is always a valid key. This function only fails if keys is empty or if the keys are invalid, none of which can happen.")
108 .to_public_key();
109
110 Self(aggregate_key)
111 }
112}
113
114impl From<&BlsSigningKey> for BlsVerificationKey {
115 fn from(sk: &BlsSigningKey) -> Self {
119 BlsVerificationKey(sk.to_blst_secret_key().sk_to_pk())
120 }
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
125pub struct BlsVerificationKeyProofOfPossession {
126 pub vk: BlsVerificationKey,
128 pub pop: BlsProofOfPossession,
130}
131
132impl BlsVerificationKeyProofOfPossession {
133 pub(crate) fn verify_proof_of_possession(&self) -> Result<(), MultiSignatureError> {
140 match self.vk.to_blst_verification_key().validate() {
141 Ok(_) => {
142 let result = verify_pairing(&self.vk, &self.pop);
143 if !(self.pop.get_k1().verify(
144 false,
145 POP,
146 &[],
147 &[],
148 &self.vk.to_blst_verification_key(),
149 false,
150 ) == BLST_ERROR::BLST_SUCCESS
151 && result)
152 {
153 return Err(MultiSignatureError::KeyInvalid(Box::new(*self)));
154 }
155 Ok(())
156 }
157 Err(e) => blst_err_to_mithril(e, None, Some(self.vk)),
158 }
159 }
160
161 #[deprecated(
168 since = "0.5.0",
169 note = "The verification of the proof of possession is not part of the public API any more"
170 )]
171 pub fn check(&self) -> Result<(), MultiSignatureError> {
172 Self::verify_proof_of_possession(self)
173 }
174
175 pub fn to_bytes(self) -> [u8; 192] {
182 let mut vkpop_bytes = [0u8; 192];
183 vkpop_bytes[..96].copy_from_slice(&self.vk.to_bytes());
184 vkpop_bytes[96..].copy_from_slice(&self.pop.to_bytes());
185 vkpop_bytes
186 }
187
188 pub fn from_bytes(bytes: &[u8]) -> Result<Self, MultiSignatureError> {
190 let mvk = BlsVerificationKey::from_bytes(
191 bytes.get(..96).ok_or(MultiSignatureError::SerializationError)?,
192 )?;
193
194 let pop = BlsProofOfPossession::from_bytes(
195 bytes.get(96..).ok_or(MultiSignatureError::SerializationError)?,
196 )?;
197
198 Ok(Self { vk: mvk, pop })
199 }
200}
201
202impl From<&BlsSigningKey> for BlsVerificationKeyProofOfPossession {
203 fn from(sk: &BlsSigningKey) -> Self {
206 Self {
207 vk: sk.into(),
208 pop: sk.into(),
209 }
210 }
211}
212
213#[cfg(test)]
214mod tests {
215 use super::*;
216
217 mod golden {
218
219 use rand_chacha::ChaCha20Rng;
220 use rand_core::SeedableRng;
221
222 use super::*;
223
224 const GOLDEN_JSON: &str = r#"
225 {
226 "vk": [143, 161, 255, 48, 78, 57, 204, 220, 25, 221, 164, 252, 248, 14, 56, 126, 186, 135, 228, 188, 145, 181, 52, 200, 97, 99, 213, 46, 0, 199, 193, 89, 187, 88, 29, 135, 173, 244, 86, 36, 83, 54, 67, 164, 6, 137, 94, 72, 6, 105, 128, 128, 93, 48, 176, 11, 4, 246, 138, 48, 180, 133, 90, 142, 192, 24, 193, 111, 142, 31, 76, 111, 110, 234, 153, 90, 208, 192, 31, 124, 95, 102, 49, 158, 99, 52, 220, 165, 94, 251, 68, 69, 121, 16, 224, 194],
227 "pop": [168, 50, 233, 193, 15, 136, 65, 72, 123, 148, 129, 176, 38, 198, 209, 47, 28, 204, 176, 144, 57, 251, 42, 28, 66, 76, 89, 97, 158, 63, 54, 198, 194, 176, 135, 221, 14, 185, 197, 225, 202, 98, 243, 74, 233, 225, 143, 151, 147, 177, 170, 117, 66, 165, 66, 62, 33, 216, 232, 75, 68, 114, 195, 22, 100, 65, 44, 198, 4, 166, 102, 233, 253, 240, 59, 175, 60, 117, 142, 114, 140, 122, 17, 87, 110, 187, 1, 17, 10, 195, 154, 13, 249, 86, 54, 226]
228 }
229 "#;
230
231 fn golden_value() -> BlsVerificationKeyProofOfPossession {
232 let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
233 let sk = BlsSigningKey::generate(&mut rng);
234 BlsVerificationKeyProofOfPossession {
235 vk: BlsVerificationKey::from(&sk),
236 pop: BlsProofOfPossession::from(&sk),
237 }
238 }
239
240 #[test]
241 fn golden_conversions() {
242 let value = serde_json::from_str(GOLDEN_JSON)
243 .expect("This JSON deserialization should not fail");
244 assert_eq!(golden_value(), value);
245
246 let serialized =
247 serde_json::to_string(&value).expect("This JSON serialization should not fail");
248 let golden_serialized = serde_json::to_string(&golden_value())
249 .expect("This JSON serialization should not fail");
250 assert_eq!(golden_serialized, serialized);
251 }
252 }
253}