1use crate::error::MassaSignatureError;
4
5use ed25519_dalek::{Signer, Verifier};
6
7use massa_hash::Hash;
8use massa_serialization::{
9 DeserializeError, Deserializer, Serializer, U64VarIntDeserializer, U64VarIntSerializer,
10};
11use nom::{
12 error::{ContextError, ParseError},
13 IResult,
14};
15use rand::rngs::OsRng;
16use serde::{
17 de::{MapAccess, SeqAccess, Visitor},
18 ser::SerializeStruct,
19 Deserialize,
20};
21use std::str::FromStr;
22use std::{borrow::Cow, cmp::Ordering, hash::Hasher, ops::Bound::Included};
23use transition::Versioned;
24
25#[allow(missing_docs)]
26#[transition::versioned(versions("0"))]
28#[derive(Clone)]
29pub struct KeyPair(ed25519_dalek::SigningKey);
30
31impl std::fmt::Display for KeyPair {
32 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
33 match self {
34 KeyPair::KeyPairV0(keypair) => keypair.fmt(f),
35 }
36 }
37}
38
39impl std::fmt::Debug for KeyPair {
40 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
41 write!(f, "{}", self)
42 }
43}
44
45const SECRET_PREFIX: char = 'S';
46
47impl FromStr for KeyPair {
48 type Err = MassaSignatureError;
49
50 fn from_str(s: &str) -> Result<Self, Self::Err> {
61 let mut chars = s.chars();
62 match chars.next() {
63 Some(prefix) if prefix == SECRET_PREFIX => {
64 let data = chars.collect::<String>();
65 let decoded_bs58_check =
66 bs58::decode(data)
67 .with_check(None)
68 .into_vec()
69 .map_err(|_| {
70 MassaSignatureError::ParsingError(format!("bad secret key bs58: {}", s))
71 })?;
72 KeyPair::from_bytes(&decoded_bs58_check)
73 }
74 _ => Err(MassaSignatureError::ParsingError(format!(
75 "bad secret prefix for: {}",
76 s
77 ))),
78 }
79 }
80}
81
82impl KeyPair {
83 pub fn get_version(&self) -> u64 {
85 match self {
86 KeyPair::KeyPairV0(keypair) => keypair.get_version(),
87 }
88 }
89
90 pub fn generate(version: u64) -> Result<Self, MassaSignatureError> {
103 match version {
104 <KeyPair!["0"]>::VERSION => Ok(KeyPairVariant)),
105 _ => Err(MassaSignatureError::InvalidVersionError(format!(
106 "KeyPair version {} doesn't exist.",
107 version
108 ))),
109 }
110 }
111
112 pub fn sign(&self, hash: &Hash) -> Result<Signature, MassaSignatureError> {
124 match self {
125 KeyPair::KeyPairV0(keypair) => keypair.sign(hash).map(Signature::SignatureV0),
126 }
127 }
128
129 pub fn get_ser_len(&self) -> usize {
131 match self {
132 KeyPair::KeyPairV0(keypair) => keypair.get_ser_len(),
133 }
134 }
135
136 pub fn to_bytes(&self) -> Vec<u8> {
145 match self {
146 KeyPair::KeyPairV0(keypair) => keypair.to_bytes(),
147 }
148 }
149
150 pub fn get_public_key(&self) -> PublicKey {
159 match self {
160 KeyPair::KeyPairV0(keypair) => PublicKey::PublicKeyV0(keypair.get_public_key()),
161 }
162 }
163
164 pub fn from_bytes(data: &[u8]) -> Result<Self, MassaSignatureError> {
175 let u64_deserializer = U64VarIntDeserializer::new(Included(0), Included(u64::MAX));
176 let (rest, version) = u64_deserializer
177 .deserialize::<DeserializeError>(data)
178 .map_err(|err| MassaSignatureError::ParsingError(err.to_string()))?;
179 match version {
180 <KeyPair!["0"]>::VERSION => {
181 Ok(KeyPairVariant?))
182 }
183 _ => Err(MassaSignatureError::InvalidVersionError(format!(
184 "Unknown keypair version: {}",
185 version
186 ))),
187 }
188 }
189}
190
191#[transition::impl_version(versions("0"))]
192impl std::fmt::Display for KeyPair {
193 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
194 write!(
195 f,
196 "{}{}",
197 SECRET_PREFIX,
198 bs58::encode(self.to_bytes()).with_check().into_string()
199 )
200 }
201}
202
203#[transition::impl_version(versions("0"), structures("KeyPair"))]
204impl KeyPair {
205 pub const SECRET_KEY_BYTES_SIZE: usize = ed25519_dalek::SECRET_KEY_LENGTH;
206
207 pub fn get_version(&self) -> u64 {
209 Self::VERSION
210 }
211
212 pub fn get_ser_len(&self) -> usize {
214 Self::VERSION_VARINT_SIZE_BYTES + Self::SECRET_KEY_BYTES_SIZE
215 }
216
217 pub fn to_bytes(&self) -> Vec<u8> {
226 let version_serializer = U64VarIntSerializer::new();
227 let mut bytes: Vec<u8> =
228 Vec::with_capacity(Self::VERSION_VARINT_SIZE_BYTES + Self::SECRET_KEY_BYTES_SIZE);
229 version_serializer
230 .serialize(&Self::VERSION, &mut bytes)
231 .unwrap();
232 bytes.extend_from_slice(&self.0.to_bytes());
233 bytes
234 }
235}
236
237#[transition::impl_version(versions("0"), structures("KeyPair", "Signature", "PublicKey"))]
238impl KeyPair {
239 pub fn sign(&self, hash: &Hash) -> Result<Signature, MassaSignatureError> {
251 Ok(Signature(self.0.sign(hash.to_bytes())))
252 }
253
254 pub fn get_public_key(&self) -> PublicKey {
263 PublicKey(self.0.verifying_key())
264 }
265
266 pub fn generate() -> Self {
279 let mut rng = OsRng;
280 KeyPair(ed25519_dalek::SigningKey::generate(&mut rng))
281 }
282
283 pub fn from_bytes(data: &[u8]) -> Result<Self, MassaSignatureError> {
295 if data.len() < Self::SECRET_KEY_BYTES_SIZE {
296 return Err(MassaSignatureError::ParsingError(
297 "keypair byte array is of invalid size".to_string(),
298 ));
299 }
300
301 Ok(KeyPair(ed25519_dalek::SigningKey::from_bytes(
302 &data[..Self::SECRET_KEY_BYTES_SIZE].try_into().unwrap(),
303 )))
304 }
305}
306
307impl ::serde::Serialize for KeyPair {
308 fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
324 let mut keypair_serializer = s.serialize_struct("keypair", 2)?;
325 keypair_serializer.serialize_field("secret_key", &Cow::from(self.to_string()))?;
326 keypair_serializer
327 .serialize_field("public_key", &Cow::from(self.get_public_key().to_string()))?;
328 keypair_serializer.end()
329 }
330}
331
332impl<'de> ::serde::Deserialize<'de> for KeyPair {
333 fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<KeyPair, D::Error> {
350 enum Field {
351 SecretKey,
352 PublicKey,
353 }
354
355 impl<'de> Deserialize<'de> for Field {
356 fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
357 where
358 D: serde::Deserializer<'de>,
359 {
360 struct FieldVisitor;
361
362 impl<'de> Visitor<'de> for FieldVisitor {
363 type Value = Field;
364
365 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
366 formatter.write_str("`secret_key` or `public_key`")
367 }
368
369 fn visit_str<E>(self, value: &str) -> Result<Field, E>
370 where
371 E: serde::de::Error,
372 {
373 match value {
374 "secret_key" => Ok(Field::SecretKey),
375 "public_key" => Ok(Field::PublicKey),
376 _ => Err(serde::de::Error::unknown_field(value, FIELDS)),
377 }
378 }
379 }
380
381 deserializer.deserialize_identifier(FieldVisitor)
382 }
383 }
384
385 struct KeyPairVisitor;
386
387 impl<'de> Visitor<'de> for KeyPairVisitor {
388 type Value = KeyPair;
389
390 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
391 formatter.write_str("{'secret_key': 'xxx', 'public_key': 'xxx'}")
392 }
393
394 fn visit_seq<V>(self, mut seq: V) -> Result<KeyPair, V::Error>
395 where
396 V: SeqAccess<'de>,
397 {
398 let secret: Cow<str> = seq
399 .next_element()?
400 .ok_or_else(|| serde::de::Error::invalid_length(0, &self))?;
401 let _: Cow<str> = seq
402 .next_element()?
403 .ok_or_else(|| serde::de::Error::invalid_length(1, &self))?;
404 KeyPair::from_str(&secret).map_err(serde::de::Error::custom)
405 }
406
407 fn visit_map<V>(self, mut map: V) -> Result<KeyPair, V::Error>
408 where
409 V: MapAccess<'de>,
410 {
411 let mut secret = None;
412 let mut public = None;
413 while let Some(key) = map.next_key()? {
414 match key {
415 Field::SecretKey => {
416 if secret.is_some() {
417 return Err(serde::de::Error::duplicate_field("secret"));
418 }
419 secret = Some(map.next_value()?);
420 }
421 Field::PublicKey => {
422 if public.is_some() {
423 return Err(serde::de::Error::duplicate_field("public"));
424 }
425 public = Some(map.next_value()?);
426 }
427 }
428 }
429 let secret: Cow<str> =
430 secret.ok_or_else(|| serde::de::Error::missing_field("secret"))?;
431 let _: Cow<str> =
432 public.ok_or_else(|| serde::de::Error::missing_field("public"))?;
433 KeyPair::from_str(&secret).map_err(serde::de::Error::custom)
434 }
435 }
436
437 const FIELDS: &[&str] = &["secret_key", "public_key"];
438 d.deserialize_struct("KeyPair", FIELDS, KeyPairVisitor)
439 }
440}
441
442#[allow(missing_docs)]
443#[transition::versioned(versions("0"))]
447#[derive(Clone, Copy, PartialEq, Eq)]
448pub struct PublicKey(ed25519_dalek::VerifyingKey);
449
450#[allow(clippy::derived_hash_with_manual_eq)]
451impl std::hash::Hash for PublicKey {
452 fn hash<H: Hasher>(&self, state: &mut H) {
453 match self {
454 PublicKey::PublicKeyV0(pubkey) => pubkey.hash(state),
455 }
456 }
457}
458
459impl PartialOrd for PublicKey {
460 fn partial_cmp(&self, other: &PublicKey) -> Option<Ordering> {
461 Some(self.cmp(other))
462 }
463}
464
465impl Ord for PublicKey {
466 fn cmp(&self, other: &PublicKey) -> Ordering {
467 self.to_bytes().cmp(&other.to_bytes())
468 }
469}
470
471#[test]
472#[ignore]
473fn pubkey_ordering() {
474 use std::collections::BTreeSet;
477
478 let v0 = vec![
479 PublicKey::from_str("P1wiuz54kR2kmvumCELcgxv1YVStCnPK8QQ6os2FNbGYwp188im").unwrap(),
480 PublicKey::from_str("P12hzfgN14TCvAM3QgWvpPdHTKLUdqh2NzWqxkr2LAEG5hJmExr1").unwrap(),
481 ];
482 let mut map = BTreeSet::new();
488 map.extend(v0);
490 }
492
493impl std::fmt::Display for PublicKey {
494 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
495 match self {
496 PublicKey::PublicKeyV0(pubkey) => pubkey.fmt(f),
497 }
498 }
499}
500
501impl std::fmt::Debug for PublicKey {
502 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
503 write!(f, "{}", self)
504 }
505}
506
507const PUBLIC_PREFIX: char = 'P';
508
509impl FromStr for PublicKey {
510 type Err = MassaSignatureError;
511
512 fn from_str(s: &str) -> Result<Self, Self::Err> {
523 let mut chars = s.chars();
524 match chars.next() {
525 Some(prefix) if prefix == PUBLIC_PREFIX => {
526 let data = chars.collect::<String>();
527 let decoded_bs58_check =
528 bs58::decode(data)
529 .with_check(None)
530 .into_vec()
531 .map_err(|_| {
532 MassaSignatureError::ParsingError("Bad public key bs58".to_owned())
533 })?;
534 PublicKey::from_bytes(&decoded_bs58_check)
535 }
536 _ => Err(MassaSignatureError::ParsingError(
537 "Bad public key prefix".to_owned(),
538 )),
539 }
540 }
541}
542
543impl PublicKey {
544 pub fn verify_signature(
547 &self,
548 hash: &Hash,
549 signature: &Signature,
550 ) -> Result<(), MassaSignatureError> {
551 match (self, signature) {
552 (PublicKey::PublicKeyV0(pubkey), Signature::SignatureV0(signature)) => {
553 pubkey.verify_signature(hash, signature)
554 }
555 }
556 }
557
558 pub fn to_bytes(&self) -> Vec<u8> {
569 match self {
570 PublicKey::PublicKeyV0(pubkey) => pubkey.to_bytes(),
571 }
572 }
573
574 pub fn get_ser_len(&self) -> usize {
576 match self {
577 PublicKey::PublicKeyV0(pubkey) => pubkey.get_ser_len(),
578 }
579 }
580
581 pub fn from_bytes(data: &[u8]) -> Result<PublicKey, MassaSignatureError> {
593 let u64_deserializer = U64VarIntDeserializer::new(Included(0), Included(u64::MAX));
594 let (rest, version) = u64_deserializer
595 .deserialize::<DeserializeError>(data)
596 .map_err(|err| MassaSignatureError::ParsingError(err.to_string()))?;
597 match version {
598 <PublicKey!["0"]>::VERSION => {
599 Ok(PublicKeyVariant?))
600 }
601 _ => Err(MassaSignatureError::InvalidVersionError(format!(
602 "Unknown PublicKey version: {}",
603 version
604 ))),
605 }
606 }
607}
608
609#[transition::impl_version(versions("0"))]
610#[allow(clippy::derived_hash_with_manual_eq)]
611impl std::hash::Hash for PublicKey {
612 fn hash<H: Hasher>(&self, state: &mut H) {
613 self.0.to_bytes().hash(state);
614 }
615}
616
617#[transition::impl_version(versions("0"))]
618impl PartialOrd for PublicKey {
619 fn partial_cmp(&self, other: &PublicKey) -> Option<Ordering> {
620 Some(self.cmp(other))
621 }
622}
623
624#[transition::impl_version(versions("0"))]
625impl Ord for PublicKey {
626 fn cmp(&self, other: &PublicKey) -> Ordering {
627 self.0.to_bytes().cmp(&other.0.to_bytes())
628 }
629}
630
631#[transition::impl_version(versions("0"))]
632impl std::fmt::Display for PublicKey {
633 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
634 write!(
635 f,
636 "{}{}",
637 PUBLIC_PREFIX,
638 bs58::encode(self.to_bytes()).with_check().into_string()
639 )
640 }
641}
642
643#[transition::impl_version(versions("0"))]
644impl std::fmt::Debug for PublicKey {
645 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
646 write!(f, "{}", self)
647 }
648}
649
650#[transition::impl_version(versions("0"), structures("PublicKey", "Signature"))]
651impl PublicKey {
652 pub const PUBLIC_KEY_SIZE_BYTES: usize = ed25519_dalek::PUBLIC_KEY_LENGTH;
654
655 pub fn get_ser_len(&self) -> usize {
657 Self::VERSION_VARINT_SIZE_BYTES + Self::PUBLIC_KEY_SIZE_BYTES
658 }
659
660 pub fn verify_signature(
663 &self,
664 hash: &Hash,
665 signature: &Signature,
666 ) -> Result<(), MassaSignatureError> {
667 self.0.verify(hash.to_bytes(), &signature.0).map_err(|err| {
668 MassaSignatureError::SignatureError(format!("Signature verification failed: {}", err))
669 })
670 }
671
672 pub fn to_bytes(&self) -> Vec<u8> {
681 let version_serializer = U64VarIntSerializer::new();
682 let mut bytes: Vec<u8> =
683 Vec::with_capacity(Self::VERSION_VARINT_SIZE_BYTES + Self::PUBLIC_KEY_SIZE_BYTES);
684 version_serializer
685 .serialize(&Self::VERSION, &mut bytes)
686 .unwrap();
687 bytes.extend_from_slice(&self.0.to_bytes());
688 bytes
689 }
690
691 pub fn from_bytes(data: &[u8]) -> Result<PublicKey, MassaSignatureError> {
705 if data.len() < Self::PUBLIC_KEY_SIZE_BYTES {
706 return Err(MassaSignatureError::ParsingError(
707 "public key byte array is of invalid size".to_string(),
708 ));
709 }
710 ed25519_dalek::VerifyingKey::from_bytes(
711 &data[..Self::PUBLIC_KEY_SIZE_BYTES].try_into().unwrap(),
712 )
713 .map(Self)
714 .map_err(|err| MassaSignatureError::ParsingError(err.to_string()))
715 }
716}
717
718#[derive(Default, Clone)]
720pub struct PublicKeyDeserializer;
721
722impl PublicKeyDeserializer {
723 pub const fn new() -> Self {
725 Self
726 }
727}
728
729impl Deserializer<PublicKey> for PublicKeyDeserializer {
730 fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
743 &self,
744 buffer: &'a [u8],
745 ) -> IResult<&'a [u8], PublicKey, E> {
746 let public_key = PublicKey::from_bytes(buffer).map_err(|_| {
747 nom::Err::Error(ParseError::from_error_kind(
748 buffer,
749 nom::error::ErrorKind::Fail,
750 ))
751 })?;
752 Ok((&buffer[public_key.get_ser_len()..], public_key))
754 }
755}
756
757impl ::serde::Serialize for PublicKey {
758 fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
774 s.collect_str(&self.to_string())
775 }
776}
777
778impl<'de> ::serde::Deserialize<'de> for PublicKey {
779 fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<PublicKey, D::Error> {
797 struct Base58CheckVisitor;
798
799 impl<'de> ::serde::de::Visitor<'de> for Base58CheckVisitor {
800 type Value = PublicKey;
801
802 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
803 formatter.write_str("an ASCII base58check string")
804 }
805
806 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
807 where
808 E: ::serde::de::Error,
809 {
810 if let Ok(v_str) = std::str::from_utf8(v) {
811 PublicKey::from_str(v_str).map_err(E::custom)
812 } else {
813 Err(E::invalid_value(::serde::de::Unexpected::Bytes(v), &self))
814 }
815 }
816
817 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
818 where
819 E: ::serde::de::Error,
820 {
821 PublicKey::from_str(v).map_err(E::custom)
822 }
823 }
824 d.deserialize_str(Base58CheckVisitor)
825 }
826}
827
828#[allow(missing_docs)]
829#[transition::versioned(versions("0"))]
831#[derive(Clone, Copy, Debug, Eq, PartialEq)]
832pub struct Signature(ed25519_dalek::Signature);
833
834#[transition::impl_version(versions("0"), structures("Signature"))]
835impl Signature {
836 pub const SIGNATURE_SIZE_BYTES: usize = ed25519_dalek::SIGNATURE_LENGTH;
838}
839
840impl std::fmt::Display for Signature {
841 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
842 match self {
843 Signature::SignatureV0(signature) => signature.fmt(f),
844 }
845 }
846}
847
848impl FromStr for Signature {
849 type Err = MassaSignatureError;
850
851 fn from_str(s: &str) -> Result<Self, Self::Err> {
864 let data = s.chars().collect::<String>();
865 let decoded_bs58_check = bs58::decode(data)
866 .with_check(None)
867 .into_vec()
868 .map_err(|_| MassaSignatureError::ParsingError(format!("bad signature bs58: {}", s)))?;
869 Signature::from_bytes(&decoded_bs58_check)
870 }
871}
872
873impl Signature {
874 pub fn to_bs58_check(&self) -> String {
888 match self {
889 Signature::SignatureV0(signature) => signature.to_bs58_check(),
890 }
891 }
892
893 pub fn from_bs58_check(data: &str) -> Result<Signature, MassaSignatureError> {
908 bs58::decode(data)
909 .with_check(None)
910 .into_vec()
911 .map_err(|err| {
912 MassaSignatureError::ParsingError(format!(
913 "signature bs58_check parsing error: {}",
914 err
915 ))
916 })
917 .and_then(|signature| Signature::from_bytes(signature.as_slice()))
918 }
919
920 pub fn get_ser_len(&self) -> usize {
922 match self {
923 Signature::SignatureV0(signature) => signature.get_ser_len(),
924 }
925 }
926
927 pub fn to_bytes(&self) -> Vec<u8> {
941 match self {
942 Signature::SignatureV0(signature) => signature.to_bytes(),
943 }
944 }
945
946 pub fn from_bytes(data: &[u8]) -> Result<Self, MassaSignatureError> {
961 let u64_deserializer = U64VarIntDeserializer::new(Included(0), Included(u64::MAX));
962 let (rest, version) = u64_deserializer
963 .deserialize::<DeserializeError>(data)
964 .map_err(|err| MassaSignatureError::ParsingError(err.to_string()))?;
965 match version {
966 <Signature!["0"]>::VERSION => {
967 Ok(SignatureVariant?))
968 }
969 _ => Err(MassaSignatureError::InvalidVersionError(format!(
970 "Unknown signature version: {}",
971 version
972 ))),
973 }
974 }
975}
976
977#[transition::impl_version(versions("0"))]
978impl std::fmt::Display for Signature {
979 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
980 write!(f, "{}", self.to_bs58_check())
981 }
982}
983
984#[transition::impl_version(versions("0"), structures("Signature"))]
985impl Signature {
986 pub fn to_bs58_check(self) -> String {
1000 bs58::encode(self.to_bytes()).with_check().into_string()
1001 }
1002
1003 pub fn get_ser_len(&self) -> usize {
1005 Self::VERSION_VARINT_SIZE_BYTES + Self::SIGNATURE_SIZE_BYTES
1006 }
1007
1008 pub fn to_bytes(self) -> Vec<u8> {
1022 let version_serializer = U64VarIntSerializer::new();
1023 let mut bytes: Vec<u8> =
1024 Vec::with_capacity(Self::VERSION_VARINT_SIZE_BYTES + Self::SIGNATURE_SIZE_BYTES);
1025 version_serializer
1026 .serialize(&Self::VERSION, &mut bytes)
1027 .unwrap();
1028 bytes.extend_from_slice(&self.0.to_bytes());
1029 bytes
1030 }
1031
1032 pub fn from_bytes(data: &[u8]) -> Result<Signature, MassaSignatureError> {
1049 if data.len() < Self::SIGNATURE_SIZE_BYTES {
1050 return Err(MassaSignatureError::ParsingError(
1051 "signature byte array is of invalid size".to_string(),
1052 ));
1053 }
1054 Ok(Signature(ed25519_dalek::Signature::from_bytes(
1055 &data[..Self::SIGNATURE_SIZE_BYTES].try_into().unwrap(),
1056 )))
1057 }
1058
1059 pub fn from_bs58_check(data: &str) -> Result<Signature, MassaSignatureError> {
1074 bs58::decode(data)
1075 .with_check(None)
1076 .into_vec()
1077 .map_err(|err| {
1078 MassaSignatureError::ParsingError(format!(
1079 "signature bs58_check parsing error: {}",
1080 err
1081 ))
1082 })
1083 .and_then(|signature_bytes: Vec<u8>| Signature::from_bytes(&signature_bytes))
1084 }
1085}
1086
1087impl ::serde::Serialize for Signature {
1088 fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1108 if s.is_human_readable() {
1109 s.collect_str(&self.to_bs58_check())
1110 } else {
1111 s.serialize_bytes(self.to_bytes().as_ref())
1112 }
1113 }
1114}
1115
1116impl<'de> ::serde::Deserialize<'de> for Signature {
1117 fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<Signature, D::Error> {
1138 if d.is_human_readable() {
1139 struct SignatureVisitor;
1140
1141 impl<'de> ::serde::de::Visitor<'de> for SignatureVisitor {
1142 type Value = Signature;
1143
1144 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
1145 formatter.write_str("an ASCII base58check string")
1146 }
1147
1148 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1149 where
1150 E: ::serde::de::Error,
1151 {
1152 if let Ok(v_str) = std::str::from_utf8(v) {
1153 Signature::from_str(v_str).map_err(E::custom)
1154 } else {
1155 Err(E::invalid_value(::serde::de::Unexpected::Bytes(v), &self))
1156 }
1157 }
1158
1159 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1160 where
1161 E: ::serde::de::Error,
1162 {
1163 Signature::from_str(v).map_err(E::custom)
1164 }
1165 }
1166 d.deserialize_str(SignatureVisitor)
1167 } else {
1168 struct BytesVisitor;
1169
1170 impl<'de> ::serde::de::Visitor<'de> for BytesVisitor {
1171 type Value = Signature;
1172
1173 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
1174 formatter.write_str("a bytestring")
1175 }
1176
1177 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1178 where
1179 E: ::serde::de::Error,
1180 {
1181 Signature::from_bytes(v).map_err(E::custom)
1182 }
1183 }
1184
1185 d.deserialize_bytes(BytesVisitor)
1186 }
1187 }
1188}
1189
1190#[derive(Default)]
1192pub struct SignatureDeserializer;
1193
1194impl SignatureDeserializer {
1195 pub const fn new() -> Self {
1197 Self
1198 }
1199}
1200
1201impl Deserializer<Signature> for SignatureDeserializer {
1202 fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
1216 &self,
1217 buffer: &'a [u8],
1218 ) -> IResult<&'a [u8], Signature, E> {
1219 let signature = Signature::from_bytes(buffer).map_err(|_| {
1220 nom::Err::Error(ParseError::from_error_kind(
1221 buffer,
1222 nom::error::ErrorKind::Fail,
1223 ))
1224 })?;
1225 Ok((&buffer[signature.get_ser_len()..], signature))
1227 }
1228}
1229
1230pub fn verify_signature_batch(
1232 batch: &[(Hash, Signature, PublicKey)],
1233) -> Result<(), MassaSignatureError> {
1234 if batch.is_empty() {
1236 return Ok(());
1237 }
1238
1239 if batch.len() == 1 {
1241 let (hash, signature, public_key) = batch[0];
1242 return public_key.verify_signature(&hash, &signature);
1243 }
1244
1245 let mut hashes = Vec::with_capacity(batch.len());
1247 let mut signatures = Vec::with_capacity(batch.len());
1248 let mut public_keys = Vec::with_capacity(batch.len());
1249
1250 for (hash, signature_, public_key_) in batch.iter() {
1251 let (signature, public_key) = match (signature_, public_key_) {
1252 (Signature::SignatureV0(s), PublicKey::PublicKeyV0(pk)) => (s.0, pk.0),
1253 };
1254
1255 hashes.push(hash.to_bytes().as_slice());
1256 signatures.push(signature);
1257 public_keys.push(public_key);
1258 }
1259
1260 ed25519_dalek::verify_batch(&hashes, signatures.as_slice(), public_keys.as_slice()).map_err(
1261 |err| {
1262 MassaSignatureError::SignatureError(format!(
1263 "Batch signature verification failed: {}",
1264 err
1265 ))
1266 },
1267 )
1268}
1269
1270#[cfg(test)]
1271mod tests {
1272 use super::*;
1273 use massa_hash::Hash;
1274 use serial_test::serial;
1275
1276 #[test]
1277 #[serial]
1278 fn test_example() {
1279 let keypair = KeyPair::generate(0).unwrap();
1280 let message = "Hello World!".as_bytes();
1281 let hash = Hash::compute_from(message);
1282 let signature = keypair.sign(&hash).unwrap();
1283 assert!(keypair
1284 .get_public_key()
1285 .verify_signature(&hash, &signature)
1286 .is_ok())
1287 }
1288
1289 #[test]
1290 #[serial]
1291 fn test_serde_keypair() {
1292 let keypair = KeyPair::generate(0).unwrap();
1293 let serialized = serde_json::to_string(&keypair).expect("could not serialize keypair");
1294 let deserialized: KeyPair =
1295 serde_json::from_str(&serialized).expect("could not deserialize keypair");
1296
1297 match (keypair, deserialized) {
1298 (KeyPair::KeyPairV0(keypair), KeyPair::KeyPairV0(deserialized)) => {
1299 assert_eq!(
1300 keypair.0.to_keypair_bytes(),
1301 deserialized.0.to_keypair_bytes()
1302 );
1303 }
1304 }
1305 }
1306
1307 #[test]
1308 #[serial]
1309 fn test_serde_public_key() {
1310 let keypair = KeyPair::generate(0).unwrap();
1311 let public_key = keypair.get_public_key();
1312 let serialized =
1313 serde_json::to_string(&public_key).expect("Could not serialize public key");
1314 let deserialized =
1315 serde_json::from_str(&serialized).expect("could not deserialize public key");
1316 assert_eq!(public_key, deserialized);
1317 }
1318
1319 #[test]
1320 #[serial]
1321 fn test_serde_signature() {
1322 let keypair = KeyPair::generate(0).unwrap();
1323 let message = "Hello World!".as_bytes();
1324 let hash = Hash::compute_from(message);
1325 let signature = keypair.sign(&hash).unwrap();
1326 let serialized =
1327 serde_json::to_string(&signature).expect("could not serialize signature key");
1328 let deserialized =
1329 serde_json::from_str(&serialized).expect("could not deserialize signature key");
1330 assert_eq!(signature, deserialized);
1331 }
1332}