koibumi-core 0.0.9

The core library for Koibumi, an experimental Bitmessage client
Documentation
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
use std::{
    fmt,
    io::{self, Read, Write},
    net::{Ipv4Addr, SocketAddrV4},
};

use rand::random;
use serde::{Deserialize, Serialize};

use crate::{
    config::Config,
    io::{LimitedReadFrom, ReadFrom, WriteTo},
    message::Message,
    net::SocketAddr,
    net_addr::Services,
    packet::Command,
    stream::StreamNumbers,
    time::Time,
    var_type::VarStr,
};

/// A Bitmessage protocol version number used in a version message.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Serialize, Deserialize)]
pub struct ProtocolVersion(u32);

impl ProtocolVersion {
    /// Constructs a protocol version from a value.
    pub fn new(value: u32) -> Self {
        Self(value)
    }

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

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

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

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

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

/// A random value specific to a node, which is used by the node
/// to detect if connecting to itself.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct NodeNonce(u64);

impl NodeNonce {
    /// Constructs a node nonce from a value.
    pub fn new(value: u64) -> Self {
        Self(value)
    }

    /// Constructs a node nonce from a random value.
    pub fn random() -> Self {
        Self(random::<u64>())
    }

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

impl fmt::Display for NodeNonce {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:016x}", self.0)
    }
}

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

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

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

/// A user agent string of a Bitmessage node.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Serialize, Deserialize)]
pub struct UserAgent(VarStr);

impl UserAgent {
    /// Constructs a user agent string from a byte array.
    pub fn new(bytes: Vec<u8>) -> Self {
        Self(VarStr::new(bytes))
    }
}

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

impl From<Vec<u8>> for UserAgent {
    fn from(bytes: Vec<u8>) -> Self {
        Self(bytes.into())
    }
}

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

impl LimitedReadFrom for UserAgent {
    fn limited_read_from(r: &mut dyn Read, max_len: usize) -> io::Result<Self>
    where
        Self: Sized,
    {
        Ok(Self(VarStr::limited_read_from(r, max_len)?))
    }
}

/// A "version" message that is exchanged between nodes when connected,
/// which informs what type of node it is.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Version {
    version: ProtocolVersion,
    services: Services,
    timestamp: Time,
    remote_services: Services,
    addr_recv: SocketAddr,
    services2: Services,
    addr_from: SocketAddr,
    nonce: NodeNonce,
    user_agent: UserAgent,
    stream_numbers: StreamNumbers,
}

impl Version {
    const MAX_USER_AGENT_LENGTH: usize = 5000 - 3;

    /// Constructs a builder for building a version message.
    pub fn builder(config: &Config, nonce: NodeNonce, user_agent: UserAgent) -> VersionBuilder {
        VersionBuilder::new(config, nonce, user_agent)
    }

    /// Returns the protocol version.
    pub fn version(&self) -> ProtocolVersion {
        self.version
    }

    /// Returns the flags what features the node serves.
    pub fn services(&self) -> Services {
        self.services
    }

    /// Returns the timestamp.
    pub fn timestamp(&self) -> Time {
        self.timestamp
    }

    /*
        /// Returns the remote services.
        pub fn remote_services(&self) -> Services {
            self.remote_services
        }

        /// Returns the addr recv.
        pub fn addr_recv(&self) -> &SocketAddr {
            &self.addr_recv
        }

        /// Returns the services2.
        pub fn services2(&self) -> Services {
            self.services2
        }

        /// Returns the addr from.
        pub fn addr_from(&self) -> &SocketAddr {
            &self.addr_from
        }
    */

    /// Returns the node nonce.
    pub fn nonce(&self) -> NodeNonce {
        self.nonce
    }

    /// Returns the user agent.
    pub fn user_agent(&self) -> &UserAgent {
        &self.user_agent
    }

    /// Returns the list of stream numbers.
    pub fn stream_numbers(&self) -> &StreamNumbers {
        &self.stream_numbers
    }
}

impl WriteTo for Version {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        self.version.write_to(w)?;
        self.services.write_to(w)?;
        self.timestamp.write_to(w)?;
        self.remote_services.write_to(w)?;
        self.addr_recv.write_to(w)?;
        self.services2.write_to(w)?;
        self.addr_from.write_to(w)?;
        self.nonce.write_to(w)?;
        self.user_agent.write_to(w)?;
        self.stream_numbers.write_to(w)?;
        Ok(())
    }
}

