splinter 0.6.14

Splinter is a privacy-focused platform for distributed applications that provides a blockchain-inspired networking environment for communication and transactions between organizations.
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
// Copyright 2018-2022 Cargill Incorporated
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::io::{self, Cursor, Read, Write};
use std::thread;
use std::time::Duration;

use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};

const HEADER_LENGTH: usize = 6;

/// An error that may be returned during frame-related operations
#[derive(Debug)]
pub enum FrameError {
    IoError(io::Error),
    InvalidChecksum,
    InvalidHeaderLength(usize),
    UnsupportedVersion,
    HandshakeFailure(String),
}

impl std::fmt::Display for FrameError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            FrameError::IoError(err) => f.write_str(&err.to_string()),
            FrameError::InvalidChecksum => f.write_str("Invalid checksum in frame header"),
            FrameError::InvalidHeaderLength(n) => write!(
                f,
                "Invalid header length expected {} but was {}",
                HEADER_LENGTH, n
            ),
            FrameError::UnsupportedVersion => f.write_str("Unsupported frame version"),
            FrameError::HandshakeFailure(msg) => f.write_str(msg),
        }
    }
}

impl std::error::Error for FrameError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            FrameError::IoError(err) => Some(&*err),
            FrameError::InvalidChecksum => None,
            FrameError::InvalidHeaderLength(_) => None,
            FrameError::UnsupportedVersion => None,
            FrameError::HandshakeFailure(_) => None,
        }
    }
}

impl From<io::Error> for FrameError {
    fn from(err: io::Error) -> Self {
        FrameError::IoError(err)
    }
}

/// The Frame version
///
/// This specifies the version of the frame, based on what value is sent during frame transmission.
/// It indicates header style and data requirements.
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum FrameVersion {
    V1 = 1,
}

impl std::fmt::Display for FrameVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "v{}", *self as u32)
    }
}

/// A complete Frame of transmitted data.
///
/// This struct owns the data that has been transmitted.  It is essentially a receiving frame.
pub struct Frame {
    data: Vec<u8>,
}

impl Frame {
    /// Convert this frame into its inner byte vector.
    pub fn into_inner(self) -> Vec<u8> {
        self.data
    }

    /// Read a frame from the given reader.
    ///
    /// # Errors
    ///
    /// This function returns an error if:
    ///
    /// - the header is malformed
    /// - the data length doesn't match the header length
    /// - an IO error occurs
    pub fn read<R: Read>(reader: &mut R) -> Result<Self, FrameError> {
        let frame_header = loop {
            match FrameHeader::read(reader) {
                Err(FrameError::IoError(ref e)) if e.kind() == io::ErrorKind::WouldBlock => {
                    thread::sleep(Duration::from_millis(100));
                    continue;
                }
                Err(err) => return Err(err),
                Ok(header) => break header,
            };
        };

        match frame_header {
            FrameHeader::V1 { length } => {
                let mut buffer = vec![0; length as usize];
                let mut remaining = &mut buffer[..];

                while !remaining.is_empty() {
                    match reader.read(remaining) {
                        Ok(0) => break,
                        Ok(n) => {
                            let tmp = remaining;
                            remaining = &mut tmp[n..];
                        }
                        Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
                        Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                            thread::sleep(Duration::from_millis(100));
                        }
                        Err(e) => return Err(FrameError::IoError(e)),
                    }
                }
                if !remaining.is_empty() {
                    Err(FrameError::IoError(io::Error::new(
                        io::ErrorKind::UnexpectedEof,
                        "Could not receive complete frame",
                    )))
                } else {
                    Ok(Self { data: buffer })
                }
            }
        }
    }
}

/// A Frame of referenced data to be transmitted using a specified version.
///
/// This struct references the data that has been transmitted.  It is essentially a sending frame.
pub struct FrameRef<'a> {
    version: FrameVersion,
    data: &'a [u8],
}

impl<'a> FrameRef<'a> {
    /// Construct a FrameRef for the given byte slice, which will be transmitted using the given
    /// frame version.
    pub fn new<'b: 'a>(version: FrameVersion, data: &'b [u8]) -> FrameRef<'a> {
        Self { version, data }
    }

    /// Write the frame to the given writer.
    ///
    /// # Errors
    ///
    /// Returns a FrameError if an IO error occurs.
    pub fn write<W: Write>(self, writer: &mut W) -> Result<(), FrameError> {
        let frame_header = match self.version {
            FrameVersion::V1 => FrameHeader::v1(self.data.len() as u32),
        };
        loop {
            match frame_header.write(writer) {
                Err(FrameError::IoError(ref e)) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    thread::sleep(Duration::from_millis(100));
                    continue;
                }
                Err(err) => return Err(err),
                Ok(_) => break,
            }
        }

        let mut buffer = self.data;
        while !buffer.is_empty() {
            match writer.write(buffer) {
                Ok(0) => {
                    return Err(FrameError::IoError(std::io::Error::new(
                        std::io::ErrorKind::WriteZero,
                        "failed to write whole buffer",
                    )))
                }
                Ok(n) => buffer = &buffer[n..],
                Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
                Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    thread::sleep(Duration::from_millis(100));
                }
                Err(e) => return Err(FrameError::IoError(e)),
            }
        }
        writer.flush()?;
        Ok(())
    }
}

