1use prelude::*;
31
32use core::{fmt, mem, u32, convert::From};
33#[cfg(feature = "std")] use std::error;
34
35use hashes::{sha256d, Hash, sha256};
36use hash_types::{BlockHash, FilterHash, TxMerkleNode, FilterHeader};
37
38use io::{self, Cursor, Read};
39
40use util::endian;
41use util::psbt;
42use util::taproot::TapLeafHash;
43use hashes::hex::ToHex;
44
45use blockdata::transaction::{TxOut, Transaction, TxIn};
46#[cfg(feature = "std")]
47use network::{message_blockdata::Inventory, address::{Address, AddrV2Message}};
48
49#[derive(Debug)]
51pub enum Error {
52 Io(io::Error),
54 Psbt(psbt::Error),
56 UnexpectedNetworkMagic {
58 expected: u32,
60 actual: u32,
62 },
63 OversizedVectorAllocation {
65 requested: usize,
67 max: usize,
69 },
70 InvalidChecksum {
72 expected: [u8; 4],
74 actual: [u8; 4],
76 },
77 NonMinimalVarInt,
79 UnknownNetworkMagic(u32),
81 ParseFailed(&'static str),
83 UnsupportedSegwitFlag(u8),
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 }
104 }
105}
106
107#[cfg(feature = "std")]
108#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
109impl ::std::error::Error for Error {
110 fn cause(&self) -> Option<&dyn error::Error> {
111 match *self {
112 Error::Io(ref e) => Some(e),
113 Error::Psbt(ref e) => Some(e),
114 Error::UnexpectedNetworkMagic { .. }
115 | Error::OversizedVectorAllocation { .. }
116 | Error::InvalidChecksum { .. }
117 | Error::NonMinimalVarInt
118 | Error::UnknownNetworkMagic(..)
119 | Error::ParseFailed(..)
120 | Error::UnsupportedSegwitFlag(..) => None,
121 }
122 }
123}
124
125#[doc(hidden)]
126impl From<io::Error> for Error {
127 fn from(error: io::Error) -> Self {
128 Error::Io(error)
129 }
130}
131
132#[doc(hidden)]
133impl From<psbt::Error> for Error {
134 fn from(e: psbt::Error) -> Error {
135 Error::Psbt(e)
136 }
137}
138
139pub fn serialize<T: Encodable + ?Sized>(data: &T) -> Vec<u8> {
141 let mut encoder = Vec::new();
142 let len = data.consensus_encode(&mut encoder).expect("in-memory writers don't error");
143 debug_assert_eq!(len, encoder.len());
144 encoder
145}
146
147pub fn serialize_hex<T: Encodable + ?Sized>(data: &T) -> String {
149 serialize(data)[..].to_hex()
150}
151
152pub fn deserialize<T: Decodable>(data: &[u8]) -> Result<T, Error> {
155 let (rv, consumed) = deserialize_partial(data)?;
156
157 if consumed == data.len() {
159 Ok(rv)
160 } else {
161 Err(Error::ParseFailed("data not consumed entirely when explicitly deserializing"))
162 }
163}
164
165pub fn deserialize_partial<T: Decodable>(data: &[u8]) -> Result<(T, usize), Error> {
168 let mut decoder = Cursor::new(data);
169 let rv = Decodable::consensus_decode(&mut decoder)?;
170 let consumed = decoder.position() as usize;
171
172 Ok((rv, consumed))
173}
174
175
176pub trait WriteExt {
178 fn emit_u64(&mut self, v: u64) -> Result<(), io::Error>;
180 fn emit_u32(&mut self, v: u32) -> Result<(), io::Error>;
182 fn emit_u16(&mut self, v: u16) -> Result<(), io::Error>;
184 fn emit_u8(&mut self, v: u8) -> Result<(), io::Error>;
186
187 fn emit_i64(&mut self, v: i64) -> Result<(), io::Error>;
189 fn emit_i32(&mut self, v: i32) -> Result<(), io::Error>;
191 fn emit_i16(&mut self, v: i16) -> Result<(), io::Error>;
193 fn emit_i8(&mut self, v: i8) -> Result<(), io::Error>;
195
196 fn emit_bool(&mut self, v: bool) -> Result<(), io::Error>;
198
199 fn emit_slice(&mut self, v: &[u8]) -> Result<(), io::Error>;
201}
202
203pub trait ReadExt {
205 fn read_u64(&mut self) -> Result<u64, Error>;
207 fn read_u32(&mut self) -> Result<u32, Error>;
209 fn read_u16(&mut self) -> Result<u16, Error>;
211 fn read_u8(&mut self) -> Result<u8, Error>;
213
214 fn read_i64(&mut self) -> Result<i64, Error>;
216 fn read_i32(&mut self) -> Result<i32, Error>;
218 fn read_i16(&mut self) -> Result<i16, Error>;
220 fn read_i8(&mut self) -> Result<i8, Error>;
222
223 fn read_bool(&mut self) -> Result<bool, Error>;
225
226 fn read_slice(&mut self, slice: &mut [u8]) -> Result<(), Error>;
228}
229
230macro_rules! encoder_fn {
231 ($name:ident, $val_type:ty, $writefn:ident) => {
232 #[inline]
233 fn $name(&mut self, v: $val_type) -> Result<(), io::Error> {
234 self.write_all(&endian::$writefn(v))
235 }
236 }
237}
238
239macro_rules! decoder_fn {
240 ($name:ident, $val_type:ty, $readfn:ident, $byte_len: expr) => {
241 #[inline]
242 fn $name(&mut self) -> Result<$val_type, Error> {
243 debug_assert_eq!(::core::mem::size_of::<$val_type>(), $byte_len); let mut val = [0; $byte_len];
245 self.read_exact(&mut val[..]).map_err(Error::Io)?;
246 Ok(endian::$readfn(&val))
247 }
248 }
249}
250
251impl<W: io::Write> WriteExt for W {
252 encoder_fn!(emit_u64, u64, u64_to_array_le);
253 encoder_fn!(emit_u32, u32, u32_to_array_le);
254 encoder_fn!(emit_u16, u16, u16_to_array_le);
255 encoder_fn!(emit_i64, i64, i64_to_array_le);
256 encoder_fn!(emit_i32, i32, i32_to_array_le);
257 encoder_fn!(emit_i16, i16, i16_to_array_le);
258
259 #[inline]
260 fn emit_i8(&mut self, v: i8) -> Result<(), io::Error> {
261 self.write_all(&[v as u8])
262 }
263 #[inline]
264 fn emit_u8(&mut self, v: u8) -> Result<(), io::Error> {
265 self.write_all(&[v])
266 }
267 #[inline]
268 fn emit_bool(&mut self, v: bool) -> Result<(), io::Error> {
269 self.write_all(&[v as u8])
270 }
271 #[inline]
272 fn emit_slice(&mut self, v: &[u8]) -> Result<(), io::Error> {
273 self.write_all(v)
274 }
275}
276
277impl<R: Read> ReadExt for R {
278 decoder_fn!(read_u64, u64, slice_to_u64_le, 8);
279 decoder_fn!(read_u32, u32, slice_to_u32_le, 4);
280 decoder_fn!(read_u16, u16, slice_to_u16_le, 2);
281 decoder_fn!(read_i64, i64, slice_to_i64_le, 8);
282 decoder_fn!(read_i32, i32, slice_to_i32_le, 4);
283 decoder_fn!(read_i16, i16, slice_to_i16_le, 2);
284
285 #[inline]
286 fn read_u8(&mut self) -> Result<u8, Error> {
287 let mut slice = [0u8; 1];
288 self.read_exact(&mut slice)?;
289 Ok(slice[0])
290 }
291 #[inline]
292 fn read_i8(&mut self) -> Result<i8, Error> {
293 let mut slice = [0u8; 1];
294 self.read_exact(&mut slice)?;
295 Ok(slice[0] as i8)
296 }
297 #[inline]
298 fn read_bool(&mut self) -> Result<bool, Error> {
299 ReadExt::read_i8(self).map(|bit| bit != 0)
300 }
301 #[inline]
302 fn read_slice(&mut self, slice: &mut [u8]) -> Result<(), Error> {
303 self.read_exact(slice).map_err(Error::Io)
304 }
305}
306
307pub const MAX_VEC_SIZE: usize = 4_000_000;
309
310pub trait Encodable {
312 fn consensus_encode<W: io::Write>(&self, writer: W) -> Result<usize, io::Error>;
317}
318
319pub trait Decodable: Sized {
321 fn consensus_decode<D: io::Read>(d: D) -> Result<Self, Error>;
323}
324
325#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
327pub struct VarInt(pub u64);
328
329#[derive(PartialEq, Eq, Clone, Debug)]
331pub struct CheckedData(pub Vec<u8>);
332
333macro_rules! impl_int_encodable {
335 ($ty:ident, $meth_dec:ident, $meth_enc:ident) => {
336 impl Decodable for $ty {
337 #[inline]
338 fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, Error> {
339 ReadExt::$meth_dec(&mut d)
340 }
341 }
342 impl Encodable for $ty {
343 #[inline]
344 fn consensus_encode<S: WriteExt>(&self, mut s: S) -> Result<usize, io::Error> {
345 s.$meth_enc(*self)?;
346 Ok(mem::size_of::<$ty>())
347 }
348 }
349 }
350}
351
352impl_int_encodable!(u8, read_u8, emit_u8);
353impl_int_encodable!(u16, read_u16, emit_u16);
354impl_int_encodable!(u32, read_u32, emit_u32);
355impl_int_encodable!(u64, read_u64, emit_u64);
356impl_int_encodable!(i8, read_i8, emit_i8);
357impl_int_encodable!(i16, read_i16, emit_i16);
358impl_int_encodable!(i32, read_i32, emit_i32);
359impl_int_encodable!(i64, read_i64, emit_i64);
360
361impl VarInt {
362 #[inline]
366 pub fn len(&self) -> usize {
367 match self.0 {
368 0..=0xFC => { 1 }
369 0xFD..=0xFFFF => { 3 }
370 0x10000..=0xFFFFFFFF => { 5 }
371 _ => { 9 }
372 }
373 }
374}
375
376impl Encodable for VarInt {
377 #[inline]
378 fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, io::Error> {
379 match self.0 {
380 0..=0xFC => {
381 (self.0 as u8).consensus_encode(s)?;
382 Ok(1)
383 },
384 0xFD..=0xFFFF => {
385 s.emit_u8(0xFD)?;
386 (self.0 as u16).consensus_encode(s)?;
387 Ok(3)
388 },
389 0x10000..=0xFFFFFFFF => {
390 s.emit_u8(0xFE)?;
391 (self.0 as u32).consensus_encode(s)?;
392 Ok(5)
393 },
394 _ => {
395 s.emit_u8(0xFF)?;
396 (self.0 as u64).consensus_encode(s)?;
397 Ok(9)
398 },
399 }
400 }
401}
402
403impl Decodable for VarInt {
404 #[inline]
405 fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, Error> {
406 let n = ReadExt::read_u8(&mut d)?;
407 match n {
408 0xFF => {
409 let x = ReadExt::read_u64(&mut d)?;
410 if x < 0x100000000 {
411 Err(self::Error::NonMinimalVarInt)
412 } else {
413 Ok(VarInt(x))
414 }
415 }
416 0xFE => {
417 let x = ReadExt::read_u32(&mut d)?;
418 if x < 0x10000 {
419 Err(self::Error::NonMinimalVarInt)
420 } else {
421 Ok(VarInt(x as u64))
422 }
423 }
424 0xFD => {
425 let x = ReadExt::read_u16(&mut d)?;
426 if x < 0xFD {
427 Err(self::Error::NonMinimalVarInt)
428 } else {
429 Ok(VarInt(x as u64))
430 }
431 }
432 n => Ok(VarInt(n as u64))
433 }
434 }
435}
436
437impl Encodable for bool {
439 #[inline]
440 fn consensus_encode<S: WriteExt>(&self, mut s: S) -> Result<usize, io::Error> {
441 s.emit_bool(*self)?;
442 Ok(1)
443 }
444}
445
446impl Decodable for bool {
447 #[inline]
448 fn consensus_decode<D: io::Read>(mut d: D) -> Result<bool, Error> {
449 ReadExt::read_bool(&mut d)
450 }
451}
452
453impl Encodable for String {
455 #[inline]
456 fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, io::Error> {
457 let b = self.as_bytes();
458 let vi_len = VarInt(b.len() as u64).consensus_encode(&mut s)?;
459 s.emit_slice(b)?;
460 Ok(vi_len + b.len())
461 }
462}
463
464impl Decodable for String {
465 #[inline]
466 fn consensus_decode<D: io::Read>(d: D) -> Result<String, Error> {
467 String::from_utf8(Decodable::consensus_decode(d)?)
468 .map_err(|_| self::Error::ParseFailed("String was not valid UTF8"))
469 }
470}
471
472impl Encodable for Cow<'static, str> {
474 #[inline]
475 fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, io::Error> {
476 let b = self.as_bytes();
477 let vi_len = VarInt(b.len() as u64).consensus_encode(&mut s)?;
478 s.emit_slice(b)?;
479 Ok(vi_len + b.len())
480 }
481}
482
483impl Decodable for Cow<'static, str> {
484 #[inline]
485 fn consensus_decode<D: io::Read>(d: D) -> Result<Cow<'static, str>, Error> {
486 String::from_utf8(Decodable::consensus_decode(d)?)
487 .map_err(|_| self::Error::ParseFailed("String was not valid UTF8"))
488 .map(Cow::Owned)
489 }
490}
491
492
493macro_rules! impl_array {
495 ( $size:expr ) => {
496 impl Encodable for [u8; $size] {
497 #[inline]
498 fn consensus_encode<S: WriteExt>(&self, mut s: S) -> Result<usize, io::Error> {
499 s.emit_slice(&self[..])?;
500 Ok(self.len())
501 }
502 }
503
504 impl Decodable for [u8; $size] {
505 #[inline]
506 fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, Error> {
507 let mut ret = [0; $size];
508 d.read_slice(&mut ret)?;
509 Ok(ret)
510 }
511 }
512 };
513}
514
515impl_array!(2);
516impl_array!(4);
517impl_array!(8);
518impl_array!(10);
519impl_array!(12);
520impl_array!(16);
521impl_array!(32);
522impl_array!(33);
523
524impl Decodable for [u16; 8] {
525 #[inline]
526 fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, Error> {
527 let mut res = [0; 8];
528 for item in &mut res {
529 *item = Decodable::consensus_decode(&mut d)?;
530 }
531 Ok(res)
532 }
533}
534
535impl Encodable for [u16; 8] {
536 #[inline]
537 fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, io::Error> {
538 for c in self.iter() { c.consensus_encode(&mut s)?; }
539 Ok(16)
540 }
541}
542
543macro_rules! impl_vec {
545 ($type: ty) => {
546 impl Encodable for Vec<$type> {
547 #[inline]
548 fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, io::Error> {
549 let mut len = 0;
550 len += VarInt(self.len() as u64).consensus_encode(&mut s)?;
551 for c in self.iter() {
552 len += c.consensus_encode(&mut s)?;
553 }
554 Ok(len)
555 }
556 }
557 impl Decodable for Vec<$type> {
558 #[inline]
559 fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, Error> {
560 let len = VarInt::consensus_decode(&mut d)?.0;
561 let byte_size = (len as usize)
562 .checked_mul(mem::size_of::<$type>())
563 .ok_or(self::Error::ParseFailed("Invalid length"))?;
564 if byte_size > MAX_VEC_SIZE {
565 return Err(self::Error::OversizedVectorAllocation { requested: byte_size, max: MAX_VEC_SIZE })
566 }
567 let mut ret = Vec::with_capacity(len as usize);
568 let mut d = d.take(MAX_VEC_SIZE as u64);
569 for _ in 0..len {
570 ret.push(Decodable::consensus_decode(&mut d)?);
571 }
572 Ok(ret)
573 }
574 }
575 }
576}
577impl_vec!(BlockHash);
578impl_vec!(FilterHash);
579impl_vec!(FilterHeader);
580impl_vec!(TxMerkleNode);
581impl_vec!(Transaction);
582impl_vec!(TxOut);
583impl_vec!(TxIn);
584impl_vec!(Vec<u8>);
585impl_vec!(u64);
586impl_vec!(TapLeafHash);
587
588#[cfg(feature = "std")] impl_vec!(Inventory);
589#[cfg(feature = "std")] impl_vec!((u32, Address));
590#[cfg(feature = "std")] impl_vec!(AddrV2Message);
591
592pub(crate) fn consensus_encode_with_size<S: io::Write>(data: &[u8], mut s: S) -> Result<usize, io::Error> {
593 let vi_len = VarInt(data.len() as u64).consensus_encode(&mut s)?;
594 s.emit_slice(data)?;
595 Ok(vi_len + data.len())
596}
597
598
599impl Encodable for Vec<u8> {
600 #[inline]
601 fn consensus_encode<S: io::Write>(&self, s: S) -> Result<usize, io::Error> {
602 consensus_encode_with_size(self, s)
603 }
604}
605
606impl Decodable for Vec<u8> {
607 #[inline]
608 fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, Error> {
609 let len = VarInt::consensus_decode(&mut d)?.0 as usize;
610 if len > MAX_VEC_SIZE {
611 return Err(self::Error::OversizedVectorAllocation { requested: len, max: MAX_VEC_SIZE })
612 }
613 let mut ret = vec![0u8; len];
614 d.read_slice(&mut ret)?;
615 Ok(ret)
616 }
617}
618
619impl Encodable for Box<[u8]> {
620 #[inline]
621 fn consensus_encode<S: io::Write>(&self, s: S) -> Result<usize, io::Error> {
622 consensus_encode_with_size(self, s)
623 }
624}
625
626impl Decodable for Box<[u8]> {
627 #[inline]
628 fn consensus_decode<D: io::Read>(d: D) -> Result<Self, Error> {
629 <Vec<u8>>::consensus_decode(d).map(From::from)
630 }
631}
632
633
634fn sha2_checksum(data: &[u8]) -> [u8; 4] {
636 let checksum = <sha256d::Hash as Hash>::hash(data);
637 [checksum[0], checksum[1], checksum[2], checksum[3]]
638}
639
640impl Encodable for CheckedData {
642 #[inline]
643 fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, io::Error> {
644 (self.0.len() as u32).consensus_encode(&mut s)?;
645 sha2_checksum(&self.0).consensus_encode(&mut s)?;
646 s.emit_slice(&self.0)?;
647 Ok(8 + self.0.len())
648 }
649}
650
651impl Decodable for CheckedData {
652 #[inline]
653 fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, Error> {
654 let len = u32::consensus_decode(&mut d)?;
655 if len > MAX_VEC_SIZE as u32 {
656 return Err(self::Error::OversizedVectorAllocation {
657 requested: len as usize,
658 max: MAX_VEC_SIZE
659 });
660 }
661 let checksum = <[u8; 4]>::consensus_decode(&mut d)?;
662 let mut ret = vec![0u8; len as usize];
663 d.read_slice(&mut ret)?;
664 let expected_checksum = sha2_checksum(&ret);
665 if expected_checksum != checksum {
666 Err(self::Error::InvalidChecksum {
667 expected: expected_checksum,
668 actual: checksum,
669 })
670 } else {
671 Ok(CheckedData(ret))
672 }
673 }
674}
675
676impl<'a, T: Encodable> Encodable for &'a T {
678 fn consensus_encode<S: io::Write>(&self, s: S) -> Result<usize, io::Error> {
679 (&**self).consensus_encode(s)
680 }
681}
682
683impl<'a, T: Encodable> Encodable for &'a mut T {
684 fn consensus_encode<S: io::Write>(&self, s: S) -> Result<usize, io::Error> {
685 (&**self).consensus_encode(s)
686 }
687}
688
689impl<T: Encodable> Encodable for rc::Rc<T> {
690 fn consensus_encode<S: io::Write>(&self, s: S) -> Result<usize, io::Error> {
691 (&**self).consensus_encode(s)
692 }
693}
694
695impl<T: Encodable> Encodable for sync::Arc<T> {
696 fn consensus_encode<S: io::Write>(&self, s: S) -> Result<usize, io::Error> {
697 (&**self).consensus_encode(s)
698 }
699}
700
701macro_rules! tuple_encode {
703 ($($x:ident),*) => {
704 impl <$($x: Encodable),*> Encodable for ($($x),*) {
705 #[inline]
706 #[allow(non_snake_case)]
707 fn consensus_encode<S: io::Write>(
708 &self,
709 mut s: S,
710 ) -> Result<usize, io::Error> {
711 let &($(ref $x),*) = self;
712 let mut len = 0;
713 $(len += $x.consensus_encode(&mut s)?;)*
714 Ok(len)
715 }
716 }
717
718 impl<$($x: Decodable),*> Decodable for ($($x),*) {
719 #[inline]
720 #[allow(non_snake_case)]
721 fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, Error> {
722 Ok(($({let $x = Decodable::consensus_decode(&mut d)?; $x }),*))
723 }
724 }
725 };
726}
727
728tuple_encode!(T0, T1);
729tuple_encode!(T0, T1, T2);
730tuple_encode!(T0, T1, T2, T3);
731tuple_encode!(T0, T1, T2, T3, T4);
732tuple_encode!(T0, T1, T2, T3, T4, T5);
733tuple_encode!(T0, T1, T2, T3, T4, T5, T6);
734tuple_encode!(T0, T1, T2, T3, T4, T5, T6, T7);
735
736impl Encodable for sha256d::Hash {
737 fn consensus_encode<S: io::Write>(&self, s: S) -> Result<usize, io::Error> {
738 self.into_inner().consensus_encode(s)
739 }
740}
741
742impl Decodable for sha256d::Hash {
743 fn consensus_decode<D: io::Read>(d: D) -> Result<Self, Error> {
744 Ok(Self::from_inner(<<Self as Hash>::Inner>::consensus_decode(d)?))
745 }
746}
747
748impl Encodable for sha256::Hash {
749 fn consensus_encode<S: io::Write>(&self, s: S) -> Result<usize, io::Error> {
750 self.into_inner().consensus_encode(s)
751 }
752}
753
754impl Decodable for sha256::Hash {
755 fn consensus_decode<D: io::Read>(d: D) -> Result<Self, Error> {
756 Ok(Self::from_inner(<<Self as Hash>::Inner>::consensus_decode(d)?))
757 }
758}
759
760impl Encodable for TapLeafHash {
761 fn consensus_encode<S: io::Write>(&self, s: S) -> Result<usize, io::Error> {
762 self.into_inner().consensus_encode(s)
763 }
764}
765
766impl Decodable for TapLeafHash {
767 fn consensus_decode<D: io::Read>(d: D) -> Result<Self, Error> {
768 Ok(Self::from_inner(<<Self as Hash>::Inner>::consensus_decode(d)?))
769 }
770}
771
772#[cfg(test)]
774mod tests {
775 use super::*;
776 use core::{mem::{self, discriminant}, fmt};
777 use super::{deserialize, serialize, Error, CheckedData, VarInt};
778 use super::{Transaction, BlockHash, FilterHash, TxMerkleNode, TxOut, TxIn};
779 use consensus::{Encodable, deserialize_partial, Decodable};
780 use util::endian::{u64_to_array_le, u32_to_array_le, u16_to_array_le};
781 use secp256k1::rand::{thread_rng, Rng};
782 #[cfg(feature = "std")]
783 use network::{Address, message_blockdata::Inventory};
784
785 #[test]
786 fn serialize_int_test() {
787 assert_eq!(serialize(&false), vec![0u8]);
789 assert_eq!(serialize(&true), vec![1u8]);
790 assert_eq!(serialize(&1u8), vec![1u8]);
792 assert_eq!(serialize(&0u8), vec![0u8]);
793 assert_eq!(serialize(&255u8), vec![255u8]);
794 assert_eq!(serialize(&1u16), vec![1u8, 0]);
796 assert_eq!(serialize(&256u16), vec![0u8, 1]);
797 assert_eq!(serialize(&5000u16), vec![136u8, 19]);
798 assert_eq!(serialize(&1u32), vec![1u8, 0, 0, 0]);
800 assert_eq!(serialize(&256u32), vec![0u8, 1, 0, 0]);
801 assert_eq!(serialize(&5000u32), vec![136u8, 19, 0, 0]);
802 assert_eq!(serialize(&500000u32), vec![32u8, 161, 7, 0]);
803 assert_eq!(serialize(&168430090u32), vec![10u8, 10, 10, 10]);
804 assert_eq!(serialize(&-1i32), vec![255u8, 255, 255, 255]);
806 assert_eq!(serialize(&-256i32), vec![0u8, 255, 255, 255]);
807 assert_eq!(serialize(&-5000i32), vec![120u8, 236, 255, 255]);
808 assert_eq!(serialize(&-500000i32), vec![224u8, 94, 248, 255]);
809 assert_eq!(serialize(&-168430090i32), vec![246u8, 245, 245, 245]);
810 assert_eq!(serialize(&1i32), vec![1u8, 0, 0, 0]);
811 assert_eq!(serialize(&256i32), vec![0u8, 1, 0, 0]);
812 assert_eq!(serialize(&5000i32), vec![136u8, 19, 0, 0]);
813 assert_eq!(serialize(&500000i32), vec![32u8, 161, 7, 0]);
814 assert_eq!(serialize(&168430090i32), vec![10u8, 10, 10, 10]);
815 assert_eq!(serialize(&1u64), vec![1u8, 0, 0, 0, 0, 0, 0, 0]);
817 assert_eq!(serialize(&256u64), vec![0u8, 1, 0, 0, 0, 0, 0, 0]);
818 assert_eq!(serialize(&5000u64), vec![136u8, 19, 0, 0, 0, 0, 0, 0]);
819 assert_eq!(serialize(&500000u64), vec![32u8, 161, 7, 0, 0, 0, 0, 0]);
820 assert_eq!(serialize(&723401728380766730u64), vec![10u8, 10, 10, 10, 10, 10, 10, 10]);
821 assert_eq!(serialize(&-1i64), vec![255u8, 255, 255, 255, 255, 255, 255, 255]);
823 assert_eq!(serialize(&-256i64), vec![0u8, 255, 255, 255, 255, 255, 255, 255]);
824 assert_eq!(serialize(&-5000i64), vec![120u8, 236, 255, 255, 255, 255, 255, 255]);
825 assert_eq!(serialize(&-500000i64), vec![224u8, 94, 248, 255, 255, 255, 255, 255]);
826 assert_eq!(serialize(&-723401728380766730i64), vec![246u8, 245, 245, 245, 245, 245, 245, 245]);
827 assert_eq!(serialize(&1i64), vec![1u8, 0, 0, 0, 0, 0, 0, 0]);
828 assert_eq!(serialize(&256i64), vec![0u8, 1, 0, 0, 0, 0, 0, 0]);
829 assert_eq!(serialize(&5000i64), vec![136u8, 19, 0, 0, 0, 0, 0, 0]);
830 assert_eq!(serialize(&500000i64), vec![32u8, 161, 7, 0, 0, 0, 0, 0]);
831 assert_eq!(serialize(&723401728380766730i64), vec![10u8, 10, 10, 10, 10, 10, 10, 10]);
832 }
833
834 #[test]
835 fn serialize_varint_test() {
836 assert_eq!(serialize(&VarInt(10)), vec![10u8]);
837 assert_eq!(serialize(&VarInt(0xFC)), vec![0xFCu8]);
838 assert_eq!(serialize(&VarInt(0xFD)), vec![0xFDu8, 0xFD, 0]);
839 assert_eq!(serialize(&VarInt(0xFFF)), vec![0xFDu8, 0xFF, 0xF]);
840 assert_eq!(serialize(&VarInt(0xF0F0F0F)), vec![0xFEu8, 0xF, 0xF, 0xF, 0xF]);
841 assert_eq!(serialize(&VarInt(0xF0F0F0F0F0E0)), vec![0xFFu8, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0, 0]);
842 assert_eq!(test_varint_encode(0xFF, &u64_to_array_le(0x100000000)).unwrap(), VarInt(0x100000000));
843 assert_eq!(test_varint_encode(0xFE, &u64_to_array_le(0x10000)).unwrap(), VarInt(0x10000));
844 assert_eq!(test_varint_encode(0xFD, &u64_to_array_le(0xFD)).unwrap(), VarInt(0xFD));
845
846 test_varint_len(VarInt(0), 1);
848 test_varint_len(VarInt(0xFC), 1);
849 test_varint_len(VarInt(0xFD), 3);
850 test_varint_len(VarInt(0xFFFF), 3);
851 test_varint_len(VarInt(0x10000), 5);
852 test_varint_len(VarInt(0xFFFFFFFF), 5);
853 test_varint_len(VarInt(0xFFFFFFFF+1), 9);
854 test_varint_len(VarInt(u64::max_value()), 9);
855 }
856
857 fn test_varint_len(varint: VarInt, expected: usize) {
858 let mut encoder = vec![];
859 assert_eq!(varint.consensus_encode(&mut encoder).unwrap(), expected);
860 assert_eq!(varint.len(), expected);
861 }
862
863 fn test_varint_encode(n: u8, x: &[u8]) -> Result<VarInt, Error> {
864 let mut input = [0u8; 9];
865 input[0] = n;
866 input[1..x.len()+1].copy_from_slice(x);
867 deserialize_partial::<VarInt>(&input).map(|t|t.0)
868 }
869
870 #[test]
871 fn deserialize_nonminimal_vec() {
872 assert_eq!(discriminant(&test_varint_encode(0xFF, &u64_to_array_le(0x100000000-1)).unwrap_err()),
874 discriminant(&Error::NonMinimalVarInt));
875 assert_eq!(discriminant(&test_varint_encode(0xFE, &u32_to_array_le(0x10000-1)).unwrap_err()),
876 discriminant(&Error::NonMinimalVarInt));
877 assert_eq!(discriminant(&test_varint_encode(0xFD, &u16_to_array_le(0xFD-1)).unwrap_err()),
878 discriminant(&Error::NonMinimalVarInt));
879
880 assert_eq!(discriminant(&deserialize::<Vec<u8>>(&[0xfd, 0x00, 0x00]).unwrap_err()),
881 discriminant(&Error::NonMinimalVarInt));
882 assert_eq!(discriminant(&deserialize::<Vec<u8>>(&[0xfd, 0xfc, 0x00]).unwrap_err()),
883 discriminant(&Error::NonMinimalVarInt));
884 assert_eq!(discriminant(&deserialize::<Vec<u8>>(&[0xfd, 0xfc, 0x00]).unwrap_err()),
885 discriminant(&Error::NonMinimalVarInt));
886 assert_eq!(discriminant(&deserialize::<Vec<u8>>(&[0xfe, 0xff, 0x00, 0x00, 0x00]).unwrap_err()),
887 discriminant(&Error::NonMinimalVarInt));
888 assert_eq!(discriminant(&deserialize::<Vec<u8>>(&[0xfe, 0xff, 0xff, 0x00, 0x00]).unwrap_err()),
889 discriminant(&Error::NonMinimalVarInt));
890 assert_eq!(discriminant(&deserialize::<Vec<u8>>(&[0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]).unwrap_err()),
891 discriminant(&Error::NonMinimalVarInt));
892 assert_eq!(discriminant(&deserialize::<Vec<u8>>(&[0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00]).unwrap_err()),
893 discriminant(&Error::NonMinimalVarInt));
894
895
896 let mut vec_256 = vec![0; 259];
897 vec_256[0] = 0xfd;
898 vec_256[1] = 0x00;
899 vec_256[2] = 0x01;
900 assert!(deserialize::<Vec<u8>>(&vec_256).is_ok());
901
902 let mut vec_253 = vec![0; 256];
903 vec_253[0] = 0xfd;
904 vec_253[1] = 0xfd;
905 vec_253[2] = 0x00;
906 assert!(deserialize::<Vec<u8>>(&vec_253).is_ok());
907 }
908
909 #[test]
910 fn serialize_checkeddata_test() {
911 let cd = CheckedData(vec![1u8, 2, 3, 4, 5]);
912 assert_eq!(serialize(&cd), vec![5, 0, 0, 0, 162, 107, 175, 90, 1, 2, 3, 4, 5]);
913 }
914
915 #[test]
916 fn serialize_vector_test() {
917 assert_eq!(serialize(&vec![1u8, 2, 3]), vec![3u8, 1, 2, 3]);
918 }
920
921 #[test]
922 fn serialize_strbuf_test() {
923 assert_eq!(serialize(&"Andrew".to_string()), vec![6u8, 0x41, 0x6e, 0x64, 0x72, 0x65, 0x77]);
924 }
925
926 #[test]
927 fn deserialize_int_test() {
928 assert!((deserialize(&[58u8, 0]) as Result<bool, _>).is_err());
930 assert_eq!(deserialize(&[58u8]).ok(), Some(true));
931 assert_eq!(deserialize(&[1u8]).ok(), Some(true));
932 assert_eq!(deserialize(&[0u8]).ok(), Some(false));
933 assert!((deserialize(&[0u8, 1]) as Result<bool, _>).is_err());
934
935 assert_eq!(deserialize(&[58u8]).ok(), Some(58u8));
937
938 assert_eq!(deserialize(&[0x01u8, 0x02]).ok(), Some(0x0201u16));
940 assert_eq!(deserialize(&[0xABu8, 0xCD]).ok(), Some(0xCDABu16));
941 assert_eq!(deserialize(&[0xA0u8, 0x0D]).ok(), Some(0xDA0u16));
942 let failure16: Result<u16, _> = deserialize(&[1u8]);
943 assert!(failure16.is_err());
944
945 assert_eq!(deserialize(&[0xABu8, 0xCD, 0, 0]).ok(), Some(0xCDABu32));
947 assert_eq!(deserialize(&[0xA0u8, 0x0D, 0xAB, 0xCD]).ok(), Some(0xCDAB0DA0u32));
948 let failure32: Result<u32, _> = deserialize(&[1u8, 2, 3]);
949 assert!(failure32.is_err());
950 assert_eq!(deserialize(&[0xABu8, 0xCD, 0, 0]).ok(), Some(0xCDABi32));
952 assert_eq!(deserialize(&[0xA0u8, 0x0D, 0xAB, 0x2D]).ok(), Some(0x2DAB0DA0i32));
953 let failurei32: Result<i32, _> = deserialize(&[1u8, 2, 3]);
954 assert!(failurei32.is_err());
955
956 assert_eq!(deserialize(&[0xABu8, 0xCD, 0, 0, 0, 0, 0, 0]).ok(), Some(0xCDABu64));
958 assert_eq!(deserialize(&[0xA0u8, 0x0D, 0xAB, 0xCD, 0x99, 0, 0, 0x99]).ok(), Some(0x99000099CDAB0DA0u64));
959 let failure64: Result<u64, _> = deserialize(&[1u8, 2, 3, 4, 5, 6, 7]);
960 assert!(failure64.is_err());
961 assert_eq!(deserialize(&[0xABu8, 0xCD, 0, 0, 0, 0, 0, 0]).ok(), Some(0xCDABi64));
963 assert_eq!(deserialize(&[0xA0u8, 0x0D, 0xAB, 0xCD, 0x99, 0, 0, 0x99]).ok(), Some(-0x66ffff663254f260i64));
964 let failurei64: Result<i64, _> = deserialize(&[1u8, 2, 3, 4, 5, 6, 7]);
965 assert!(failurei64.is_err());
966 }
967
968 #[test]
969 fn deserialize_vec_test() {
970 assert_eq!(deserialize(&[3u8, 2, 3, 4]).ok(), Some(vec![2u8, 3, 4]));
971 assert!((deserialize(&[4u8, 2, 3, 4, 5, 6]) as Result<Vec<u8>, _>).is_err());
972 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());
974
975 let rand_io_err = Error::Io(io::Error::new(io::ErrorKind::Other, ""));
976
977 let err = deserialize::<CheckedData>(&serialize(&(super::MAX_VEC_SIZE as u32))).unwrap_err();
980 assert_eq!(discriminant(&err), discriminant(&rand_io_err));
981
982 test_len_is_max_vec::<u8>();
983 test_len_is_max_vec::<BlockHash>();
984 test_len_is_max_vec::<FilterHash>();
985 test_len_is_max_vec::<TxMerkleNode>();
986 test_len_is_max_vec::<Transaction>();
987 test_len_is_max_vec::<TxOut>();
988 test_len_is_max_vec::<TxIn>();
989 test_len_is_max_vec::<Vec<u8>>();
990 test_len_is_max_vec::<u64>();
991 #[cfg(feature = "std")]
992 test_len_is_max_vec::<(u32, Address)>();
993 #[cfg(feature = "std")]
994 test_len_is_max_vec::<Inventory>();
995 }
996
997 fn test_len_is_max_vec<T>() where Vec<T>: Decodable, T: fmt::Debug {
998 let rand_io_err = Error::Io(io::Error::new(io::ErrorKind::Other, ""));
999 let varint = VarInt((super::MAX_VEC_SIZE / mem::size_of::<T>()) as u64);
1000 let err = deserialize::<Vec<T>>(&serialize(&varint)).unwrap_err();
1001 assert_eq!(discriminant(&err), discriminant(&rand_io_err));
1002 }
1003
1004 #[test]
1005 fn deserialize_strbuf_test() {
1006 assert_eq!(deserialize(&[6u8, 0x41, 0x6e, 0x64, 0x72, 0x65, 0x77]).ok(), Some("Andrew".to_string()));
1007 assert_eq!(
1008 deserialize(&[6u8, 0x41, 0x6e, 0x64, 0x72, 0x65, 0x77]).ok(),
1009 Some(Cow::Borrowed("Andrew"))
1010 );
1011 }
1012
1013 #[test]
1014 fn deserialize_checkeddata_test() {
1015 let cd: Result<CheckedData, _> = deserialize(&[5u8, 0, 0, 0, 162, 107, 175, 90, 1, 2, 3, 4, 5]);
1016 assert_eq!(cd.ok(), Some(CheckedData(vec![1u8, 2, 3, 4, 5])));
1017 }
1018
1019 #[test]
1020 fn limit_read_test() {
1021 let witness = vec![vec![0u8; 3_999_999]; 2];
1022 let ser = serialize(&witness);
1023 let mut reader = io::Cursor::new(ser);
1024 let err = Vec::<Vec<u8>>::consensus_decode(&mut reader);
1025 assert!(err.is_err());
1026 }
1027
1028 #[test]
1029 fn serialization_round_trips() {
1030 macro_rules! round_trip {
1031 ($($val_type:ty),*) => {
1032 $(
1033 let r: $val_type = thread_rng().gen();
1034 assert_eq!(deserialize::<$val_type>(&serialize(&r)).unwrap(), r);
1035 )*
1036 };
1037 }
1038 macro_rules! round_trip_bytes {
1039 ($(($val_type:ty, $data:expr)),*) => {
1040 $(
1041 thread_rng().fill(&mut $data[..]);
1042 assert_eq!(deserialize::<$val_type>(&serialize(&$data)).unwrap()[..], $data[..]);
1043 )*
1044 };
1045 }
1046
1047 let mut data = Vec::with_capacity(256);
1048 let mut data64 = Vec::with_capacity(256);
1049 for _ in 0..10 {
1050 round_trip!{bool, i8, u8, i16, u16, i32, u32, i64, u64,
1051 (bool, i8, u16, i32), (u64, i64, u32, i32, u16, i16), (i8, u8, i16, u16, i32, u32, i64, u64),
1052 [u8; 2], [u8; 4], [u8; 8], [u8; 12], [u8; 16], [u8; 32]};
1053
1054 data.clear();
1055 data64.clear();
1056 let len = thread_rng().gen_range(1..256);
1057 data.resize(len, 0u8);
1058 data64.resize(len, 0u64);
1059 let mut arr33 = [0u8; 33];
1060 let mut arr16 = [0u16; 8];
1061 round_trip_bytes!{(Vec<u8>, data), ([u8; 33], arr33), ([u16; 8], arr16), (Vec<u64>, data64)};
1062
1063
1064 }
1065 }
1066}
1067