fluence_identity/
signature.rs1use crate::ed25519;
17use crate::secp256k1;
18#[cfg(not(target_arch = "wasm32"))]
19use crate::rsa;
20use crate::error::DecodingError;
21use serde::{Deserialize, Serialize};
22use crate::key_pair::KeyFormat;
23use std::convert::TryFrom;
24
25#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
26pub enum Signature {
27 Ed25519(ed25519::Signature),
28 #[cfg(not(target_arch = "wasm32"))]
29 Rsa(rsa::Signature),
30 Secp256k1(secp256k1::Signature),
31}
32
33impl Signature {
34 fn get_prefix(&self) -> u8 {
35 use Signature::*;
36 match self {
37 Ed25519(_) => KeyFormat::Ed25519.into(),
38 #[cfg(not(target_arch = "wasm32"))]
39 Rsa(_) => KeyFormat::Rsa.into(),
40 Secp256k1(_) => KeyFormat::Secp256k1.into()
41 }
42 }
43
44 pub fn encode(&self) -> Vec<u8> {
46 use Signature::*;
47
48 let mut result: Vec<u8> = vec![self.get_prefix()];
49
50 match self {
51 Ed25519(sig) => result.extend(sig.0.clone()),
52 #[cfg(not(target_arch = "wasm32"))]
53 Rsa(sig) => result.extend(sig.0.clone()),
54 Secp256k1(sig) => result.extend(sig.0.clone()),
55 }
56
57 result
58 }
59
60 pub fn decode(bytes: Vec<u8>) -> Result<Self, DecodingError> {
62 match KeyFormat::try_from(bytes[0])? {
63 KeyFormat::Ed25519 => Ok(Signature::Ed25519(ed25519::Signature(bytes[1..].to_vec()))),
64 #[cfg(not(target_arch = "wasm32"))]
65 KeyFormat::Rsa => Ok(Signature::Rsa(rsa::Signature(bytes[1..].to_vec()))),
66 KeyFormat::Secp256k1 => Ok(Signature::Secp256k1(secp256k1::Signature(bytes[1..].to_vec()))),
67
68 }
69 }
70
71 pub fn to_vec(&self) -> &[u8] {
72 use Signature::*;
73
74 match self {
75 Ed25519(sig) => &sig.0,
76 #[cfg(not(target_arch = "wasm32"))]
77 Rsa(sig) => &sig.0,
78 Secp256k1(sig) => &sig.0,
79 }
80 }
81}
82
83#[cfg(test)]
84mod tests {
85 use crate::*;
86
87 #[test]
88 fn signature_encode_decode() {
89 let bytes: Vec<u8> = (0..10).collect();
90 let ed25519_sig = Signature::Ed25519(crate::ed25519::Signature(bytes.clone()));
91 let secp256k1_sig = Signature::Secp256k1(crate::secp256k1::Signature(bytes.clone()));
92 #[cfg(not(target_arch = "wasm32"))]
93 let rsa_sig = Signature::Rsa(crate::rsa::Signature(bytes.clone()));
94
95 assert_eq!(Signature::decode(ed25519_sig.encode()).unwrap(), ed25519_sig);
96 assert_eq!(Signature::decode(secp256k1_sig.encode()).unwrap(), secp256k1_sig);
97 #[cfg(not(target_arch = "wasm32"))]
98 assert_eq!(Signature::decode(rsa_sig.encode()).unwrap(), rsa_sig);
99 }
100}