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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! Object types defined in the Bitmessage protocol.

use std::{
    convert::{TryFrom, TryInto},
    fmt,
    io::{self, Read, Write},
};

use crate::{
    io::{LenBm, ReadFrom, SizedReadFrom, WriteTo},
    net::{Addr, AddrExt, OnionV3Addr, ParseOnionV3AddrError, SocketAddrExt},
    priv_util::ToHexString,
    time::Time,
    var_type::VarInt,
};

pub use crate::stream::StreamNumber;

/// Represents type of object such as public key or one-to-one message.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct ObjectType(u32);

impl ObjectType {
    /// Constructs an object type from a value.
    pub const fn new(value: u32) -> Self {
        Self(value)
    }

    /// Returns the value as `u32`.
    pub fn as_u32(self) -> u32 {
        self.0
    }
}

impl fmt::Display for ObjectType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl From<u32> for ObjectType {
    fn from(value: u32) -> Self {
        Self(value)
    }
}

impl WriteTo for ObjectType {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        self.0.write_to(w)
    }
}

impl ReadFrom for ObjectType {
    fn read_from(r: &mut dyn Read) -> io::Result<Self>
    where
        Self: Sized,
    {
        Ok(Self(u32::read_from(r)?))
    }
}

impl LenBm for ObjectType {
    fn len_bm(&self) -> usize {
        self.0.len_bm()
    }
}

/// A version number used in Bitmessage objects.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct ObjectVersion(VarInt);

impl fmt::Display for ObjectVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl ObjectVersion {
    /// Constructs an object version from a value.
    pub fn new(value: u64) -> Self {
        Self(value.into())
    }

    /// Returns the value as `u64`.
    pub fn as_u64(self) -> u64 {
        self.0.as_u64()
    }
}

impl From<u64> for ObjectVersion {
    fn from(value: u64) -> Self {
        Self(value.into())
    }
}

impl WriteTo for ObjectVersion {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        self.0.write_to(w)
    }
}

impl ReadFrom for ObjectVersion {
    fn read_from(r: &mut dyn Read) -> io::Result<Self>
    where
        Self: Sized,
    {
        Ok(Self(VarInt::read_from(r)?))
    }
}

impl LenBm for ObjectVersion {
    fn len_bm(&self) -> usize {
        self.0.len_bm()
    }
}

/// The header structure of Bitmessage objects.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Header {
    expires_time: Time,
    object_type: ObjectType,
    version: ObjectVersion,
    stream_number: StreamNumber,
}

impl Header {
    /// Constructs an object header from the specified parameters.
    pub fn new(
        expires_time: Time,
        object_type: ObjectType,
        version: ObjectVersion,
        stream_number: StreamNumber,
    ) -> Self {
        Self {
            expires_time,
            object_type,
            version,
            stream_number,
        }
    }

    /// Returns the expires time.
    pub fn expires_time(&self) -> Time {
        self.expires_time
    }

    /// Returns the object type.
    pub fn object_type(&self) -> ObjectType {
        self.object_type
    }

    /// Returns the object version.
    pub fn version(&self) -> ObjectVersion {
        self.version
    }

    /// Returns the stream number.
    pub fn stream_number(&self) -> StreamNumber {
        self.stream_number
    }
}

impl WriteTo for Header {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        self.expires_time.write_to(w)?;
        self.object_type.write_to(w)?;
        self.version.write_to(w)?;
        self.stream_number.write_to(w)?;
        Ok(())
    }
}

impl ReadFrom for Header {
    fn read_from(r: &mut dyn Read) -> io::Result<Self>
    where
        Self: Sized,
    {
        Ok(Self {
            expires_time: Time::read_from(r)?,
            object_type: ObjectType::read_from(r)?,
            version: ObjectVersion::read_from(r)?,
            stream_number: StreamNumber::read_from(r)?,
        })
    }
}

impl LenBm for Header {
    fn len_bm(&self) -> usize {
        self.expires_time.len_bm()
            + self.object_type.len_bm()
            + self.version.len_bm()
            + self.stream_number.len_bm()
    }
}

#[test]
fn test_header_write_to() {
    let test = Header::new(
        0x0123_4567_89ab_cdef.into(),
        2.into(),
        3u64.into(),
        1u32.into(),
    );
    let mut bytes = Vec::new();
    test.write_to(&mut bytes).unwrap();
    let expected = [
        0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x00, 0x00, 0x02, 3, 1,
    ];
    assert_eq!(bytes, expected);
}

#[test]
fn test_header_read_from() {
    use std::io::Cursor;

    let mut bytes = Cursor::new([
        0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x00, 0x00, 0x02, 3, 1,
    ]);
    let test = Header::read_from(&mut bytes).unwrap();
    let expected = Header::new(
        0x0123_4567_89ab_cdef.into(),
        2.into(),
        3u64.into(),
        1u32.into(),
    );
    assert_eq!(test, expected);
}

/// Known types of Bitmessage objects.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum ObjectKind {
    Getpubkey,
    Pubkey,
    Msg,
    Broadcast,
    Onionpeer,
    //I2p,
    //Addr,
}

const OBJECT_GETPUBKEY: u32 = 0;
const OBJECT_PUBKEY: u32 = 1;
const OBJECT_MSG: u32 = 2;
const OBJECT_BROADCAST: u32 = 3;
const OBJECT_ONIONPEER: u32 = 0x74_6f72;
//const OBJECT_I2P: u32 = 0x493250;
//const OBJECT_ADDR: u32 = 0x61646472;

/// The error type returned when a conversion from a Bitmessage object type
/// to a known object type fails.
///
/// This error is used as the error type for the `TryFrom` implementation
/// for `ObjectKind`.
///
/// The source object type is returned as a payload of this error type.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct TryFromObjectTypeError(ObjectType);

