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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
//! ssb-tfk
//!
//! A module that implements the Type Format Key (TFK) encoding of ssb message keys.
//! Spec defined [here](https://github.com/ssbc/envelope-spec/blob/master/encoding/tfk.md)
//!
//! Enable the `multiformats` feature to include type conversions to / from multiformats types.

use snafu::{OptionExt, ResultExt, Snafu};

#[cfg(feature = "multiformats")]
pub use ssb_multiformats::multifeed::Multifeed;
#[cfg(feature = "multiformats")]
pub use ssb_multiformats::multihash::Multihash;
#[cfg(feature = "multiformats")]
pub use ssb_multiformats::multikey::Multikey;

#[cfg(feature = "multiformats")]
use std::convert::TryFrom;

use std::io::Read;
use std::io::Write;

#[derive(Snafu, Debug)]
pub enum Error {
    InvalidType,
    InvalidFormat,
    NotEnoughBytes,
    WriteError { source: std::io::Error },
    ReadError { source: std::io::Error },
}

// TODO: use constants from ssb_crypto
const FEED_KEY_LENGTH: usize = 32;
const MESSAGE_KEY_LENGTH: usize = 32;
const BLOB_KEY_LENGTH: usize = 32;
const DIFFIE_HELLMAN_KEY_LENGTH: usize = 32;

/// A KeyType represents the type of the key, as well as owning the actual bytes of the key.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum KeyType {
    Feed([u8; FEED_KEY_LENGTH]),                    // 0
    Message([u8; MESSAGE_KEY_LENGTH]),              // 1
    Blob([u8; BLOB_KEY_LENGTH]),                    // 2
    DiffieHellman([u8; DIFFIE_HELLMAN_KEY_LENGTH]), // 3
}

impl KeyType {
    pub fn get_encoding_type_byte(&self) -> u8 {
        match self {
            KeyType::Feed(_) => 0,
            KeyType::Message(_) => 1,
            KeyType::Blob(_) => 2,
            KeyType::DiffieHellman(_) => 3,
        }
    }
    pub fn get_key_bytes(&self) -> &[u8] {
        match self {
            KeyType::Feed(bytes) => bytes,
            KeyType::Message(bytes) => bytes,
            KeyType::Blob(bytes) => bytes,
            KeyType::DiffieHellman(bytes) => bytes,
        }
    }

    pub fn decode_read<R: Read>(type_byte: u8, reader: &mut R) -> Result<Self, Error> {
        match type_byte {
            0 => {
                let mut key_bytes = [0u8; FEED_KEY_LENGTH];
                reader.read_exact(&mut key_bytes).context(ReadError)?;
                Ok(KeyType::Feed(key_bytes))
            }
            1 => {
                let mut key_bytes = [0u8; MESSAGE_KEY_LENGTH];
                reader.read_exact(&mut key_bytes).context(ReadError)?;
                Ok(KeyType::Message(key_bytes))
            }
            2 => {
                let mut key_bytes = [0u8; BLOB_KEY_LENGTH];
                reader.read_exact(&mut key_bytes).context(ReadError)?;
                Ok(KeyType::Blob(key_bytes))
            }
            3 => {
                let mut key_bytes = [0u8; DIFFIE_HELLMAN_KEY_LENGTH];
                reader.read_exact(&mut key_bytes).context(ReadError)?;
                Ok(KeyType::DiffieHellman(key_bytes))
            }
            _ => Err(Error::InvalidType),
        }
    }
}

/// Format encodes the message format, either `Classic` (javascript ssb) or `GabbyGrove` (go ssb)
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Format {
    Classic = 0,
    GabbyGrove = 1,
}

impl Format {
    pub fn encode(&self) -> u8 {
        *self as u8
    }
    pub fn encode_write<W: Write>(&self, writer: &mut W) -> Result<(), Error> {
        writer.write(&[self.encode()]).context(WriteError)?;
        Ok(())
    }

    pub fn decode(byte: u8) -> Result<Self, Error> {
        match byte {
            0 => Ok(Format::Classic),
            1 => Ok(Format::GabbyGrove),
            _ => Err(Error::InvalidFormat),
        }
    }
}

/// TypeFormatKey is able to represent any of the current ssb key types and encode / decode them to
/// the TFK binary representation.
#[derive(PartialEq, Debug)]
pub struct TypeFormatKey {
    pub key_type: KeyType,
    pub format: Format,
}

impl TypeFormatKey {
    pub fn new(key_type: KeyType, format: Format) -> TypeFormatKey {
        TypeFormatKey { key_type, format }
    }

    pub fn encode_write<W: Write>(&self, writer: &mut W) -> Result<(), Error> {
        let type_byte = self.key_type.get_encoding_type_byte();
        writer.write(&[type_byte]).context(WriteError)?;

        self.format.encode_write(writer)?;

        let key = self.key_type.get_key_bytes();
        writer.write(key).context(WriteError)?;
        Ok(())
    }

    pub fn decode_read<R: Read>(reader: &mut R) -> Result<TypeFormatKey, Error> {
        let mut header_bytes = [0u8; 2];
        reader.read_exact(&mut header_bytes).context(ReadError)?;

        let key_type_byte = header_bytes.get(0).context(NotEnoughBytes)?;

        let format_byte = header_bytes.get(1).context(NotEnoughBytes)?;
        let format = Format::decode(*format_byte)?;

        let key_type = KeyType::decode_read(*key_type_byte, reader)?;

        Ok(TypeFormatKey { key_type, format })
    }
}