/// A FrameHeader.
///
/// Each variant corresponds to the implementation for a given version.
#[derive(Debug, PartialEq)]
enum FrameHeader {
    V1 { length: u32 },
}

impl FrameHeader {
    /// Construct a version 1 frame header.
    fn v1(length: u32) -> Self {
        FrameHeader::V1 { length }
    }

    /// Read a FrameHeader from the given reader.
    ///
    /// This function uses the first 2 bytes of the stream to read the version, and constructs the
    /// corresponding frame header variant accordingly.
    ///
    /// # Errors
    ///
    /// Returns a FrameError if:
    ///
    /// - the version received does not match any of the existing variants
    /// - the frame header is not the proper length
    /// - the frame version fails its checksum
    /// - an IO error occurs
    fn read<R: Read>(reader: &mut R) -> Result<Self, FrameError> {
        let version = reader.read_u16::<BigEndian>()?;
        match version {
            1 => {
                // Header length + checksum byte
                let mut buffer = [0u8; HEADER_LENGTH + 1];
                let mut cursor = Cursor::new(&mut buffer[..]);
                cursor.write_u16::<BigEndian>(1u16)?;

                let n = reader.read(&mut cursor.get_mut()[std::mem::size_of::<u16>()..])?;
                if n != HEADER_LENGTH + 1 - std::mem::size_of::<u16>() {
                    return Err(FrameError::InvalidHeaderLength(n));
                }

                let checksum = compute_checksum(&cursor.get_ref()[..HEADER_LENGTH]);
                if checksum != cursor.get_ref()[HEADER_LENGTH] {
                    return Err(FrameError::InvalidChecksum);
                }

                Ok(FrameHeader::V1 {
                    length: cursor.read_u32::<BigEndian>()?,
                })
            }
            _ => Err(FrameError::UnsupportedVersion),
        }
    }

    /// Write this FrameHeader to the given writer.
    ///
    /// # Errors
    ///
    /// Returns a FrameError if:
    ///
    /// - an IO error occurs
    fn write<W: Write>(&self, writer: &mut W) -> Result<(), FrameError> {
        match *self {
            FrameHeader::V1 { length } => {
                let mut header_bytes = [0u8; HEADER_LENGTH + 1];
                let mut cursor = Cursor::new(&mut header_bytes[..]);

                cursor.write_u16::<BigEndian>(1)?;
                cursor.write_u32::<BigEndian>(length)?;

                // reserve the remaining bytes

                cursor.get_mut()[HEADER_LENGTH] =
                    compute_checksum(&cursor.get_ref()[..HEADER_LENGTH]);

                writer.write_all(cursor.into_inner())?;
            }
        }

        Ok(())
    }
}

/// Compute a longitudinal check-sum
fn compute_checksum(buffer: &[u8]) -> u8 {
    // International standard ISO 1155[7] states that a longitudinal redundancy check for a
    // sequence of bytes may be computed in software by the following algorithm
    // lrc := 0
    // for each byte b in the buffer do
    //     lrc := (lrc + b) and 0xFF
    // lrc := (((lrc XOR 0xFF) + 1) and 0xFF)

    let mut lrc = 0u16;
    for b in buffer {
        lrc = (lrc + (*b as u16)) & 0x00ff;
    }

    lrc = ((lrc ^ 0x00ff) + 1u16) & 0xff;

    lrc as u8
}

/// Negotiate the frame version for a given socket connection.
pub enum FrameNegotiation {
    /// The Outbound variant transmits the min and max supported version, and expects to receive
    /// either a version in that range, or `0` if the other end cannot support the a version in
    /// that range.
    Outbound {
        min: FrameVersion,
        max: FrameVersion,
    },
    /// The Inbound variant transmits receives the min and max and decides if it should send its
    /// version or `0`, depending on whether or not it falls in the range.
    Inbound { version: FrameVersion },
}

