relay-core 0.2.0-alpha.8

The core components of the Relay Protocol.
Documentation
use base64::prelude::BASE64_STANDARD;
use base64_serde::base64_serde_type;
use serde::{Deserialize, Serialize};

base64_serde_type!(Base64Standard, BASE64_STANDARD);

/// A wrapper struct that holds data along with an optional signature.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Signed {
    #[serde(with = "Base64Standard")]
    pub payload: Vec<u8>,
    #[serde(with = "Base64Standard")]
    pub sig: Vec<u8>,
}

impl Signed {
    /// Creates a new Signed wrapper without a signature.
    pub fn unsigned(payload: Vec<u8>) -> Self {
        Signed {
            payload,
            sig: Vec::new(),
        }
    }

    /// Creates a new Signed wrapper with a signature.
    pub fn new(payload: Vec<u8>, sig: Vec<u8>) -> Self {
        Signed { payload, sig }
    }

    pub fn is_signed(&self) -> bool {
        !self.sig.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new_unsigned() {
        let payload = vec![1, 2, 3];
        let signed = Signed::unsigned(payload.clone());
        assert_eq!(signed.payload, payload);
        assert!(!signed.is_signed());
        assert_eq!(signed.sig, Vec::new());
    }

    #[test]
    fn new_signed() {
        let payload = vec![1, 2, 3];
        let signature = vec![4, 5, 6];
        let signed = Signed::new(payload.clone(), signature.clone());
        assert_eq!(signed.payload, payload);
        assert!(signed.is_signed());
        assert_eq!(signed.sig, signature);
    }
}