Skip to main content

relay_core/
signed.rs

1use base64::prelude::BASE64_STANDARD;
2use base64_serde::base64_serde_type;
3use serde::{Deserialize, Serialize};
4
5base64_serde_type!(Base64Standard, BASE64_STANDARD);
6
7/// A wrapper struct that holds data along with an optional signature.
8#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
9pub struct Signed {
10    #[serde(with = "Base64Standard")]
11    pub payload: Vec<u8>,
12    #[serde(with = "Base64Standard")]
13    pub sig: Vec<u8>,
14}
15
16impl Signed {
17    /// Creates a new Signed wrapper without a signature.
18    pub fn unsigned(payload: Vec<u8>) -> Self {
19        Signed {
20            payload,
21            sig: Vec::new(),
22        }
23    }
24
25    /// Creates a new Signed wrapper with a signature.
26    pub fn new(payload: Vec<u8>, sig: Vec<u8>) -> Self {
27        Signed { payload, sig }
28    }
29
30    pub fn is_signed(&self) -> bool {
31        !self.sig.is_empty()
32    }
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn new_unsigned() {
41        let payload = vec![1, 2, 3];
42        let signed = Signed::unsigned(payload.clone());
43        assert_eq!(signed.payload, payload);
44        assert!(!signed.is_signed());
45        assert_eq!(signed.sig, Vec::new());
46    }
47
48    #[test]
49    fn new_signed() {
50        let payload = vec![1, 2, 3];
51        let signature = vec![4, 5, 6];
52        let signed = Signed::new(payload.clone(), signature.clone());
53        assert_eq!(signed.payload, payload);
54        assert!(signed.is_signed());
55        assert_eq!(signed.sig, signature);
56    }
57}