radix_common/crypto/ed25519/
signature.rs1use crate::ScryptoSbor;
2use radix_rust::copy_u8_array;
3use sbor::rust::borrow::ToOwned;
4use sbor::rust::fmt;
5use sbor::rust::str::FromStr;
6use sbor::rust::string::String;
7use sbor::rust::vec::Vec;
8use sbor::*;
9
10#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
12#[derive(Clone, Copy, PartialEq, Eq, Hash, Sbor)]
13pub struct Ed25519Signature(
14 #[cfg_attr(feature = "serde", serde(with = "hex::serde"))] pub [u8; Self::LENGTH],
15);
16
17impl Ed25519Signature {
18 pub const LENGTH: usize = 64;
19
20 pub fn to_vec(&self) -> Vec<u8> {
21 self.0.to_vec()
22 }
23}
24
25impl TryFrom<&[u8]> for Ed25519Signature {
26 type Error = ParseEd25519SignatureError;
27
28 fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
29 if slice.len() != Ed25519Signature::LENGTH {
30 return Err(ParseEd25519SignatureError::InvalidLength(slice.len()));
31 }
32
33 Ok(Ed25519Signature(copy_u8_array(slice)))
34 }
35}
36
37impl AsRef<Self> for Ed25519Signature {
38 fn as_ref(&self) -> &Self {
39 self
40 }
41}
42
43impl AsRef<[u8]> for Ed25519Signature {
44 fn as_ref(&self) -> &[u8] {
45 &self.0
46 }
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, ScryptoSbor)]
54pub enum ParseEd25519SignatureError {
55 InvalidHex(String),
56 InvalidLength(usize),
57}
58
59#[cfg(not(feature = "alloc"))]
61impl std::error::Error for ParseEd25519SignatureError {}
62
63#[cfg(not(feature = "alloc"))]
64impl fmt::Display for ParseEd25519SignatureError {
65 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66 write!(f, "{:?}", self)
67 }
68}
69
70impl FromStr for Ed25519Signature {
75 type Err = ParseEd25519SignatureError;
76
77 fn from_str(s: &str) -> Result<Self, Self::Err> {
78 let bytes =
79 hex::decode(s).map_err(|_| ParseEd25519SignatureError::InvalidHex(s.to_owned()))?;
80 Self::try_from(bytes.as_slice())
81 }
82}
83
84impl fmt::Display for Ed25519Signature {
85 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
86 write!(f, "{}", hex::encode(self.to_vec()))
87 }
88}
89
90impl fmt::Debug for Ed25519Signature {
91 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
92 write!(f, "{}", self)
93 }
94}