impl FrameNegotiation {
    /// Construct the outbound side of a negotiation with the given min,max.
    pub fn outbound(min: FrameVersion, max: FrameVersion) -> Self {
        FrameNegotiation::Outbound { min, max }
    }

    /// Construct the inbound side of a negotiation with the given version.
    pub fn inbound(version: FrameVersion) -> Self {
        FrameNegotiation::Inbound { version }
    }

    /// Negotiate frame version to use for future communications over the given stream.
    ///
    /// # Errors
    ///
    /// Returns a FrameError if:
    ///
    /// - either end cannot agree on a version
    /// - an IO error, if one occurs
    pub fn negotiate<S: Read + Write>(self, stream: &mut S) -> Result<FrameVersion, FrameError> {
        match self {
            FrameNegotiation::Outbound { min, max } => {
                stream
                    .write_u16::<BigEndian>(min as u16)
                    .map_err(Self::map_io_err)?;
                stream
                    .write_u16::<BigEndian>(max as u16)
                    .map_err(Self::map_io_err)?;

                let frame_version = stream.read_u16::<BigEndian>().map_err(Self::map_io_err)?;

                match frame_version {
                    0 => Err(FrameError::UnsupportedVersion),
                    1 => Ok(FrameVersion::V1),
                    _ => Err(FrameError::UnsupportedVersion),
                }
            }
            FrameNegotiation::Inbound { version } => {
                let min = stream.read_u16::<BigEndian>().map_err(Self::map_io_err)?;
                let max = stream.read_u16::<BigEndian>().map_err(Self::map_io_err)?;
                if min > version as u16 || max < version as u16 {
                    stream.write_u16::<BigEndian>(0).map_err(Self::map_io_err)?;
                    Err(FrameError::UnsupportedVersion)
                } else {
                    stream
                        .write_u16::<BigEndian>(version as u16)
                        .map_err(Self::map_io_err)?;
                    Ok(version)
                }
            }
        }
    }