impl fmt::Display for TryFromObjectTypeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "unknown object type {}", self.0)
    }
}

impl std::error::Error for TryFromObjectTypeError {}

impl TryFrom<ObjectType> for ObjectKind {
    type Error = TryFromObjectTypeError;

    fn try_from(t: ObjectType) -> Result<Self, <Self as TryFrom<ObjectType>>::Error> {
        match t.as_u32() {
            OBJECT_GETPUBKEY => Ok(Self::Getpubkey),
            OBJECT_PUBKEY => Ok(Self::Pubkey),
            OBJECT_MSG => Ok(Self::Msg),
            OBJECT_BROADCAST => Ok(Self::Broadcast),
            OBJECT_ONIONPEER => Ok(Self::Onionpeer),
            _ => Err(TryFromObjectTypeError(t)),
        }
    }
}

impl From<ObjectKind> for ObjectType {
    fn from(kind: ObjectKind) -> Self {
        match kind {
            ObjectKind::Getpubkey => OBJECT_GETPUBKEY.into(),
            ObjectKind::Pubkey => OBJECT_PUBKEY.into(),
            ObjectKind::Msg => OBJECT_MSG.into(),
            ObjectKind::Broadcast => OBJECT_BROADCAST.into(),
            ObjectKind::Onionpeer => OBJECT_ONIONPEER.into(),
        }
    }
}

/// An extended network address object
/// that can represent IPv4, IPv6, Onion v2 or Onion v3 address.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Onionpeer {
    port: VarInt,
    addr: Vec<u8>,
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum TryFromOnionpeerError {
    InvalidPort(u64),
    InvalidLength(usize),
    InvalidPrefix([u8; 6]),
    ParseOnionV3AddrError(ParseOnionV3AddrError),
}

impl fmt::Display for TryFromOnionpeerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidPort(port) => write!(f, "invalid port: {}", port),
            Self::InvalidLength(len) => write!(f, "invalid length: {}", len),
            Self::InvalidPrefix(prefix) => {
                write!(f, "invalid prefix: {}", prefix.as_ref().to_hex_string())
            }
            Self::ParseOnionV3AddrError(err) => err.fmt(f),
        }
    }
}

impl std::error::Error for TryFromOnionpeerError {}

impl From<ParseOnionV3AddrError> for TryFromOnionpeerError {
    fn from(err: ParseOnionV3AddrError) -> Self {
        Self::ParseOnionV3AddrError(err)
    }
}

const ONION_PREFIX: [u8; 6] = [0xfd, 0x87, 0xd8, 0x7e, 0xeb, 0x43];

impl TryFrom<Onionpeer> for SocketAddrExt {
    type Error = TryFromOnionpeerError;

    fn try_from(op: Onionpeer) -> Result<Self, <Self as TryFrom<Onionpeer>>::Error> {
        if op.port.as_u64() > u16::MAX as u64 {
            return Err(TryFromOnionpeerError::InvalidPort(op.port.as_u64()));
        }
        let port = op.port.as_u64() as u16;
        let len = op.addr.len();
        if len == 16 {
            let bytes: [u8; 16] = op.addr[..].try_into().unwrap();
            let addr: Addr = bytes.into();
            let addr: AddrExt = addr.into();
            Ok(Self::new(addr, port))
        } else if len == 6 + 35 {
            if op.addr[0..6] != *ONION_PREFIX.as_ref() {
                let prefix = op.addr[0..6].try_into().unwrap();
                return Err(TryFromOnionpeerError::InvalidPrefix(prefix));
            }
            let mut bytes = [0; 35];
            bytes.copy_from_slice(&op.addr[6..]);
            let addr = OnionV3Addr::new(bytes)?;
            let addr = AddrExt::OnionV3(addr);
            Ok(Self::new(addr, port))
        } else {
            Err(TryFromOnionpeerError::InvalidLength(len))
        }
    }
}

const IPV4_PREFIX: [u8; 12] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff];

impl From<SocketAddrExt> for Onionpeer {
    fn from(addr: SocketAddrExt) -> Self {
        match addr {
            SocketAddrExt::Ipv4(sa) => {
                let port: VarInt = (sa.port() as u64).into();
                let mut addr = IPV4_PREFIX.clone().to_vec();
                addr.extend_from_slice(&sa.ip().octets());
                Self { port, addr }
            }
            SocketAddrExt::Ipv6(sa) => {
                let port: VarInt = (sa.port() as u64).into();
                let addr = sa.ip().octets().to_vec();
                Self { port, addr }
            }
            SocketAddrExt::OnionV2(sa) => {
                let port: VarInt = (sa.port() as u64).into();
                let mut addr = ONION_PREFIX.clone().to_vec();
                addr.extend_from_slice(sa.onion_addr().as_ref());
                Self { port, addr }
            }
            SocketAddrExt::OnionV3(sa) => {
                let port: VarInt = (sa.port() as u64).into();
                let mut addr = ONION_PREFIX.clone().to_vec();
                addr.extend_from_slice(sa.onion_addr().as_ref());
                Self { port, addr }
            }
        }
    }
}

impl WriteTo for Onionpeer {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        self.port.write_to(w)?;
        self.addr.write_to(w)?;
        Ok(())
    }
}

impl SizedReadFrom for Onionpeer {
    fn sized_read_from(r: &mut dyn Read, len: usize) -> io::Result<Self>
    where
        Self: Sized,
    {
        let port = VarInt::read_from(r)?;
        let addr = Vec::<u8>::sized_read_from(r, len - port.len_bm())?;
        Ok(Self { port, addr })
    }
}