m10_sdk/types/
signature.rs

1use std::str::FromStr;
2
3use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
4
5use crate::PublicKey;
6
7#[derive(Debug, Clone, Eq, PartialEq)]
8pub struct Sign(pub Vec<u8>);
9
10impl Sign {
11    pub fn to_vec(&self) -> Vec<u8> {
12        self.0.clone()
13    }
14}
15
16impl std::fmt::Display for Sign {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        write!(f, "{}", base64::encode(&self.0))
19    }
20}
21
22impl Serialize for Sign {
23    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
24        serializer.collect_str(&base64::display::Base64Display::with_config(
25            &self.0,
26            base64::STANDARD,
27        ))
28    }
29}
30
31impl<'de> Deserialize<'de> for Sign {
32    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
33        struct Vis;
34        impl serde::de::Visitor<'_> for Vis {
35            type Value = Sign;
36
37            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
38                formatter.write_str("a base64 string")
39            }
40
41            fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
42                base64::decode(v).map(Sign).map_err(Error::custom)
43            }
44        }
45        deserializer.deserialize_str(Vis)
46    }
47}
48
49impl FromStr for Sign {
50    type Err = base64::DecodeError;
51
52    fn from_str(s: &str) -> Result<Self, Self::Err> {
53        let key = base64::decode(s)?;
54        Ok(Self(key))
55    }
56}
57
58impl From<Sign> for Vec<u8> {
59    fn from(val: Sign) -> Self {
60        val.0
61    }
62}
63
64#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
65pub struct Signature {
66    pub public_key: PublicKey,
67    pub signature: Sign,
68    pub algorithm: i32,
69}
70
71impl From<Signature> for m10_protos::sdk::transaction::Signature {
72    fn from(val: Signature) -> Self {
73        m10_protos::sdk::transaction::Signature {
74            public_key: val.public_key.to_vec(),
75            signature: val.signature.to_vec(),
76            algorithm: val.algorithm,
77        }
78    }
79}
80
81impl From<m10_protos::sdk::transaction::Signature> for Signature {
82    fn from(val: m10_protos::sdk::transaction::Signature) -> Self {
83        Signature {
84            public_key: PublicKey(val.public_key),
85            signature: Sign(val.signature),
86            algorithm: val.algorithm,
87        }
88    }
89}