impl ReadFrom for Version {
    fn read_from(r: &mut dyn Read) -> io::Result<Self>
    where
        Self: Sized,
    {
        Ok(Self {
            version: ProtocolVersion::read_from(r)?,
            services: Services::read_from(r)?,
            timestamp: Time::read_from(r)?,
            remote_services: Services::read_from(r)?,
            addr_recv: SocketAddr::read_from(r)?,
            services2: Services::read_from(r)?,
            addr_from: SocketAddr::read_from(r)?,
            nonce: NodeNonce::read_from(r)?,
            user_agent: UserAgent::limited_read_from(r, Self::MAX_USER_AGENT_LENGTH)?,
            stream_numbers: StreamNumbers::read_from(r)?,
        })
    }
}

impl Message for Version {
    const COMMAND: Command = Command::VERSION;
}

/// A builder for building a version message.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct VersionBuilder {
    message: Version,
}

lazy_static! {
    pub(crate) static ref LOCAL_SOCKET_ADDR: SocketAddr =
        SocketAddr::Ipv4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 8444));
}

impl VersionBuilder {
    fn new(config: &Config, nonce: NodeNonce, user_agent: UserAgent) -> Self {
        let stream_numbers: StreamNumbers = vec![1_u32.into()].into();
        let message = Version {
            version: config.protocol_version(),
            services: Services::NETWORK,
            timestamp: Time::now(),
            remote_services: Services::NETWORK,
            addr_recv: LOCAL_SOCKET_ADDR.clone(),
            services2: Services::NETWORK,
            addr_from: LOCAL_SOCKET_ADDR.clone(),
            nonce,
            user_agent,
            stream_numbers,
        };
        Self { message }
    }

    /// Sets the flags what features the node serves.
    pub fn services(&mut self, services: Services) -> &mut Self {
        self.message.services = services;
        self
    }

    /// Sets the timestamp.
    pub fn timestamp(&mut self, timestamp: Time) -> &mut Self {
        self.message.timestamp = timestamp;
        self
    }

    /*
        /// Sets the remote services.
        pub fn remote_services(&mut self, services: Services) -> &mut Self {
            self.message.remote_services = services;
            self
        }

        /// Sets the addr recv.
        pub fn addr_recv(&mut self, addr: SocketAddr) -> &mut Self {
            self.message.addr_recv = addr;
            self
        }

        /// Sets the services2.
        pub fn services2(&mut self, services: Services) -> &mut Self {
            self.message.services2 = services;
            self
        }

        /// Sets the addr from.
        pub fn addr_from(&mut self, addr: SocketAddr) -> &mut Self {
            self.message.addr_from = addr;
            self
        }
    */

    /// Sets the list of stream numbers.
    pub fn stream_numbers(&mut self, list: StreamNumbers) -> &mut Self {
        self.message.stream_numbers = list;
        self
    }

    /// Returns the version message this builder represents.
    pub fn build(&self) -> Version {
        self.message.clone()
    }
}

#[test]
fn test_version_write_to() {
    let config = Config::new();
    let stream_numbers: StreamNumbers = vec![1_u32.into(), 2_u32.into()].into();
    let test = Version::builder(
        &config,
        0x0123_4567_89ab_cdef.into(),
        b"hello".to_vec().into(),
    )
    .stream_numbers(stream_numbers)
    .build();
    let mut bytes = Vec::new();
    test.write_to(&mut bytes).unwrap();
    bytes[12..20].copy_from_slice(&[0xff; 8]);
    let expected = [
        0, 0, 0, 3, //
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //
        0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, //
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 127, 0, 0, 1, 0x20, 0xfc, //
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 127, 0, 0, 1, 0x20, 0xfc, //
        0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, //
        5, b'h', b'e', b'l', b'l', b'o', //
        2, 1, 2, //
    ];
    assert_eq!(bytes, expected.to_vec());
}

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

    let mut bytes = Cursor::new(
        [
            0, 0, 0, 3, //
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, //
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 127, 0, 0, 1, 0x20, 0xfc, //
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 127, 0, 0, 1, 0x20, 0xfc, //
            0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, //
            5, b'h', b'e', b'l', b'l', b'o', //
            2, 1, 2, //
        ]
        .to_vec(),
    );
    let test = Version::read_from(&mut bytes).unwrap();
    let stream_numbers: StreamNumbers = vec![1_u32.into(), 2_u32.into()].into();
    let config = Config::new();
    let mut expected = Version::builder(
        &config,
        0x0123_4567_89ab_cdef.into(),
        b"hello".to_vec().into(),
    )
    .stream_numbers(stream_numbers)
    .build();
    expected.timestamp = 0xffff_ffff_ffff_ffff.into();
    assert_eq!(test, expected);
}