/// All Multihashes can be converted to a TypeFormatKey so this conversion can never fail.
#[cfg(feature = "multiformats")]
impl From<Multihash> for TypeFormatKey {
    fn from(multihash: Multihash) -> Self {
        let key_type = match multihash {
            Multihash::Message(hash) => KeyType::Message(hash),
            Multihash::Blob(hash) => KeyType::Blob(hash),
        };

        TypeFormatKey {
            key_type,
            format: Format::Classic,
        }
    }
}

/// All Multifeeds can be converted to a TypeFormatKey so this conversion can never fail.
#[cfg(feature = "multiformats")]
impl From<Multifeed> for TypeFormatKey {
    fn from(multifeed: Multifeed) -> Self {
        let key_type = match multifeed {
            Multifeed::Multikey(Multikey::Ed25519(hash)) => KeyType::Feed(hash.0),
        };

        TypeFormatKey {
            key_type,
            format: Format::Classic,
        }
    }
}

/// _Not_ all TypeFormatKeys are Multihashes so this conversion can fail.
#[cfg(feature = "multiformats")]
impl TryFrom<TypeFormatKey> for Multihash {
    type Error = Error;

    fn try_from(type_format_key: TypeFormatKey) -> Result<Self, Self::Error> {
        match type_format_key.key_type {
            KeyType::Message(key) => Ok(Multihash::Message(key)),
            KeyType::Blob(key) => Ok(Multihash::Blob(key)),
            _ => Err(Error::InvalidType),
        }
    }
}

/// _Not_ all TypeFormatKeys are Multifeeds so this conversion can fail.
#[cfg(feature = "multiformats")]
impl TryFrom<TypeFormatKey> for Multifeed {
    type Error = Error;

    fn try_from(type_format_key: TypeFormatKey) -> Result<Self, Self::Error> {
        match type_format_key.key_type {
            KeyType::Feed(key) => Ok(Multifeed::Multikey(Multikey::from_ed25519(&key))),
            _ => Err(Error::InvalidType),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::*;
    #[cfg(feature = "multiformats")]
    use std::convert::TryFrom;


    #[test]
    fn encode_decode() {
        let key_type = KeyType::Blob([6; BLOB_KEY_LENGTH]);
        let format = Format::GabbyGrove;

        let tfk = TypeFormatKey { key_type, format };

        let mut encoded = Vec::new();

        tfk.encode_write(&mut encoded).unwrap();

        let decoded = TypeFormatKey::decode_read(&mut encoded.as_slice()).unwrap();

        assert_eq!(decoded, tfk);
    }

    // To run the tests below, you need to enable the multiformats feature eg `$ cargo test
    // --features="multiformats"`
    
    // Converts from a ssb "legacy" string message id -> multihash  -> tfk -> binary encoded tfk -> tfk -> multihash
    #[test]
    #[cfg(feature = "multiformats")]
    fn message_from_to_multihash() {
        let (multihash, _) =
            Multihash::from_legacy(b"%39f9I0e4bEln+yy6850joHRTqmEQfUyxssv54UANNuk=.sha256")
                .unwrap();
        let tfk: TypeFormatKey = multihash.clone().into();
        match tfk.key_type {
            KeyType::Message(_) => (),
            _ => assert!(false, "Incorrect key type"),
        }

        let mut encoded = Vec::new();

        tfk.encode_write(&mut encoded).unwrap();

        let decoded = TypeFormatKey::decode_read(&mut encoded.as_slice()).unwrap();

        let new_multihash = Multihash::try_from(decoded).unwrap();
        assert_eq!(new_multihash, multihash);
    }

    // Converts from a ssb "legacy" string blob id -> multihash  -> tfk -> binary encoded tfk -> tfk -> multihash
    #[test]
    #[cfg(feature = "multiformats")]
    fn blob_from_to_multihash() {
        let (multihash, _) =
            Multihash::from_legacy(b"&39f9I0e4bEln+yy6850joHRTqmEQfUyxssv54UANNuk=.sha256")
                .unwrap();
        let tfk: TypeFormatKey = multihash.clone().into();
        match tfk.key_type {
            KeyType::Blob(_) => (),
            _ => assert!(false, "Incorrect key type"),
        }

        let mut encoded = Vec::new();

        tfk.encode_write(&mut encoded).unwrap();

        let decoded = TypeFormatKey::decode_read(&mut encoded.as_slice()).unwrap();

        let new_multihash = Multihash::try_from(decoded).unwrap();
        assert_eq!(new_multihash, multihash);
    }

    // Converts from a ssb "legacy" string feed id -> multifeed  -> tfk -> binary encoded tfk -> tfk -> multifeed
    #[test]
    #[cfg(feature = "multiformats")]
    fn feed_from_to_multifeed() {
        let (multifeed, _) =
            Multifeed::from_legacy(b"@EtTsMe7l6ap8aRHp2H4XaUpqZpXkieOqjjM7cvj493Q=.ed25519")
                .unwrap();
        let tfk: TypeFormatKey = multifeed.clone().into();
        match tfk.key_type {
            KeyType::Feed(_) => (),
            _ => assert!(false, "Incorrect key type"),
        }

        let mut encoded = Vec::new();

        tfk.encode_write(&mut encoded).unwrap();

        let decoded = TypeFormatKey::decode_read(&mut encoded.as_slice()).unwrap();

        let new_multifeed = Multifeed::try_from(decoded).unwrap();
        assert_eq!(new_multifeed, multifeed);
    }
}