    fn map_io_err(err: io::Error) -> FrameError {
        use io::ErrorKind::*;
        match err.kind() {
            UnexpectedEof | ConnectionReset | ConnectionAborted | BrokenPipe => {
                FrameError::HandshakeFailure(
                    "unable to complete handshake due to closed connection".into(),
                )
            }
            _ => FrameError::IoError(err),
        }
    }
}

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

    use std::thread;

    /// Test that a v1 frame header with a data length of 0 and the correct checksum will be read
    /// correctly into a FrameHeader.
    #[test]
    fn read_version_1_zero_length() {
        let header_bytes = vec![0u8; HEADER_LENGTH + 1];
        let mut header_cursor = Cursor::new(header_bytes);

        header_cursor
            .write_u16::<BigEndian>(1)
            .expect("Could not write to cursor");
        // set the checksum for 1 xored + 1
        header_cursor.get_mut()[HEADER_LENGTH] = 0xff;

        header_cursor.set_position(0);

        let frame_header = FrameHeader::read(&mut header_cursor).expect("Unable to read_header");

        assert_eq!(FrameHeader::v1(0), frame_header);
    }

    /// Test that a v1 frame header with a data length of 2 and the correct checksum will be read
    /// correctly into a FrameHeader.
    #[test]
    fn read_version_and_length() {
        let header_bytes = vec![0u8; HEADER_LENGTH + 1];
        let mut header_cursor = Cursor::new(header_bytes);

        header_cursor
            .write_u16::<BigEndian>(1)
            .expect("Could not write version to cursor");
        header_cursor
            .write_u32::<BigEndian>(2)
            .expect("Could not write length to cursor");
        // set the checksum for 1 xored + 1
        header_cursor.get_mut()[HEADER_LENGTH] = 0xfd;

        header_cursor.set_position(0);

        let frame_header = FrameHeader::read(&mut header_cursor).expect("Unable to read_header");

        assert_eq!(FrameHeader::v1(2), frame_header);
    }

    /// Test that a v1 frame header with an invalid checksum will return an error when read.
    #[test]
    fn fail_checksum() {
        let header_bytes = vec![0u8; HEADER_LENGTH + 1];
        let mut header_cursor = Cursor::new(header_bytes);

        header_cursor
            .write_u16::<BigEndian>(1)
            .expect("Could not write version to cursor");
        header_cursor
            .write_u32::<BigEndian>(2)
            .expect("Could not write length to cursor");
        header_cursor.set_position(0);

        match FrameHeader::read(&mut header_cursor) {
            Ok(_) => panic!("Should not have produced a frame header"),
            Err(FrameError::InvalidChecksum) => (),
            Err(err) => panic!("Produced invalid error: {}", err),
        }
    }

    /// Test that a v1 FrameHeader with a given length will be correctly written to bytes,
    /// producing the correct checksum.
    #[test]
    fn standard_write() {
        let header_bytes = vec![0u8; HEADER_LENGTH + 1];
        let mut header_cursor = Cursor::new(header_bytes);

        let frame_header = FrameHeader::v1(3);

        frame_header
            .write(&mut header_cursor)
            .expect("Unable to write frame header");

        header_cursor.set_position(0);
        assert_eq!(
            1,
            header_cursor
                .read_u16::<BigEndian>()
                .expect("Unable to read version")
        );
        assert_eq!(
            3,
            header_cursor
                .read_u32::<BigEndian>()
                .expect("Unable to read length")
        );

        assert_eq!(0xFC, header_cursor.get_ref()[HEADER_LENGTH]);
    }

    /// Test a round-trip write and read of a FrameHeader.  Construct a valid FrameHeader, and
    /// write it to bytes.  Read a new FrameHeader from the bytes and verify that they are equal.
    #[test]
    fn round_trip() {
        let header_bytes = vec![0u8; HEADER_LENGTH + 1];
        let mut header_cursor = Cursor::new(header_bytes);

        let frame_header = FrameHeader::v1(100);

        frame_header
            .write(&mut header_cursor)
            .expect("Unable to write frame header");

        header_cursor.set_position(0);
        let FrameHeader::V1 { length } =
            FrameHeader::read(&mut header_cursor).expect("Unable to read header");

        assert_eq!(100, length);
    }

    /// Test that outbound frame version negotiation works:
    /// 1. Create a stream pair
    /// 2. Send one end to a thread, to act as the inbound receiver
    /// 3. Create an outbound negotiation and execute it on the stream
    /// 4. Verify that the agree on versions.
    #[test]
    fn basic_outbound_negotiation() {
        let (mut tx, mut rx) = stream::byte_stream_pair();

        let (done_tx, done_rx) = std::sync::mpsc::channel();
        let join_handle = thread::spawn(move || {
            let res = FrameNegotiation::inbound(FrameVersion::V1)
                .negotiate(&mut rx)
                .expect("Should have successfully negotiated");

            done_rx.recv().unwrap();

            res
        });

        let version = FrameNegotiation::outbound(FrameVersion::V1, FrameVersion::V1)
            .negotiate(&mut tx)
            .expect("Unable to negotiate a valid version");

        assert_eq!(FrameVersion::V1, version);

        done_tx.send(1u8).expect("unable to send stop signal");

        let remote_res = join_handle.join().expect("Unable to join thread");

        assert_eq!(FrameVersion::V1, remote_res);
    }

    /// Test that outbound frame version negotiation works:
    /// 1. Create a stream pair
    /// 2. Send one end to a thread, to act as the inbound receiver - this stream will return no
    ///    version supported.
    /// 3. Create an outbound negotiation and execute it on the stream.
    /// 4. Verify that negotiation returns an error.
    #[test]
    fn unsupported_range() {
        let (mut tx, mut rx) = stream::byte_stream_pair();

        let (done_tx, done_rx) = std::sync::mpsc::channel();
        let join_handle = thread::spawn(move || {
            rx.write_u16::<BigEndian>(0)
                .expect("Unable to write unsupported version");

            done_rx.recv().unwrap();
        });

        let res = FrameNegotiation::outbound(FrameVersion::V1, FrameVersion::V1).negotiate(&mut tx);

        done_tx.send(1u8).expect("Unable to send stop signal");

        join_handle.join().expect("Unable to join thread");

        match res {
            Err(FrameError::UnsupportedVersion) => (),
            res => {
                panic!("Unexpected result: {:?}", res);
            }
        }
    }

    /// Test that inbound frame version negotiation returns a error on UnexpectedEof
    /// 1. Create a stream pair
    /// 2. Send one end to a thread to act as the outbound end - this stream will be dropped
    ///    before sending any information.
    /// 3. Create an inbound negotiation and execute it on the stream.
    /// 4. Verify that negotiation returns an Handshake error.
    #[test]
    fn frame_negotation_eof() {
        let (mut tx, rx) = stream::byte_stream_pair();

        let (done_tx, done_rx) = std::sync::mpsc::channel();
        let join_handle = thread::spawn(move || {
            drop(rx);

            done_rx.recv().unwrap();
        });

        let res = FrameNegotiation::inbound(FrameVersion::V1).negotiate(&mut tx);

        done_tx.send(1u8).expect("Unable to send stop signal");

        join_handle.join().expect("Unable to join thread");

        match res {
            Err(FrameError::HandshakeFailure(_)) => (),
            res => {
                panic!("Unexpected result: {:?}", res);
            }
        }
    }

    /// Test that outbound frame version negotiation works:
    /// 1. Create a stream pair
    /// 2. Send one end to a thread, to act as the outbound end - this stream will send a range
    ///    that does not include V1.
    /// 3. Create an inbound negotiation and execute it on the stream.
    /// 4. Verify that negotiation returns an error.
    #[test]
    fn out_of_range() {
        let (mut tx, mut rx) = stream::byte_stream_pair();

        let (done_tx, done_rx) = std::sync::mpsc::channel();
        let join_handle = thread::spawn(move || {
            rx.write_u16::<BigEndian>(3)
                .expect("Unable to write min version");
            rx.write_u16::<BigEndian>(5)
                .expect("Unable to write min version");

            let res = rx
                .read_u16::<BigEndian>()
                .expect("Unable to read negotiated version");

            done_rx.recv().unwrap();

            res
        });

        let res = FrameNegotiation::inbound(FrameVersion::V1).negotiate(&mut tx);

        done_tx.send(1u8).expect("Unable to send stop signal");

        let remote_res = join_handle.join().expect("unable to join thread");

        match res {
            Err(FrameError::UnsupportedVersion) => (),
            res => panic!("Unexpected result: {:?}", res),
        }

        assert_eq!(0u16, remote_res);
    }

    /// Read a frame from a stream.  The stream will be constructed with a valid header and a short
    /// data payload. Frame::read should result in a valid frame, with the expected data.
    #[test]
    fn read_frame_v1() {
        let input = b"hello";
        let mut cursor = Cursor::new(vec![0; 128]);
        FrameHeader::v1(input.len() as u32)
            .write(&mut cursor)
            .expect("Unable to write header");

        cursor.write(&input[..]).expect("Unable to write data");

        cursor.set_position(0);

        let frame = Frame::read(&mut cursor).expect("Unable to read frame");

        assert_eq!(input.to_vec(), frame.data);
    }

    /// Write a frame to a stream and verify that an equivalent frame is read back from the stream.
    #[test]
    fn frame_round_trip() {
        let input = b"hello world";
        let frame_ref = FrameRef::new(FrameVersion::V1, input);

        let mut cursor = Cursor::new(vec![0, 128]);

        frame_ref.write(&mut cursor).expect("Unable to write data");

        cursor.set_position(0);

        let frame = Frame::read(&mut cursor).expect("Unable to read frame");

        assert_eq!(input.to_vec(), frame.data);
    }

    #[cfg(not(target_os = "unix"))]
    mod stream {
        use std::io::{Error as IoError, Read, Write};
        use std::sync::mpsc::{channel, Receiver, Sender};

        pub struct InProcByteStream {
            outbound: Sender<Vec<u8>>,
            inbound: Receiver<Vec<u8>>,
        }

        pub fn byte_stream_pair() -> (InProcByteStream, InProcByteStream) {
            let (left_tx, left_rx) = channel();
            let (right_tx, right_rx) = channel();

            (
                InProcByteStream {
                    outbound: right_tx,
                    inbound: left_rx,
                },
                InProcByteStream {
                    outbound: left_tx,
                    inbound: right_rx,
                },
            )
        }

        impl Read for InProcByteStream {
            fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError> {
                let bytes_received = self
                    .inbound
                    .recv()
                    .map_err(|e| IoError::new(std::io::ErrorKind::UnexpectedEof, e))?;

                buf.copy_from_slice(&bytes_received);

                Ok(bytes_received.len())
            }
        }

        impl Write for InProcByteStream {
            fn write(&mut self, buf: &[u8]) -> Result<usize, IoError> {
                let n = buf.len();

                self.outbound
                    .send(buf.to_vec())
                    .map_err(|e| IoError::new(std::io::ErrorKind::Interrupted, e))?;

                Ok(n)
            }

            fn flush(&mut self) -> Result<(), IoError> {
                Ok(())
            }
        }
    }

    #[cfg(target_os = "unix")]
    mod stream {
        use std::os::unix::net::UnixStream;

        pub struct InProcByteStream {
            inner: UnixStream,
        }

        pub fn byte_stream_pair() -> (InProcByteStream, InProcByteStream) {
            let (left, right) = UnixStream::pair().expect("Unable to create unix stream");

            (
                InProcByteStream { inner: left },
                InProcByteStream { inner: right },
            )
        }

        impl Read for InProcByteStream {
            fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError> {
                self.inner.read(buf)
            }
        }

        impl Write for InProcByteStream {
            fn write(&mut self, buf: &[u8]) -> Result<usize, IoError> {
                self.inner.write(buf)
            }
        }
    }
}