1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
//! Various helper traits, structs, methods, and macros.

use serde::{Deserialize, Serialize};
use std::fmt::Debug;

use super::*;

/// Trait for objects with associated unique identifiers.
pub trait Identified {
    type I: Id;
    fn id(&self) -> &Self::I;
}

/// Trait for unique identifiers.
pub trait Id
    : Sized + ::std::str::FromStr<Err = String> + ToString + Serialize + Deserialize
{}

macro_rules! uuid_id {
    ( #[$doc:meta] $name:ident ) => {
        #[$doc]
        #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
        pub struct $name(pub Uuid);

        impl $name {
            /// Create new random id.
            pub fn random() -> $name {
                $name(Uuid::new(::uuid::UuidVersion::Random).expect("No randomness source"))
            }
        }

        impl Default for $name {
            fn default() -> $name {
                $name::random()
            }
        }

        impl ::std::str::FromStr for $name {
            type Err=String;
            fn from_str(s: &str) -> std::result::Result<$name, String> {
                let uuid = Uuid::parse_str(s).map_err(|_| format!("unparseable uuid {}", s))?;
                Ok($name(uuid))
            }
        }

        impl ToString for $name {
            fn to_string(&self) -> String {
                self.0.hyphenated().to_string()
            }
        }

        impl Id for $name {}

        impl ::serde::Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
                where S: ::serde::Serializer
            {
                serializer.serialize_str(&*self.to_string())
            }
        }

        impl ::serde::Deserialize for $name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
                where D: ::serde::Deserializer
            {
                struct Visitor;
                impl ::serde::de::Visitor for Visitor {
                    type Value = $name;

                    fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                        formatter.write_str("an hex hyphenated uuid")
                    }

                    fn visit_str<E>(self, v: &str) -> ::std::result::Result<Self::Value, E>
                        where E: ::serde::de::Error
                    {
                        use std::str::FromStr;
                        $name::from_str(v).map_err(|s| ::serde::de::Error::custom(s))
                    }

                }
                deserializer.deserialize_str(Visitor)
            }
        }
    }
}

macro_rules! identify {
    ($object:ident, $id:ident) => {
        impl Identified for $object {
            type I = $id;
            fn id(&self) -> &$id {
                &self.id
            }
        }
    }
}

/// Abstract object for signed message together with the signature and claimed signer.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Signed<M>
    where M: Clone + Debug + PartialEq + ::serde::Serialize + ::serde::Deserialize
{
    pub signature: Signature,
    pub signer: AgentId,
    pub body: M,
}

impl<M> std::ops::Deref for Signed<M>
    where M: Clone + Debug + PartialEq + ::serde::Serialize + ::serde::Deserialize
{
    type Target = M;
    fn deref(&self) -> &M {
        &self.body
    }
}

impl<ID, M> Identified for Signed<M>
    where M: Identified<I = ID> + Clone + Debug + PartialEq + Serialize + Deserialize,
          ID: Id
{
    type I = ID;
    fn id(&self) -> &ID {
        use std::ops::Deref;
        self.deref().id()
    }
}

/// Abstract trait for objects that may be signed.
pub trait Sign {
    /// Generate a canonical representation of the object.
    ///
    /// This will be the main object under consideration during signing and verification, and as 
    /// such it determines which fields are actually signed.
    fn canonical(&self) -> SdaResult<Vec<u8>>;
}

impl<T: ::serde::Serialize> Sign for T {
    fn canonical(&self) -> SdaResult<Vec<u8>> {
        Ok(::serde_json::to_vec(self)?)
    }
}

/// Abstract object for messages labelled by some form of identifier.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Labelled<ID, M>
    where M: Clone + Debug + PartialEq + ::serde::Serialize + ::serde::Deserialize,
          ID: Id + Clone + Debug + PartialEq + ::serde::Serialize + ::serde::Deserialize
{
    pub id: ID,
    pub body: M,
}

impl<ID, M> Identified for Labelled<ID, M>
    where M: Clone + Debug + PartialEq + ::serde::Serialize + ::serde::Deserialize,
          ID: Id + Clone + Debug + PartialEq + ::serde::Serialize + ::serde::Deserialize
{
    type I = ID;
    fn id(&self) -> &ID {
        &self.id
    }
}

pub fn label<ID, M>(id: &ID, body: &M) -> Labelled<ID, M>
    where M: Clone + Debug + PartialEq + ::serde::Serialize + ::serde::Deserialize,
          ID: Id + Clone + Debug + PartialEq + ::serde::Serialize + ::serde::Deserialize
{
    Labelled {
        id: id.clone(),
        body: body.clone(),
    }
}

/// Blob of binary data.
#[derive(Clone, Debug, PartialEq)]
pub struct Binary(pub Vec<u8>);

impl Binary {
    fn to_base64(&self) -> String {
        ::data_encoding::base64::encode(&*self.0)
    }

    fn from_base64(s: &str) -> ::std::result::Result<Binary, String> {
        Ok(Binary(::data_encoding::base64::decode(s.as_bytes()).map_err(|e| format!("Base64 decoding error: {}", e))?))
    }
}

impl ::serde::Serialize for Binary {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: ::serde::Serializer
    {
        serializer.serialize_str(&*self.to_base64())
    }
}

impl ::serde::Deserialize for Binary {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where D: ::serde::Deserializer
    {
        struct Visitor;
        impl ::serde::de::Visitor for Visitor {
            type Value = Binary;

            fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                formatter.write_str("a base64 string")
            }

            fn visit_str<E>(self, v: &str) -> ::std::result::Result<Self::Value, E>
                where E: ::serde::de::Error
            {
                Binary::from_base64(v).map_err(|s| ::serde::de::Error::custom(s))
            }
        }
        deserializer.deserialize_str(Visitor)
    }
}