bitcoin/consensus/
encode.rs

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