Make Readable::read a templated on the stream, not Readable itself
[rust-lightning] / lightning / src / util / ser.rs
1 //! A very simple serialization framework which is used to serialize/deserialize messages as well
2 //! as ChannelsManagers and ChannelMonitors.
3
4 use std::result::Result;
5 use std::io::{Read, Write};
6 use std::collections::HashMap;
7 use std::hash::Hash;
8 use std::sync::Mutex;
9 use std::cmp;
10
11 use secp256k1::Signature;
12 use secp256k1::key::{PublicKey, SecretKey};
13 use bitcoin::blockdata::script::Script;
14 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
15 use bitcoin::consensus;
16 use bitcoin::consensus::Encodable;
17 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
18 use std::marker::Sized;
19 use ln::msgs::DecodeError;
20 use ln::channelmanager::{PaymentPreimage, PaymentHash};
21 use util::byte_utils;
22
23 use util::byte_utils::{be64_to_array, be48_to_array, be32_to_array, be16_to_array, slice_to_be16, slice_to_be32, slice_to_be48, slice_to_be64};
24
25 const MAX_BUF_SIZE: usize = 64 * 1024;
26
27 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
28 /// buffers being written into.
29 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
30 /// hints.
31 pub trait Writer {
32         /// Writes the given buf out. See std::io::Write::write_all for more
33         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
34         /// Hints that data of the given size is about the be written. This may not always be called
35         /// prior to data being written and may be safely ignored.
36         fn size_hint(&mut self, size: usize);
37 }
38
39 impl<W: Write> Writer for W {
40         #[inline]
41         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
42                 <Self as ::std::io::Write>::write_all(self, buf)
43         }
44         #[inline]
45         fn size_hint(&mut self, _size: usize) { }
46 }
47
48 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
49 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
50         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
51                 self.0.write_all(buf)
52         }
53         fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
54                 self.0.write_all(buf)?;
55                 Ok(buf.len())
56         }
57         fn flush(&mut self) -> Result<(), ::std::io::Error> {
58                 Ok(())
59         }
60 }
61
62 pub(crate) struct VecWriter(pub Vec<u8>);
63 impl Writer for VecWriter {
64         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
65                 self.0.extend_from_slice(buf);
66                 Ok(())
67         }
68         fn size_hint(&mut self, size: usize) {
69                 self.0.reserve_exact(size);
70         }
71 }
72
73 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
74 /// of some data when serialized but don't yet need the full data.
75 pub(crate) struct LengthCalculatingWriter(pub usize);
76 impl Writer for LengthCalculatingWriter {
77         #[inline]
78         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
79                 self.0 += buf.len();
80                 Ok(())
81         }
82         #[inline]
83         fn size_hint(&mut self, _size: usize) {}
84 }
85
86 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
87 /// forward to ensure we always consume exactly the fixed length specified.
88 pub(crate) struct FixedLengthReader<R: Read> {
89         read: R,
90         bytes_read: u64,
91         total_bytes: u64,
92 }
93 impl<R: Read> FixedLengthReader<R> {
94         pub fn new(read: R, total_bytes: u64) -> Self {
95                 Self { read, bytes_read: 0, total_bytes }
96         }
97
98         pub fn bytes_remain(&mut self) -> bool {
99                 self.bytes_read != self.total_bytes
100         }
101
102         pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
103                 ::std::io::copy(self, &mut ::std::io::sink()).unwrap();
104                 if self.bytes_read != self.total_bytes {
105                         Err(DecodeError::ShortRead)
106                 } else {
107                         Ok(())
108                 }
109         }
110 }
111 impl<R: Read> Read for FixedLengthReader<R> {
112         fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
113                 if self.total_bytes == self.bytes_read {
114                         Ok(0)
115                 } else {
116                         let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
117                         match self.read.read(&mut dest[0..(read_len as usize)]) {
118                                 Ok(v) => {
119                                         self.bytes_read += v as u64;
120                                         Ok(v)
121                                 },
122                                 Err(e) => Err(e),
123                         }
124                 }
125         }
126 }
127
128 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
129 /// between "EOF reached before we started" and "EOF reached mid-read".
130 pub(crate) struct ReadTrackingReader<R: Read> {
131         read: R,
132         pub have_read: bool,
133 }
134 impl<R: Read> ReadTrackingReader<R> {
135         pub fn new(read: R) -> Self {
136                 Self { read, have_read: false }
137         }
138 }
139 impl<R: Read> Read for ReadTrackingReader<R> {
140         fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
141                 match self.read.read(dest) {
142                         Ok(0) => Ok(0),
143                         Ok(len) => {
144                                 self.have_read = true;
145                                 Ok(len)
146                         },
147                         Err(e) => Err(e),
148                 }
149         }
150 }
151
152 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
153 pub trait Writeable {
154         /// Writes self out to the given Writer
155         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
156
157         /// Writes self out to a Vec<u8>
158         fn encode(&self) -> Vec<u8> {
159                 let mut msg = VecWriter(Vec::new());
160                 self.write(&mut msg).unwrap();
161                 msg.0
162         }
163
164         /// Writes self out to a Vec<u8>
165         fn encode_with_len(&self) -> Vec<u8> {
166                 let mut msg = VecWriter(Vec::new());
167                 0u16.write(&mut msg).unwrap();
168                 self.write(&mut msg).unwrap();
169                 let len = msg.0.len();
170                 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
171                 msg.0
172         }
173 }
174
175 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
176 pub trait Readable
177         where Self: Sized
178 {
179         /// Reads a Self in from the given Read
180         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
181 }
182
183 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
184 /// from a Read given some additional set of arguments which is required to deserialize.
185 pub trait ReadableArgs<P>
186         where Self: Sized
187 {
188         /// Reads a Self in from the given Read
189         fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
190 }
191
192 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
193 pub trait MaybeReadable
194         where Self: Sized
195 {
196         /// Reads a Self in from the given Read
197         fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
198 }
199
200 pub(crate) struct U48(pub u64);
201 impl Writeable for U48 {
202         #[inline]
203         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
204                 writer.write_all(&be48_to_array(self.0))
205         }
206 }
207 impl Readable for U48 {
208         #[inline]
209         fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
210                 let mut buf = [0; 6];
211                 reader.read_exact(&mut buf)?;
212                 Ok(U48(slice_to_be48(&buf)))
213         }
214 }
215
216 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
217 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
218 ///
219 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
220 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
221 /// you're looking for an example of a variable-length integer to use for your own project, move
222 /// along, this is a rather poor design.
223 pub(crate) struct BigSize(pub u64);
224 impl Writeable for BigSize {
225         #[inline]
226         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
227                 match self.0 {
228                         0...0xFC => {
229                                 (self.0 as u8).write(writer)
230                         },
231                         0xFD...0xFFFF => {
232                                 0xFDu8.write(writer)?;
233                                 (self.0 as u16).write(writer)
234                         },
235                         0x10000...0xFFFFFFFF => {
236                                 0xFEu8.write(writer)?;
237                                 (self.0 as u32).write(writer)
238                         },
239                         _ => {
240                                 0xFFu8.write(writer)?;
241                                 (self.0 as u64).write(writer)
242                         },
243                 }
244         }
245 }
246 impl Readable for BigSize {
247         #[inline]
248         fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
249                 let n: u8 = Readable::read(reader)?;
250                 match n {
251                         0xFF => {
252                                 let x: u64 = Readable::read(reader)?;
253                                 if x < 0x100000000 {
254                                         Err(DecodeError::InvalidValue)
255                                 } else {
256                                         Ok(BigSize(x))
257                                 }
258                         }
259                         0xFE => {
260                                 let x: u32 = Readable::read(reader)?;
261                                 if x < 0x10000 {
262                                         Err(DecodeError::InvalidValue)
263                                 } else {
264                                         Ok(BigSize(x as u64))
265                                 }
266                         }
267                         0xFD => {
268                                 let x: u16 = Readable::read(reader)?;
269                                 if x < 0xFD {
270                                         Err(DecodeError::InvalidValue)
271                                 } else {
272                                         Ok(BigSize(x as u64))
273                                 }
274                         }
275                         n => Ok(BigSize(n as u64))
276                 }
277         }
278 }
279
280 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
281 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
282 /// encapsulates such integers implementing Readable/Writeable for them.
283 #[cfg_attr(test, derive(PartialEq, Debug))]
284 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
285
286 macro_rules! impl_writeable_primitive {
287         ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
288                 impl Writeable for $val_type {
289                         #[inline]
290                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
291                                 writer.write_all(&$meth_write(*self))
292                         }
293                 }
294                 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
295                         #[inline]
296                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
297                                 // Skip any full leading 0 bytes when writing (in BE):
298                                 writer.write_all(&$meth_write(self.0)[(self.0.leading_zeros()/8) as usize..$len])
299                         }
300                 }
301                 impl Readable for $val_type {
302                         #[inline]
303                         fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
304                                 let mut buf = [0; $len];
305                                 reader.read_exact(&mut buf)?;
306                                 Ok($meth_read(&buf))
307                         }
308                 }
309                 impl Readable for HighZeroBytesDroppedVarInt<$val_type> {
310                         #[inline]
311                         fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
312                                 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
313                                 // the high bytes being dropped. To do so, we start reading into the middle of buf
314                                 // and then convert the appropriate number of bytes with extra high bytes out of
315                                 // buf.
316                                 let mut buf = [0; $len*2];
317                                 let mut read_len = reader.read(&mut buf[$len..])?;
318                                 let mut total_read_len = read_len;
319                                 while read_len != 0 && total_read_len != $len {
320                                         read_len = reader.read(&mut buf[($len + total_read_len)..])?;
321                                         total_read_len += read_len;
322                                 }
323                                 if total_read_len == 0 || buf[$len] != 0 {
324                                         let first_byte = $len - ($len - total_read_len);
325                                         Ok(HighZeroBytesDroppedVarInt($meth_read(&buf[first_byte..first_byte + $len])))
326                                 } else {
327                                         // If the encoding had extra zero bytes, return a failure even though we know
328                                         // what they meant (as the TLV test vectors require this)
329                                         Err(DecodeError::InvalidValue)
330                                 }
331                         }
332                 }
333         }
334 }
335
336 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
337 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
338 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
339
340 impl Writeable for u8 {
341         #[inline]
342         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
343                 writer.write_all(&[*self])
344         }
345 }
346 impl Readable for u8 {
347         #[inline]
348         fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
349                 let mut buf = [0; 1];
350                 reader.read_exact(&mut buf)?;
351                 Ok(buf[0])
352         }
353 }
354
355 impl Writeable for bool {
356         #[inline]
357         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
358                 writer.write_all(&[if *self {1} else {0}])
359         }
360 }
361 impl Readable for bool {
362         #[inline]
363         fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
364                 let mut buf = [0; 1];
365                 reader.read_exact(&mut buf)?;
366                 if buf[0] != 0 && buf[0] != 1 {
367                         return Err(DecodeError::InvalidValue);
368                 }
369                 Ok(buf[0] == 1)
370         }
371 }
372
373 // u8 arrays
374 macro_rules! impl_array {
375         ( $size:expr ) => (
376                 impl Writeable for [u8; $size]
377                 {
378                         #[inline]
379                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
380                                 w.write_all(self)
381                         }
382                 }
383
384                 impl Readable for [u8; $size]
385                 {
386                         #[inline]
387                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
388                                 let mut buf = [0u8; $size];
389                                 r.read_exact(&mut buf)?;
390                                 Ok(buf)
391                         }
392                 }
393         );
394 }
395
396 //TODO: performance issue with [u8; size] with impl_array!()
397 impl_array!(3); // for rgb
398 impl_array!(4); // for IPv4
399 impl_array!(10); // for OnionV2
400 impl_array!(16); // for IPv6
401 impl_array!(32); // for channel id & hmac
402 impl_array!(33); // for PublicKey
403 impl_array!(64); // for Signature
404 impl_array!(1300); // for OnionPacket.hop_data
405
406 // HashMap
407 impl<K, V> Writeable for HashMap<K, V>
408         where K: Writeable + Eq + Hash,
409               V: Writeable
410 {
411         #[inline]
412         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
413         (self.len() as u16).write(w)?;
414                 for (key, value) in self.iter() {
415                         key.write(w)?;
416                         value.write(w)?;
417                 }
418                 Ok(())
419         }
420 }
421
422 impl<K, V> Readable for HashMap<K, V>
423         where K: Readable + Eq + Hash,
424               V: Readable
425 {
426         #[inline]
427         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
428                 let len: u16 = Readable::read(r)?;
429                 let mut ret = HashMap::with_capacity(len as usize);
430                 for _ in 0..len {
431                         ret.insert(K::read(r)?, V::read(r)?);
432                 }
433                 Ok(ret)
434         }
435 }
436
437 // Vectors
438 impl Writeable for Vec<u8> {
439         #[inline]
440         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
441                 (self.len() as u16).write(w)?;
442                 w.write_all(&self)
443         }
444 }
445
446 impl Readable for Vec<u8> {
447         #[inline]
448         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
449                 let len: u16 = Readable::read(r)?;
450                 let mut ret = Vec::with_capacity(len as usize);
451                 ret.resize(len as usize, 0);
452                 r.read_exact(&mut ret)?;
453                 Ok(ret)
454         }
455 }
456 impl Writeable for Vec<Signature> {
457         #[inline]
458         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
459                 (self.len() as u16).write(w)?;
460                 for e in self.iter() {
461                         e.write(w)?;
462                 }
463                 Ok(())
464         }
465 }
466
467 impl Readable for Vec<Signature> {
468         #[inline]
469         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
470                 let len: u16 = Readable::read(r)?;
471                 let byte_size = (len as usize)
472                                 .checked_mul(33)
473                                 .ok_or(DecodeError::BadLengthDescriptor)?;
474                 if byte_size > MAX_BUF_SIZE {
475                         return Err(DecodeError::BadLengthDescriptor);
476                 }
477                 let mut ret = Vec::with_capacity(len as usize);
478                 for _ in 0..len { ret.push(Signature::read(r)?); }
479                 Ok(ret)
480         }
481 }
482
483 impl Writeable for Script {
484         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
485                 (self.len() as u16).write(w)?;
486                 w.write_all(self.as_bytes())
487         }
488 }
489
490 impl Readable for Script {
491         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
492                 let len = <u16 as Readable>::read(r)? as usize;
493                 let mut buf = vec![0; len];
494                 r.read_exact(&mut buf)?;
495                 Ok(Script::from(buf))
496         }
497 }
498
499 impl Writeable for PublicKey {
500         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
501                 self.serialize().write(w)
502         }
503 }
504
505 impl Readable for PublicKey {
506         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
507                 let buf: [u8; 33] = Readable::read(r)?;
508                 match PublicKey::from_slice(&buf) {
509                         Ok(key) => Ok(key),
510                         Err(_) => return Err(DecodeError::InvalidValue),
511                 }
512         }
513 }
514
515 impl Writeable for SecretKey {
516         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
517                 let mut ser = [0; 32];
518                 ser.copy_from_slice(&self[..]);
519                 ser.write(w)
520         }
521 }
522
523 impl Readable for SecretKey {
524         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
525                 let buf: [u8; 32] = Readable::read(r)?;
526                 match SecretKey::from_slice(&buf) {
527                         Ok(key) => Ok(key),
528                         Err(_) => return Err(DecodeError::InvalidValue),
529                 }
530         }
531 }
532
533 impl Writeable for Sha256dHash {
534         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
535                 w.write_all(&self[..])
536         }
537 }
538
539 impl Readable for Sha256dHash {
540         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
541                 use bitcoin_hashes::Hash;
542
543                 let buf: [u8; 32] = Readable::read(r)?;
544                 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
545         }
546 }
547
548 impl Writeable for Signature {
549         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
550                 self.serialize_compact().write(w)
551         }
552 }
553
554 impl Readable for Signature {
555         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
556                 let buf: [u8; 64] = Readable::read(r)?;
557                 match Signature::from_compact(&buf) {
558                         Ok(sig) => Ok(sig),
559                         Err(_) => return Err(DecodeError::InvalidValue),
560                 }
561         }
562 }
563
564 impl Writeable for PaymentPreimage {
565         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
566                 self.0.write(w)
567         }
568 }
569
570 impl Readable for PaymentPreimage {
571         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
572                 let buf: [u8; 32] = Readable::read(r)?;
573                 Ok(PaymentPreimage(buf))
574         }
575 }
576
577 impl Writeable for PaymentHash {
578         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
579                 self.0.write(w)
580         }
581 }
582
583 impl Readable for PaymentHash {
584         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
585                 let buf: [u8; 32] = Readable::read(r)?;
586                 Ok(PaymentHash(buf))
587         }
588 }
589
590 impl<T: Writeable> Writeable for Option<T> {
591         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
592                 match *self {
593                         None => 0u8.write(w)?,
594                         Some(ref data) => {
595                                 1u8.write(w)?;
596                                 data.write(w)?;
597                         }
598                 }
599                 Ok(())
600         }
601 }
602
603 impl<T: Readable> Readable for Option<T>
604 {
605         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
606                 match <u8 as Readable>::read(r)? {
607                         0 => Ok(None),
608                         1 => Ok(Some(Readable::read(r)?)),
609                         _ => return Err(DecodeError::InvalidValue),
610                 }
611         }
612 }
613
614 impl Writeable for OutPoint {
615         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
616                 self.txid.write(w)?;
617                 self.vout.write(w)?;
618                 Ok(())
619         }
620 }
621
622 impl Readable for OutPoint {
623         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
624                 let txid = Readable::read(r)?;
625                 let vout = Readable::read(r)?;
626                 Ok(OutPoint {
627                         txid,
628                         vout,
629                 })
630         }
631 }
632
633 macro_rules! impl_consensus_ser {
634         ($bitcoin_type: ty) => {
635                 impl Writeable for $bitcoin_type {
636                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
637                                 match self.consensus_encode(WriterWriteAdaptor(writer)) {
638                                         Ok(_) => Ok(()),
639                                         Err(consensus::encode::Error::Io(e)) => Err(e),
640                                         Err(_) => panic!("We shouldn't get a consensus::encode::Error unless our Write generated an std::io::Error"),
641                                 }
642                         }
643                 }
644
645                 impl Readable for $bitcoin_type {
646                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
647                                 match consensus::encode::Decodable::consensus_decode(r) {
648                                         Ok(t) => Ok(t),
649                                         Err(consensus::encode::Error::Io(ref e)) if e.kind() == ::std::io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
650                                         Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e)),
651                                         Err(_) => Err(DecodeError::InvalidValue),
652                                 }
653                         }
654                 }
655         }
656 }
657 impl_consensus_ser!(Transaction);
658 impl_consensus_ser!(TxOut);
659
660 impl<T: Readable> Readable for Mutex<T> {
661         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
662                 let t: T = Readable::read(r)?;
663                 Ok(Mutex::new(t))
664         }
665 }
666 impl<T: Writeable> Writeable for Mutex<T> {
667         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
668                 self.lock().unwrap().write(w)
669         }
670 }
671
672 impl<A: Readable, B: Readable> Readable for (A, B) {
673         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
674                 let a: A = Readable::read(r)?;
675                 let b: B = Readable::read(r)?;
676                 Ok((a, b))
677         }
678 }
679 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
680         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
681                 self.0.write(w)?;
682                 self.1.write(w)
683         }
684 }