bitcoincash/consensus/
encode.rs

1// Written in 2014 by Andrew Poelstra <apoelstra@wpsoftware.net>
2// SPDX-License-Identifier: CC0-1.0
3
4//! Bitcoin consensus-encodable types.
5//!
6//! This is basically a replacement of the `Encodable` trait which does
7//! normalization of endianness etc., to ensure that the encoding matches
8//! the network consensus encoding.
9//!
10//! Essentially, anything that must go on the _disk_ or _network_ must be
11//! encoded using the `Encodable` trait, since this data must be the same for
12//! all systems. Any data going to the _user_ e.g., over JSONRPC, should use the
13//! ordinary `Encodable` trait. (This should also be the same across systems, of
14//! course, but has some critical differences from the network format e.g.,
15//! scripts come with an opcode decode, hashes are big-endian, numbers are
16//! typically big-endian decimals, etc.)
17//!
18
19use crate::prelude::*;
20
21use core::{fmt, mem, u32, convert::From};
22
23use crate::hashes::{sha256d, Hash, sha256};
24use crate::hash_types::{BlockHash, FilterHash, TxMerkleNode, FilterHeader};
25use crate::internal_macros::write_err;
26use crate::io::{self, Cursor, Read};
27
28use crate::util::endian;
29use crate::util::psbt;
30use crate::util::bip152::{ShortId, PrefilledTransaction};
31use crate::util::taproot::TapLeafHash;
32use crate::hashes::hex::ToHex;
33
34use crate::blockdata::transaction::{TxOut, Transaction, TxIn};
35#[cfg(feature = "std")]
36use crate::network::{message_blockdata::Inventory, address::{Address, AddrV2Message}};
37
38/// Encoding error
39#[derive(Debug)]
40#[non_exhaustive]
41pub enum Error {
42    /// And I/O error
43    Io(io::Error),
44    /// PSBT-related error
45    Psbt(psbt::Error),
46    /// Network magic was not expected
47    UnexpectedNetworkMagic {
48        /// The expected network magic
49        expected: u32,
50        /// The unexpected network magic
51        actual: u32,
52    },
53    /// Tried to allocate an oversized vector
54    OversizedVectorAllocation {
55        /// The capacity requested
56        requested: usize,
57        /// The maximum capacity
58        max: usize,
59    },
60    /// Checksum was invalid
61    InvalidChecksum {
62        /// The expected checksum
63        expected: [u8; 4],
64        /// The invalid checksum
65        actual: [u8; 4],
66    },
67    /// VarInt was encoded in a non-minimal way
68    NonMinimalVarInt,
69    /// Network magic was unknown
70    UnknownNetworkMagic(u32),
71    /// Parsing error
72    ParseFailed(&'static str),
73    /// Unsupported Segwit flag
74    UnsupportedSegwitFlag(u8),
75}
76
77impl fmt::Display for Error {
78    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79        match *self {
80            Error::Io(ref e) => write_err!(f, "IO error"; e),
81            Error::Psbt(ref e) => write_err!(f, "PSBT error"; e),
82            Error::UnexpectedNetworkMagic { expected: ref e, actual: ref a } => write!(f,
83                "unexpected network magic: expected {}, actual {}", e, a),
84            Error::OversizedVectorAllocation { requested: ref r, max: ref m } => write!(f,
85                "allocation of oversized vector: requested {}, maximum {}", r, m),
86            Error::InvalidChecksum { expected: ref e, actual: ref a } => write!(f,
87                "invalid checksum: expected {}, actual {}", e.to_hex(), a.to_hex()),
88            Error::NonMinimalVarInt => write!(f, "non-minimal varint"),
89            Error::UnknownNetworkMagic(ref m) => write!(f, "unknown network magic: {}", m),
90            Error::ParseFailed(ref s) => write!(f, "parse failed: {}", s),
91            Error::UnsupportedSegwitFlag(ref swflag) => write!(f,
92                "unsupported segwit version: {}", swflag),
93        }
94    }
95}
96
97#[cfg(feature = "std")]
98#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
99impl std::error::Error for Error {
100    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
101        use self::Error::*;
102
103        match self {
104            Io(e) => Some(e),
105            Psbt(e) => Some(e),
106            UnexpectedNetworkMagic { .. }
107            | OversizedVectorAllocation { .. }
108            | InvalidChecksum { .. }
109            | NonMinimalVarInt
110            | UnknownNetworkMagic(_)
111            | ParseFailed(_)
112            | UnsupportedSegwitFlag(_) => None,
113        }
114    }
115}
116
117#[doc(hidden)]
118impl From<io::Error> for Error {
119    fn from(error: io::Error) -> Self {
120        Error::Io(error)
121    }
122}
123
124#[doc(hidden)]
125impl From<psbt::Error> for Error {
126    fn from(e: psbt::Error) -> Error {
127        Error::Psbt(e)
128    }
129}
130
131/// Encode an object into a vector
132pub fn serialize<T: Encodable + ?Sized>(data: &T) -> Vec<u8> {
133    let mut encoder = Vec::new();
134    let len = data.consensus_encode(&mut encoder).expect("in-memory writers don't error");
135    debug_assert_eq!(len, encoder.len());
136    encoder
137}
138
139/// Encode an object into a hex-encoded string
140pub fn serialize_hex<T: Encodable + ?Sized>(data: &T) -> String {
141    serialize(data)[..].to_hex()
142}
143
144/// Deserialize an object from a vector, will error if said deserialization
145/// doesn't consume the entire vector.
146pub fn deserialize<T: Decodable>(data: &[u8]) -> Result<T, Error> {
147    let (rv, consumed) = deserialize_partial(data)?;
148
149    // Fail if data are not consumed entirely.
150    if consumed == data.len() {
151        Ok(rv)
152    } else {
153        Err(Error::ParseFailed("data not consumed entirely when explicitly deserializing"))
154    }
155}
156
157/// Deserialize an object from a vector, but will not report an error if said deserialization
158/// doesn't consume the entire vector.
159pub fn deserialize_partial<T: Decodable>(data: &[u8]) -> Result<(T, usize), Error> {
160    let mut decoder = Cursor::new(data);
161    let rv = Decodable::consensus_decode_from_finite_reader(&mut decoder)?;
162    let consumed = decoder.position() as usize;
163
164    Ok((rv, consumed))
165}
166
167
168/// Extensions of `Write` to encode data as per Bitcoin consensus
169pub trait WriteExt : io::Write {
170    /// Output a 64-bit uint
171    fn emit_u64(&mut self, v: u64) -> Result<(), io::Error>;
172    /// Output a 32-bit uint
173    fn emit_u32(&mut self, v: u32) -> Result<(), io::Error>;
174    /// Output a 16-bit uint
175    fn emit_u16(&mut self, v: u16) -> Result<(), io::Error>;
176    /// Output a 8-bit uint
177    fn emit_u8(&mut self, v: u8) -> Result<(), io::Error>;
178
179    /// Output a 64-bit int
180    fn emit_i64(&mut self, v: i64) -> Result<(), io::Error>;
181    /// Output a 32-bit int
182    fn emit_i32(&mut self, v: i32) -> Result<(), io::Error>;
183    /// Output a 16-bit int
184    fn emit_i16(&mut self, v: i16) -> Result<(), io::Error>;
185    /// Output a 8-bit int
186    fn emit_i8(&mut self, v: i8) -> Result<(), io::Error>;
187
188    /// Output a boolean
189    fn emit_bool(&mut self, v: bool) -> Result<(), io::Error>;
190
191    /// Output a byte slice
192    fn emit_slice(&mut self, v: &[u8]) -> Result<(), io::Error>;
193}
194
195/// Extensions of `Read` to decode data as per Bitcoin consensus
196pub trait ReadExt : io::Read {
197    /// Read a 64-bit uint
198    fn read_u64(&mut self) -> Result<u64, Error>;
199    /// Read a 32-bit uint
200    fn read_u32(&mut self) -> Result<u32, Error>;
201    /// Read a 16-bit uint
202    fn read_u16(&mut self) -> Result<u16, Error>;
203    /// Read a 8-bit uint
204    fn read_u8(&mut self) -> Result<u8, Error>;
205
206    /// Read a 64-bit int
207    fn read_i64(&mut self) -> Result<i64, Error>;
208    /// Read a 32-bit int
209    fn read_i32(&mut self) -> Result<i32, Error>;
210    /// Read a 16-bit int
211    fn read_i16(&mut self) -> Result<i16, Error>;
212    /// Read a 8-bit int
213    fn read_i8(&mut self) -> Result<i8, Error>;
214
215    /// Read a boolean
216    fn read_bool(&mut self) -> Result<bool, Error>;
217
218    /// Read a byte slice
219    fn read_slice(&mut self, slice: &mut [u8]) -> Result<(), Error>;
220}
221
222macro_rules! encoder_fn {
223    ($name:ident, $val_type:ty, $writefn:ident) => {
224        #[inline]
225        fn $name(&mut self, v: $val_type) -> Result<(), io::Error> {
226            self.write_all(&endian::$writefn(v))
227        }
228    }
229}
230
231macro_rules! decoder_fn {
232    ($name:ident, $val_type:ty, $readfn:ident, $byte_len: expr) => {
233        #[inline]
234        fn $name(&mut self) -> Result<$val_type, Error> {
235            $crate::internal_macros::const_assert!(::core::mem::size_of::<$val_type>() == $byte_len);
236            let mut val = [0; $byte_len];
237            self.read_exact(&mut val[..]).map_err(Error::Io)?;
238            Ok(endian::$readfn(&val))
239        }
240    }
241}
242
243impl<W: io::Write + ?Sized> WriteExt for W {
244    encoder_fn!(emit_u64, u64, u64_to_array_le);
245    encoder_fn!(emit_u32, u32, u32_to_array_le);
246    encoder_fn!(emit_u16, u16, u16_to_array_le);
247    encoder_fn!(emit_i64, i64, i64_to_array_le);
248    encoder_fn!(emit_i32, i32, i32_to_array_le);
249    encoder_fn!(emit_i16, i16, i16_to_array_le);
250
251    #[inline]
252    fn emit_i8(&mut self, v: i8) -> Result<(), io::Error> {
253        self.write_all(&[v as u8])
254    }
255    #[inline]
256    fn emit_u8(&mut self, v: u8) -> Result<(), io::Error> {
257        self.write_all(&[v])
258    }
259    #[inline]
260    fn emit_bool(&mut self, v: bool) -> Result<(), io::Error> {
261        self.write_all(&[v as u8])
262    }
263    #[inline]
264    fn emit_slice(&mut self, v: &[u8]) -> Result<(), io::Error> {
265        self.write_all(v)
266    }
267}
268
269impl<R: Read + ?Sized> ReadExt for R {
270    decoder_fn!(read_u64, u64, slice_to_u64_le, 8);
271    decoder_fn!(read_u32, u32, slice_to_u32_le, 4);
272    decoder_fn!(read_u16, u16, slice_to_u16_le, 2);
273    decoder_fn!(read_i64, i64, slice_to_i64_le, 8);
274    decoder_fn!(read_i32, i32, slice_to_i32_le, 4);
275    decoder_fn!(read_i16, i16, slice_to_i16_le, 2);
276
277    #[inline]
278    fn read_u8(&mut self) -> Result<u8, Error> {
279        let mut slice = [0u8; 1];
280        self.read_exact(&mut slice)?;
281        Ok(slice[0])
282    }
283    #[inline]
284    fn read_i8(&mut self) -> Result<i8, Error> {
285        let mut slice = [0u8; 1];
286        self.read_exact(&mut slice)?;
287        Ok(slice[0] as i8)
288    }
289    #[inline]
290    fn read_bool(&mut self) -> Result<bool, Error> {
291        ReadExt::read_i8(self).map(|bit| bit != 0)
292    }
293    #[inline]
294    fn read_slice(&mut self, slice: &mut [u8]) -> Result<(), Error> {
295        self.read_exact(slice).map_err(Error::Io)
296    }
297}
298
299/// Maximum size, in bytes, of a vector we are allowed to decode
300pub const MAX_VEC_SIZE: usize = 256_000_000;
301
302/// Data which can be encoded in a consensus-consistent way
303pub trait Encodable {
304    /// Encode an object with a well-defined format.
305    /// Returns the number of bytes written on success.
306    ///
307    /// The only errors returned are errors propagated from the writer.
308    fn consensus_encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error>;
309}
310
311/// Data which can be encoded in a consensus-consistent way
312pub trait Decodable: Sized {
313    /// Decode `Self` from a size-limited reader.
314    ///
315    /// Like `consensus_decode` but relies on the reader being
316    /// limited in the amount of data it returns, e.g. by
317    /// being wrapped in [`std::io::Take`].
318    ///
319    /// Failling to obide to this requirement might lead to
320    /// memory exhaustion caused by malicious inputs.
321    ///
322    /// Users should default to `consensus_decode`, but
323    /// when data to be decoded is already in a byte vector
324    /// of a limited size, calling this function directly
325    /// might be marginally faster (due to avoiding
326    /// extra checks).
327    ///
328    /// ### Rules for trait implementations
329    ///
330    /// * Simple types that that have a fixed size (own and member fields),
331    ///   don't have to overwrite this method, or be concern with it.
332    /// * Types that deserialize using externally provided length
333    ///   should implement it:
334    ///   * Make `consensus_decode` forward to `consensus_decode_bytes_from_finite_reader`
335    ///     with the reader wrapped by `Take`. Failure to do so, without other
336    ///     forms of memory exhaustion protection might lead to resource exhaustion
337    ///     vulnerability.
338    ///   * Put a max cap on things like `Vec::with_capacity` to avoid oversized
339    ///     allocations, and rely on the reader running out of data, and collections
340    ///     reallocating on a legitimately oversized input data, instead of trying
341    ///     to enforce arbitrary length limits.
342    /// * Types that contain other types that implement custom `consensus_decode_from_finite_reader`,
343    ///   should also implement it applying same rules, and in addition make sure to call
344    ///   `consensus_decode_from_finite_reader` on all members, to avoid creating redundant
345    ///   `Take` wrappers. Failure to do so might result only in a tiny performance hit.
346    #[inline]
347    fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, Error> {
348        // This method is always strictly less general than, `consensus_decode`,
349        // so it's safe and make sense to default to just calling it.
350        // This way most types, that don't care about protecting against
351        // resource exhaustion due to malicious input, can just ignore it.
352        Self::consensus_decode(reader)
353    }
354
355    /// Decode an object with a well-defined format.
356    ///
357    /// This is the method that should be implemented for a typical, fixed sized type
358    /// implementing this trait. Default implementation is wrapping the reader
359    /// in [`crate::io::Take`] to limit the input size to [`MAX_VEC_SIZE`], and forwards the call to
360    /// [`Self::consensus_decode_from_finite_reader`], which is convenient
361    /// for types that override [`Self::consensus_decode_from_finite_reader`]
362    /// instead.
363    #[inline]
364    fn consensus_decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, Error> {
365        Self::consensus_decode_from_finite_reader(reader.take(MAX_VEC_SIZE as u64).by_ref())
366    }
367}
368
369/// A variable-length unsigned integer
370#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
371pub struct VarInt(pub u64);
372
373/// Data which must be preceded by a 4-byte checksum
374#[derive(PartialEq, Eq, Clone, Debug)]
375pub struct CheckedData(pub Vec<u8>);
376
377// Primitive types
378macro_rules! impl_int_encodable {
379    ($ty:ident, $meth_dec:ident, $meth_enc:ident) => {
380        impl Decodable for $ty {
381            #[inline]
382            fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
383                ReadExt::$meth_dec(r)
384            }
385        }
386        impl Encodable for $ty {
387            #[inline]
388            fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
389                w.$meth_enc(*self)?;
390                Ok(mem::size_of::<$ty>())
391            }
392        }
393    }
394}
395
396impl_int_encodable!(u8,  read_u8,  emit_u8);
397impl_int_encodable!(u16, read_u16, emit_u16);
398impl_int_encodable!(u32, read_u32, emit_u32);
399impl_int_encodable!(u64, read_u64, emit_u64);
400impl_int_encodable!(i8,  read_i8,  emit_i8);
401impl_int_encodable!(i16, read_i16, emit_i16);
402impl_int_encodable!(i32, read_i32, emit_i32);
403impl_int_encodable!(i64, read_i64, emit_i64);
404
405#[allow(clippy::len_without_is_empty)] // VarInt has on concept of 'is_empty'.
406impl VarInt {
407    /// Gets the length of this VarInt when encoded.
408    /// Returns 1 for 0..=0xFC, 3 for 0xFD..=(2^16-1), 5 for 0x10000..=(2^32-1),
409    /// and 9 otherwise.
410    #[inline]
411    pub fn len(&self) -> usize {
412        match self.0 {
413            0..=0xFC             => { 1 }
414            0xFD..=0xFFFF        => { 3 }
415            0x10000..=0xFFFFFFFF => { 5 }
416            _                    => { 9 }
417        }
418    }
419}
420
421impl Encodable for VarInt {
422    #[inline]
423    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
424        match self.0 {
425            0..=0xFC => {
426                (self.0 as u8).consensus_encode(w)?;
427                Ok(1)
428            },
429            0xFD..=0xFFFF => {
430                w.emit_u8(0xFD)?;
431                (self.0 as u16).consensus_encode(w)?;
432                Ok(3)
433            },
434            0x10000..=0xFFFFFFFF => {
435                w.emit_u8(0xFE)?;
436                (self.0 as u32).consensus_encode(w)?;
437                Ok(5)
438            },
439            _ => {
440                w.emit_u8(0xFF)?;
441                (self.0 as u64).consensus_encode(w)?;
442                Ok(9)
443            },
444        }
445    }
446}
447
448impl Decodable for VarInt {
449    #[inline]
450    fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
451        let n = ReadExt::read_u8(r)?;
452        match n {
453            0xFF => {
454                let x = ReadExt::read_u64(r)?;
455                if x < 0x100000000 {
456                    Err(self::Error::NonMinimalVarInt)
457                } else {
458                    Ok(VarInt(x))
459                }
460            }
461            0xFE => {
462                let x = ReadExt::read_u32(r)?;
463                if x < 0x10000 {
464                    Err(self::Error::NonMinimalVarInt)
465                } else {
466                    Ok(VarInt(x as u64))
467                }
468            }
469            0xFD => {
470                let x = ReadExt::read_u16(r)?;
471                if x < 0xFD {
472                    Err(self::Error::NonMinimalVarInt)
473                } else {
474                    Ok(VarInt(x as u64))
475                }
476            }
477            n => Ok(VarInt(n as u64))
478        }
479    }
480}
481
482// Booleans
483impl Encodable for bool {
484    #[inline]
485    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
486        w.emit_bool(*self)?;
487        Ok(1)
488    }
489}
490
491impl Decodable for bool {
492    #[inline]
493    fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<bool, Error> {
494        ReadExt::read_bool(r)
495    }
496}
497
498// Strings
499impl Encodable for String {
500    #[inline]
501    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
502        let b = self.as_bytes();
503        let vi_len = VarInt(b.len() as u64).consensus_encode(w)?;
504        w.emit_slice(b)?;
505        Ok(vi_len + b.len())
506    }
507}
508
509impl Decodable for String {
510    #[inline]
511    fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<String, Error> {
512        String::from_utf8(Decodable::consensus_decode(r)?)
513            .map_err(|_| self::Error::ParseFailed("String was not valid UTF8"))
514    }
515}
516
517// Cow<'static, str>
518impl Encodable for Cow<'static, str> {
519    #[inline]
520    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
521        let b = self.as_bytes();
522        let vi_len = VarInt(b.len() as u64).consensus_encode(w)?;
523        w.emit_slice(b)?;
524        Ok(vi_len + b.len())
525    }
526}
527
528impl Decodable for Cow<'static, str> {
529    #[inline]
530    fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Cow<'static, str>, Error> {
531        String::from_utf8(Decodable::consensus_decode(r)?)
532            .map_err(|_| self::Error::ParseFailed("String was not valid UTF8"))
533            .map(Cow::Owned)
534    }
535}
536
537
538// Arrays
539macro_rules! impl_array {
540    ( $size:literal ) => {
541        impl Encodable for [u8; $size] {
542            #[inline]
543            fn consensus_encode<W: WriteExt + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
544                w.emit_slice(&self[..])?;
545                Ok(self.len())
546            }
547        }
548
549        impl Decodable for [u8; $size] {
550            #[inline]
551            fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
552                let mut ret = [0; $size];
553                r.read_slice(&mut ret)?;
554                Ok(ret)
555            }
556        }
557    };
558}
559
560impl_array!(2);
561impl_array!(4);
562impl_array!(6);
563impl_array!(8);
564impl_array!(10);
565impl_array!(12);
566impl_array!(16);
567impl_array!(32);
568impl_array!(33);
569
570impl Decodable for [u16; 8] {
571    #[inline]
572    fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
573        let mut res = [0; 8];
574        for item in &mut res {
575            *item = Decodable::consensus_decode(r)?;
576        }
577        Ok(res)
578    }
579}
580
581impl Encodable for [u16; 8] {
582    #[inline]
583    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
584        for c in self.iter() { c.consensus_encode(w)?; }
585        Ok(16)
586    }
587}
588
589// Vectors
590macro_rules! impl_vec {
591    ($type: ty) => {
592        impl Encodable for Vec<$type> {
593            #[inline]
594            fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
595                let mut len = 0;
596                len += VarInt(self.len() as u64).consensus_encode(w)?;
597                for c in self.iter() {
598                    len += c.consensus_encode(w)?;
599                }
600                Ok(len)
601            }
602        }
603
604        impl Decodable for Vec<$type> {
605            #[inline]
606            fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
607                let len = VarInt::consensus_decode_from_finite_reader(r)?.0;
608                // Do not allocate upfront more items than if the sequnce of type
609                // occupied roughly quarter a block. This should never be the case
610                // for normal data, but even if that's not true - `push` will just
611                // reallocate.
612                // Note: OOM protection relies on reader eventually running out of
613                // data to feed us.
614                let max_capacity = MAX_VEC_SIZE / 4 / mem::size_of::<$type>();
615                let mut ret = Vec::with_capacity(core::cmp::min(len as usize, max_capacity));
616                for _ in 0..len {
617                    ret.push(Decodable::consensus_decode_from_finite_reader(r)?);
618                }
619                Ok(ret)
620            }
621        }
622    }
623}
624impl_vec!(BlockHash);
625impl_vec!(FilterHash);
626impl_vec!(FilterHeader);
627impl_vec!(TxMerkleNode);
628impl_vec!(Transaction);
629impl_vec!(TxOut);
630impl_vec!(TxIn);
631impl_vec!(Vec<u8>);
632impl_vec!(u64);
633impl_vec!(TapLeafHash);
634impl_vec!(VarInt);
635impl_vec!(ShortId);
636impl_vec!(PrefilledTransaction);
637
638#[cfg(feature = "std")] impl_vec!(Inventory);
639#[cfg(feature = "std")] impl_vec!((u32, Address));
640#[cfg(feature = "std")] impl_vec!(AddrV2Message);
641
642pub(crate) fn consensus_encode_with_size<S: io::Write>(data: &[u8], mut s: S) -> Result<usize, io::Error> {
643    let vi_len = VarInt(data.len() as u64).consensus_encode(&mut s)?;
644    s.emit_slice(data)?;
645    Ok(vi_len + data.len())
646}
647
648
649struct ReadBytesFromFiniteReaderOpts {
650    len: usize,
651    chunk_size: usize,
652}
653
654/// Read `opts.len` bytes from reader, where `opts.len` could potentially be malicious
655///
656/// This function relies on reader being bound in amount of data
657/// it returns for OOM protection. See [`Decodable::consensus_decode_from_finite_reader`].
658#[inline]
659fn read_bytes_from_finite_reader<D: io::Read>(mut d: D, mut opts: ReadBytesFromFiniteReaderOpts) -> Result<Vec<u8>, Error> {
660    let mut ret = vec![];
661
662    assert_ne!(opts.chunk_size, 0);
663
664    while opts.len > 0 {
665        let chunk_start = ret.len();
666        let chunk_size = core::cmp::min(opts.len, opts.chunk_size);
667        let chunk_end = chunk_start + chunk_size;
668        ret.resize(chunk_end, 0u8);
669        d.read_slice(&mut ret[chunk_start..chunk_end])?;
670        opts.len -= chunk_size;
671    }
672
673    Ok(ret)
674}
675
676impl Encodable for Vec<u8> {
677    #[inline]
678    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
679        consensus_encode_with_size(self, w)
680    }
681}
682
683impl Decodable for Vec<u8> {
684    #[inline]
685    fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
686        let len = VarInt::consensus_decode(r)?.0 as usize;
687        // most real-world vec of bytes data, wouldn't be larger than 128KiB
688        read_bytes_from_finite_reader(r, ReadBytesFromFiniteReaderOpts { len, chunk_size: 128 * 1024 })
689    }
690}
691
692impl Encodable for Box<[u8]> {
693    #[inline]
694    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
695        consensus_encode_with_size(self, w)
696    }
697}
698
699impl Decodable for Box<[u8]> {
700    #[inline]
701    fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
702        <Vec<u8>>::consensus_decode_from_finite_reader(r).map(From::from)
703    }
704}
705
706
707/// Do a double-SHA256 on some data and return the first 4 bytes
708fn sha2_checksum(data: &[u8]) -> [u8; 4] {
709    let checksum = <sha256d::Hash as Hash>::hash(data);
710    [checksum[0], checksum[1], checksum[2], checksum[3]]
711}
712
713// Checked data
714impl Encodable for CheckedData {
715    #[inline]
716    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
717        (self.0.len() as u32).consensus_encode(w)?;
718        sha2_checksum(&self.0).consensus_encode(w)?;
719        w.emit_slice(&self.0)?;
720        Ok(8 + self.0.len())
721    }
722}
723
724impl Decodable for CheckedData {
725    #[inline]
726    fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
727        let len = u32::consensus_decode_from_finite_reader(r)? as usize;
728
729        let checksum = <[u8; 4]>::consensus_decode_from_finite_reader(r)?;
730        let ret = read_bytes_from_finite_reader(r, ReadBytesFromFiniteReaderOpts { len, chunk_size: MAX_VEC_SIZE })?;
731        let expected_checksum = sha2_checksum(&ret);
732        if expected_checksum != checksum {
733            Err(self::Error::InvalidChecksum {
734                expected: expected_checksum,
735                actual: checksum,
736            })
737        } else {
738            Ok(CheckedData(ret))
739        }
740    }
741}
742
743// References
744impl<'a, T: Encodable> Encodable for &'a T {
745    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
746        (**self).consensus_encode(w)
747    }
748}
749
750impl<'a, T: Encodable> Encodable for &'a mut T {
751    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
752        (**self).consensus_encode(w)
753    }
754}
755
756impl<T: Encodable> Encodable for rc::Rc<T> {
757    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
758        (**self).consensus_encode(w)
759    }
760}
761
762impl<T: Encodable> Encodable for sync::Arc<T> {
763    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
764        (**self).consensus_encode(w)
765    }
766}
767
768// Tuples
769macro_rules! tuple_encode {
770    ($($x:ident),*) => {
771        impl <$($x: Encodable),*> Encodable for ($($x),*) {
772            #[inline]
773            #[allow(non_snake_case)]
774            fn consensus_encode<W: io::Write + ?Sized>(
775                &self,
776                w: &mut W,
777            ) -> Result<usize, io::Error> {
778                let &($(ref $x),*) = self;
779                let mut len = 0;
780                $(len += $x.consensus_encode(w)?;)*
781                Ok(len)
782            }
783        }
784
785        impl<$($x: Decodable),*> Decodable for ($($x),*) {
786            #[inline]
787            #[allow(non_snake_case)]
788            fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
789                Ok(($({let $x = Decodable::consensus_decode(r)?; $x }),*))
790            }
791        }
792    };
793}
794
795tuple_encode!(T0, T1);
796tuple_encode!(T0, T1, T2);
797tuple_encode!(T0, T1, T2, T3);
798tuple_encode!(T0, T1, T2, T3, T4);
799tuple_encode!(T0, T1, T2, T3, T4, T5);
800tuple_encode!(T0, T1, T2, T3, T4, T5, T6);
801tuple_encode!(T0, T1, T2, T3, T4, T5, T6, T7);
802
803impl Encodable for sha256d::Hash {
804    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
805        self.into_inner().consensus_encode(w)
806    }
807}
808
809impl Decodable for sha256d::Hash {
810    fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
811        Ok(Self::from_inner(<<Self as Hash>::Inner>::consensus_decode(r)?))
812    }
813}
814
815impl Encodable for sha256::Hash {
816    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
817        self.into_inner().consensus_encode(w)
818    }
819}
820
821impl Decodable for sha256::Hash {
822    fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
823        Ok(Self::from_inner(<<Self as Hash>::Inner>::consensus_decode(r)?))
824    }
825}
826
827impl Encodable for TapLeafHash {
828    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
829        self.into_inner().consensus_encode(w)
830    }
831}
832
833impl Decodable for TapLeafHash {
834    fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
835        Ok(Self::from_inner(<<Self as Hash>::Inner>::consensus_decode(r)?))
836    }
837}
838
839// Tests
840#[cfg(test)]
841mod tests {
842    use super::*;
843    use core::{mem::{self, discriminant}, fmt};
844    use super::{deserialize, serialize, Error, CheckedData, VarInt};
845    use super::{Transaction, BlockHash, FilterHash, TxMerkleNode, TxOut, TxIn};
846    use crate::consensus::{Encodable, deserialize_partial, Decodable};
847    use crate::util::endian::{u64_to_array_le, u32_to_array_le, u16_to_array_le};
848    use secp256k1::rand::{thread_rng, Rng};
849    #[cfg(feature = "std")]
850    use crate::network::{Address, message_blockdata::Inventory};
851
852    #[test]
853    fn serialize_int_test() {
854        // bool
855        assert_eq!(serialize(&false), vec![0u8]);
856        assert_eq!(serialize(&true), vec![1u8]);
857        // u8
858        assert_eq!(serialize(&1u8), vec![1u8]);
859        assert_eq!(serialize(&0u8), vec![0u8]);
860        assert_eq!(serialize(&255u8), vec![255u8]);
861        // u16
862        assert_eq!(serialize(&1u16), vec![1u8, 0]);
863        assert_eq!(serialize(&256u16), vec![0u8, 1]);
864        assert_eq!(serialize(&5000u16), vec![136u8, 19]);
865        // u32
866        assert_eq!(serialize(&1u32), vec![1u8, 0, 0, 0]);
867        assert_eq!(serialize(&256u32), vec![0u8, 1, 0, 0]);
868        assert_eq!(serialize(&5000u32), vec![136u8, 19, 0, 0]);
869        assert_eq!(serialize(&500000u32), vec![32u8, 161, 7, 0]);
870        assert_eq!(serialize(&168430090u32), vec![10u8, 10, 10, 10]);
871        // i32
872        assert_eq!(serialize(&-1i32), vec![255u8, 255, 255, 255]);
873        assert_eq!(serialize(&-256i32), vec![0u8, 255, 255, 255]);
874        assert_eq!(serialize(&-5000i32), vec![120u8, 236, 255, 255]);
875        assert_eq!(serialize(&-500000i32), vec![224u8, 94, 248, 255]);
876        assert_eq!(serialize(&-168430090i32), vec![246u8, 245, 245, 245]);
877        assert_eq!(serialize(&1i32), vec![1u8, 0, 0, 0]);
878        assert_eq!(serialize(&256i32), vec![0u8, 1, 0, 0]);
879        assert_eq!(serialize(&5000i32), vec![136u8, 19, 0, 0]);
880        assert_eq!(serialize(&500000i32), vec![32u8, 161, 7, 0]);
881        assert_eq!(serialize(&168430090i32), vec![10u8, 10, 10, 10]);
882        // u64
883        assert_eq!(serialize(&1u64), vec![1u8, 0, 0, 0, 0, 0, 0, 0]);
884        assert_eq!(serialize(&256u64), vec![0u8, 1, 0, 0, 0, 0, 0, 0]);
885        assert_eq!(serialize(&5000u64), vec![136u8, 19, 0, 0, 0, 0, 0, 0]);
886        assert_eq!(serialize(&500000u64), vec![32u8, 161, 7, 0, 0, 0, 0, 0]);
887        assert_eq!(serialize(&723401728380766730u64), vec![10u8, 10, 10, 10, 10, 10, 10, 10]);
888        // i64
889        assert_eq!(serialize(&-1i64), vec![255u8, 255, 255, 255, 255, 255, 255, 255]);
890        assert_eq!(serialize(&-256i64), vec![0u8, 255, 255, 255, 255, 255, 255, 255]);
891        assert_eq!(serialize(&-5000i64), vec![120u8, 236, 255, 255, 255, 255, 255, 255]);
892        assert_eq!(serialize(&-500000i64), vec![224u8, 94, 248, 255, 255, 255, 255, 255]);
893        assert_eq!(serialize(&-723401728380766730i64), vec![246u8, 245, 245, 245, 245, 245, 245, 245]);
894        assert_eq!(serialize(&1i64), vec![1u8, 0, 0, 0, 0, 0, 0, 0]);
895        assert_eq!(serialize(&256i64), vec![0u8, 1, 0, 0, 0, 0, 0, 0]);
896        assert_eq!(serialize(&5000i64), vec![136u8, 19, 0, 0, 0, 0, 0, 0]);
897        assert_eq!(serialize(&500000i64), vec![32u8, 161, 7, 0, 0, 0, 0, 0]);
898        assert_eq!(serialize(&723401728380766730i64), vec![10u8, 10, 10, 10, 10, 10, 10, 10]);
899    }
900
901    #[test]
902    fn serialize_varint_test() {
903        assert_eq!(serialize(&VarInt(10)), vec![10u8]);
904        assert_eq!(serialize(&VarInt(0xFC)), vec![0xFCu8]);
905        assert_eq!(serialize(&VarInt(0xFD)), vec![0xFDu8, 0xFD, 0]);
906        assert_eq!(serialize(&VarInt(0xFFF)), vec![0xFDu8, 0xFF, 0xF]);
907        assert_eq!(serialize(&VarInt(0xF0F0F0F)), vec![0xFEu8, 0xF, 0xF, 0xF, 0xF]);
908        assert_eq!(serialize(&VarInt(0xF0F0F0F0F0E0)), vec![0xFFu8, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0, 0]);
909        assert_eq!(test_varint_encode(0xFF, &u64_to_array_le(0x100000000)).unwrap(), VarInt(0x100000000));
910        assert_eq!(test_varint_encode(0xFE, &u64_to_array_le(0x10000)).unwrap(), VarInt(0x10000));
911        assert_eq!(test_varint_encode(0xFD, &u64_to_array_le(0xFD)).unwrap(), VarInt(0xFD));
912
913        // Test that length calc is working correctly
914        test_varint_len(VarInt(0), 1);
915        test_varint_len(VarInt(0xFC), 1);
916        test_varint_len(VarInt(0xFD), 3);
917        test_varint_len(VarInt(0xFFFF), 3);
918        test_varint_len(VarInt(0x10000), 5);
919        test_varint_len(VarInt(0xFFFFFFFF), 5);
920        test_varint_len(VarInt(0xFFFFFFFF+1), 9);
921        test_varint_len(VarInt(u64::max_value()), 9);
922    }
923
924    fn test_varint_len(varint: VarInt, expected: usize) {
925        let mut encoder = vec![];
926        assert_eq!(varint.consensus_encode(&mut encoder).unwrap(), expected);
927        assert_eq!(varint.len(), expected);
928    }
929
930    fn test_varint_encode(n: u8, x: &[u8]) -> Result<VarInt, Error> {
931        let mut input = [0u8; 9];
932        input[0] = n;
933        input[1..x.len()+1].copy_from_slice(x);
934        deserialize_partial::<VarInt>(&input).map(|t|t.0)
935    }
936
937    #[test]
938    fn deserialize_nonminimal_vec() {
939        // Check the edges for variant int
940        assert_eq!(discriminant(&test_varint_encode(0xFF, &u64_to_array_le(0x100000000-1)).unwrap_err()),
941                   discriminant(&Error::NonMinimalVarInt));
942        assert_eq!(discriminant(&test_varint_encode(0xFE, &u32_to_array_le(0x10000-1)).unwrap_err()),
943                   discriminant(&Error::NonMinimalVarInt));
944        assert_eq!(discriminant(&test_varint_encode(0xFD, &u16_to_array_le(0xFD-1)).unwrap_err()),
945                   discriminant(&Error::NonMinimalVarInt));
946
947        assert_eq!(discriminant(&deserialize::<Vec<u8>>(&[0xfd, 0x00, 0x00]).unwrap_err()),
948                   discriminant(&Error::NonMinimalVarInt));
949        assert_eq!(discriminant(&deserialize::<Vec<u8>>(&[0xfd, 0xfc, 0x00]).unwrap_err()),
950                   discriminant(&Error::NonMinimalVarInt));
951        assert_eq!(discriminant(&deserialize::<Vec<u8>>(&[0xfd, 0xfc, 0x00]).unwrap_err()),
952                   discriminant(&Error::NonMinimalVarInt));
953        assert_eq!(discriminant(&deserialize::<Vec<u8>>(&[0xfe, 0xff, 0x00, 0x00, 0x00]).unwrap_err()),
954                   discriminant(&Error::NonMinimalVarInt));
955        assert_eq!(discriminant(&deserialize::<Vec<u8>>(&[0xfe, 0xff, 0xff, 0x00, 0x00]).unwrap_err()),
956                   discriminant(&Error::NonMinimalVarInt));
957        assert_eq!(discriminant(&deserialize::<Vec<u8>>(&[0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]).unwrap_err()),
958                   discriminant(&Error::NonMinimalVarInt));
959        assert_eq!(discriminant(&deserialize::<Vec<u8>>(&[0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00]).unwrap_err()),
960                   discriminant(&Error::NonMinimalVarInt));
961
962
963        let mut vec_256 = vec![0; 259];
964        vec_256[0] = 0xfd;
965        vec_256[1] = 0x00;
966        vec_256[2] = 0x01;
967        assert!(deserialize::<Vec<u8>>(&vec_256).is_ok());
968
969        let mut vec_253 = vec![0; 256];
970        vec_253[0] = 0xfd;
971        vec_253[1] = 0xfd;
972        vec_253[2] = 0x00;
973        assert!(deserialize::<Vec<u8>>(&vec_253).is_ok());
974    }
975
976    #[test]
977    fn serialize_checkeddata_test() {
978        let cd = CheckedData(vec![1u8, 2, 3, 4, 5]);
979        assert_eq!(serialize(&cd), vec![5, 0, 0, 0, 162, 107, 175, 90, 1, 2, 3, 4, 5]);
980    }
981
982    #[test]
983    fn serialize_vector_test() {
984        assert_eq!(serialize(&vec![1u8, 2, 3]), vec![3u8, 1, 2, 3]);
985        // TODO: test vectors of more interesting objects
986    }
987
988    #[test]
989    fn serialize_strbuf_test() {
990        assert_eq!(serialize(&"Andrew".to_string()), vec![6u8, 0x41, 0x6e, 0x64, 0x72, 0x65, 0x77]);
991    }
992
993    #[test]
994    fn deserialize_int_test() {
995        // bool
996        assert!((deserialize(&[58u8, 0]) as Result<bool, _>).is_err());
997        assert_eq!(deserialize(&[58u8]).ok(), Some(true));
998        assert_eq!(deserialize(&[1u8]).ok(), Some(true));
999        assert_eq!(deserialize(&[0u8]).ok(), Some(false));
1000        assert!((deserialize(&[0u8, 1]) as Result<bool, _>).is_err());
1001
1002        // u8
1003        assert_eq!(deserialize(&[58u8]).ok(), Some(58u8));
1004
1005        // u16
1006        assert_eq!(deserialize(&[0x01u8, 0x02]).ok(), Some(0x0201u16));
1007        assert_eq!(deserialize(&[0xABu8, 0xCD]).ok(), Some(0xCDABu16));
1008        assert_eq!(deserialize(&[0xA0u8, 0x0D]).ok(), Some(0xDA0u16));
1009        let failure16: Result<u16, _> = deserialize(&[1u8]);
1010        assert!(failure16.is_err());
1011
1012        // u32
1013        assert_eq!(deserialize(&[0xABu8, 0xCD, 0, 0]).ok(), Some(0xCDABu32));
1014        assert_eq!(deserialize(&[0xA0u8, 0x0D, 0xAB, 0xCD]).ok(), Some(0xCDAB0DA0u32));
1015        let failure32: Result<u32, _> = deserialize(&[1u8, 2, 3]);
1016        assert!(failure32.is_err());
1017        // TODO: test negative numbers
1018        assert_eq!(deserialize(&[0xABu8, 0xCD, 0, 0]).ok(), Some(0xCDABi32));
1019        assert_eq!(deserialize(&[0xA0u8, 0x0D, 0xAB, 0x2D]).ok(), Some(0x2DAB0DA0i32));
1020        let failurei32: Result<i32, _> = deserialize(&[1u8, 2, 3]);
1021        assert!(failurei32.is_err());
1022
1023        // u64
1024        assert_eq!(deserialize(&[0xABu8, 0xCD, 0, 0, 0, 0, 0, 0]).ok(), Some(0xCDABu64));
1025        assert_eq!(deserialize(&[0xA0u8, 0x0D, 0xAB, 0xCD, 0x99, 0, 0, 0x99]).ok(), Some(0x99000099CDAB0DA0u64));
1026        let failure64: Result<u64, _> = deserialize(&[1u8, 2, 3, 4, 5, 6, 7]);
1027        assert!(failure64.is_err());
1028        // TODO: test negative numbers
1029        assert_eq!(deserialize(&[0xABu8, 0xCD, 0, 0, 0, 0, 0, 0]).ok(), Some(0xCDABi64));
1030        assert_eq!(deserialize(&[0xA0u8, 0x0D, 0xAB, 0xCD, 0x99, 0, 0, 0x99]).ok(), Some(-0x66ffff663254f260i64));
1031        let failurei64: Result<i64, _> = deserialize(&[1u8, 2, 3, 4, 5, 6, 7]);
1032        assert!(failurei64.is_err());
1033    }
1034
1035    #[test]
1036    fn deserialize_vec_test() {
1037        assert_eq!(deserialize(&[3u8, 2, 3, 4]).ok(), Some(vec![2u8, 3, 4]));
1038        assert!((deserialize(&[4u8, 2, 3, 4, 5, 6]) as Result<Vec<u8>, _>).is_err());
1039        // found by cargo fuzz
1040        assert!(deserialize::<Vec<u64>>(&[0xff,0xff,0xff,0xff,0x6b,0x6b,0x6b,0x6b,0x6b,0x6b,0x6b,0x6b,0x6b,0x6b,0x6b,0x6b,0xa,0xa,0x3a]).is_err());
1041
1042        let rand_io_err = Error::Io(io::Error::new(io::ErrorKind::Other, ""));
1043
1044        // Check serialization that `if len > MAX_VEC_SIZE {return err}` isn't inclusive,
1045        // by making sure it fails with IO Error and not an `OversizedVectorAllocation` Error.
1046        let err = deserialize::<CheckedData>(&serialize(&(super::MAX_VEC_SIZE as u32))).unwrap_err();
1047        assert_eq!(discriminant(&err), discriminant(&rand_io_err));
1048
1049        test_len_is_max_vec::<u8>();
1050        test_len_is_max_vec::<BlockHash>();
1051        test_len_is_max_vec::<FilterHash>();
1052        test_len_is_max_vec::<TxMerkleNode>();
1053        test_len_is_max_vec::<Transaction>();
1054        test_len_is_max_vec::<TxOut>();
1055        test_len_is_max_vec::<TxIn>();
1056        test_len_is_max_vec::<Vec<u8>>();
1057        test_len_is_max_vec::<u64>();
1058        #[cfg(feature = "std")]
1059        test_len_is_max_vec::<(u32, Address)>();
1060        #[cfg(feature = "std")]
1061        test_len_is_max_vec::<Inventory>();
1062    }
1063
1064    fn test_len_is_max_vec<T>() where Vec<T>: Decodable, T: fmt::Debug {
1065        let rand_io_err = Error::Io(io::Error::new(io::ErrorKind::Other, ""));
1066        let varint = VarInt((super::MAX_VEC_SIZE / mem::size_of::<T>()) as u64);
1067        let err = deserialize::<Vec<T>>(&serialize(&varint)).unwrap_err();
1068        assert_eq!(discriminant(&err), discriminant(&rand_io_err));
1069    }
1070
1071    #[test]
1072    fn deserialize_strbuf_test() {
1073        assert_eq!(deserialize(&[6u8, 0x41, 0x6e, 0x64, 0x72, 0x65, 0x77]).ok(), Some("Andrew".to_string()));
1074        assert_eq!(
1075            deserialize(&[6u8, 0x41, 0x6e, 0x64, 0x72, 0x65, 0x77]).ok(),
1076            Some(Cow::Borrowed("Andrew"))
1077        );
1078    }
1079
1080    #[test]
1081    fn deserialize_checkeddata_test() {
1082        let cd: Result<CheckedData, _> = deserialize(&[5u8, 0, 0, 0, 162, 107, 175, 90, 1, 2, 3, 4, 5]);
1083        assert_eq!(cd.ok(), Some(CheckedData(vec![1u8, 2, 3, 4, 5])));
1084    }
1085
1086    #[test]
1087    fn serialization_round_trips() {
1088        macro_rules! round_trip {
1089            ($($val_type:ty),*) => {
1090                $(
1091                    let r: $val_type = thread_rng().gen();
1092                    assert_eq!(deserialize::<$val_type>(&serialize(&r)).unwrap(), r);
1093                )*
1094            };
1095        }
1096        macro_rules! round_trip_bytes {
1097            ($(($val_type:ty, $data:expr)),*) => {
1098                $(
1099                    thread_rng().fill(&mut $data[..]);
1100                    assert_eq!(deserialize::<$val_type>(&serialize(&$data)).unwrap()[..], $data[..]);
1101                )*
1102            };
1103        }
1104
1105        let mut data = Vec::with_capacity(256);
1106        let mut data64 = Vec::with_capacity(256);
1107        for _ in 0..10 {
1108            round_trip!{bool, i8, u8, i16, u16, i32, u32, i64, u64,
1109            (bool, i8, u16, i32), (u64, i64, u32, i32, u16, i16), (i8, u8, i16, u16, i32, u32, i64, u64),
1110            [u8; 2], [u8; 4], [u8; 8], [u8; 12], [u8; 16], [u8; 32]};
1111
1112            data.clear();
1113            data64.clear();
1114            let len = thread_rng().gen_range(1..256);
1115            data.resize(len, 0u8);
1116            data64.resize(len, 0u64);
1117            let mut arr33 = [0u8; 33];
1118            let mut arr16 = [0u16; 8];
1119            round_trip_bytes!{(Vec<u8>, data), ([u8; 33], arr33), ([u16; 8], arr16), (Vec<u64>, data64)};
1120
1121
1122        }
1123    }
1124
1125    #[test]
1126    fn test_read_bytes_from_finite_reader() {
1127        let data : Vec<u8> = (0..10).collect();
1128
1129        for chunk_size in 1..20 {
1130            assert_eq!(
1131                read_bytes_from_finite_reader(
1132                    io::Cursor::new(&data),
1133                    ReadBytesFromFiniteReaderOpts { len: data.len(), chunk_size }
1134                ).unwrap(),
1135                data
1136            );
1137        }
1138    }
1139
1140}
1141