Impl (de)serialization for bitcoin::Transaction.
[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};
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<R>
177         where Self: Sized,
178               R: Read
179 {
180         /// Reads a Self in from the given Read
181         fn read(reader: &mut R) -> Result<Self, DecodeError>;
182 }
183
184 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
185 /// from a Read given some additional set of arguments which is required to deserialize.
186 pub trait ReadableArgs<R, P>
187         where Self: Sized,
188               R: Read
189 {
190         /// Reads a Self in from the given Read
191         fn read(reader: &mut R, params: P) -> Result<Self, DecodeError>;
192 }
193
194 pub(crate) struct U48(pub u64);
195 impl Writeable for U48 {
196         #[inline]
197         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
198                 writer.write_all(&be48_to_array(self.0))
199         }
200 }
201 impl<R: Read> Readable<R> for U48 {
202         #[inline]
203         fn read(reader: &mut R) -> Result<U48, DecodeError> {
204                 let mut buf = [0; 6];
205                 reader.read_exact(&mut buf)?;
206                 Ok(U48(slice_to_be48(&buf)))
207         }
208 }
209
210 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
211 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
212 ///
213 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
214 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
215 /// you're looking for an example of a variable-length integer to use for your own project, move
216 /// along, this is a rather poor design.
217 pub(crate) struct BigSize(pub u64);
218 impl Writeable for BigSize {
219         #[inline]
220         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
221                 match self.0 {
222                         0...0xFC => {
223                                 (self.0 as u8).write(writer)
224                         },
225                         0xFD...0xFFFF => {
226                                 0xFDu8.write(writer)?;
227                                 (self.0 as u16).write(writer)
228                         },
229                         0x10000...0xFFFFFFFF => {
230                                 0xFEu8.write(writer)?;
231                                 (self.0 as u32).write(writer)
232                         },
233                         _ => {
234                                 0xFFu8.write(writer)?;
235                                 (self.0 as u64).write(writer)
236                         },
237                 }
238         }
239 }
240 impl<R: Read> Readable<R> for BigSize {
241         #[inline]
242         fn read(reader: &mut R) -> Result<BigSize, DecodeError> {
243                 let n: u8 = Readable::read(reader)?;
244                 match n {
245                         0xFF => {
246                                 let x: u64 = Readable::read(reader)?;
247                                 if x < 0x100000000 {
248                                         Err(DecodeError::InvalidValue)
249                                 } else {
250                                         Ok(BigSize(x))
251                                 }
252                         }
253                         0xFE => {
254                                 let x: u32 = Readable::read(reader)?;
255                                 if x < 0x10000 {
256                                         Err(DecodeError::InvalidValue)
257                                 } else {
258                                         Ok(BigSize(x as u64))
259                                 }
260                         }
261                         0xFD => {
262                                 let x: u16 = Readable::read(reader)?;
263                                 if x < 0xFD {
264                                         Err(DecodeError::InvalidValue)
265                                 } else {
266                                         Ok(BigSize(x as u64))
267                                 }
268                         }
269                         n => Ok(BigSize(n as u64))
270                 }
271         }
272 }
273
274 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
275 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
276 /// encapsulates such integers implementing Readable/Writeable for them.
277 #[cfg_attr(test, derive(PartialEq, Debug))]
278 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
279
280 macro_rules! impl_writeable_primitive {
281         ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
282                 impl Writeable for $val_type {
283                         #[inline]
284                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
285                                 writer.write_all(&$meth_write(*self))
286                         }
287                 }
288                 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
289                         #[inline]
290                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
291                                 // Skip any full leading 0 bytes when writing (in BE):
292                                 writer.write_all(&$meth_write(self.0)[(self.0.leading_zeros()/8) as usize..$len])
293                         }
294                 }
295                 impl<R: Read> Readable<R> for $val_type {
296                         #[inline]
297                         fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
298                                 let mut buf = [0; $len];
299                                 reader.read_exact(&mut buf)?;
300                                 Ok($meth_read(&buf))
301                         }
302                 }
303                 impl<R: Read> Readable<R> for HighZeroBytesDroppedVarInt<$val_type> {
304                         #[inline]
305                         fn read(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
306                                 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
307                                 // the high bytes being dropped. To do so, we start reading into the middle of buf
308                                 // and then convert the appropriate number of bytes with extra high bytes out of
309                                 // buf.
310                                 let mut buf = [0; $len*2];
311                                 let mut read_len = reader.read(&mut buf[$len..])?;
312                                 let mut total_read_len = read_len;
313                                 while read_len != 0 && total_read_len != $len {
314                                         read_len = reader.read(&mut buf[($len + total_read_len)..])?;
315                                         total_read_len += read_len;
316                                 }
317                                 if total_read_len == 0 || buf[$len] != 0 {
318                                         let first_byte = $len - ($len - total_read_len);
319                                         Ok(HighZeroBytesDroppedVarInt($meth_read(&buf[first_byte..first_byte + $len])))
320                                 } else {
321                                         // If the encoding had extra zero bytes, return a failure even though we know
322                                         // what they meant (as the TLV test vectors require this)
323                                         Err(DecodeError::InvalidValue)
324                                 }
325                         }
326                 }
327         }
328 }
329
330 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
331 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
332 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
333
334 impl Writeable for u8 {
335         #[inline]
336         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
337                 writer.write_all(&[*self])
338         }
339 }
340 impl<R: Read> Readable<R> for u8 {
341         #[inline]
342         fn read(reader: &mut R) -> Result<u8, DecodeError> {
343                 let mut buf = [0; 1];
344                 reader.read_exact(&mut buf)?;
345                 Ok(buf[0])
346         }
347 }
348
349 impl Writeable for bool {
350         #[inline]
351         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
352                 writer.write_all(&[if *self {1} else {0}])
353         }
354 }
355 impl<R: Read> Readable<R> for bool {
356         #[inline]
357         fn read(reader: &mut R) -> Result<bool, DecodeError> {
358                 let mut buf = [0; 1];
359                 reader.read_exact(&mut buf)?;
360                 if buf[0] != 0 && buf[0] != 1 {
361                         return Err(DecodeError::InvalidValue);
362                 }
363                 Ok(buf[0] == 1)
364         }
365 }
366
367 // u8 arrays
368 macro_rules! impl_array {
369         ( $size:expr ) => (
370                 impl Writeable for [u8; $size]
371                 {
372                         #[inline]
373                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
374                                 w.write_all(self)
375                         }
376                 }
377
378                 impl<R: Read> Readable<R> for [u8; $size]
379                 {
380                         #[inline]
381                         fn read(r: &mut R) -> Result<Self, DecodeError> {
382                                 let mut buf = [0u8; $size];
383                                 r.read_exact(&mut buf)?;
384                                 Ok(buf)
385                         }
386                 }
387         );
388 }
389
390 //TODO: performance issue with [u8; size] with impl_array!()
391 impl_array!(3); // for rgb
392 impl_array!(4); // for IPv4
393 impl_array!(10); // for OnionV2
394 impl_array!(16); // for IPv6
395 impl_array!(32); // for channel id & hmac
396 impl_array!(33); // for PublicKey
397 impl_array!(64); // for Signature
398 impl_array!(1300); // for OnionPacket.hop_data
399
400 // HashMap
401 impl<K, V> Writeable for HashMap<K, V>
402         where K: Writeable + Eq + Hash,
403               V: Writeable
404 {
405         #[inline]
406         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
407         (self.len() as u16).write(w)?;
408                 for (key, value) in self.iter() {
409                         key.write(w)?;
410                         value.write(w)?;
411                 }
412                 Ok(())
413         }
414 }
415
416 impl<R, K, V> Readable<R> for HashMap<K, V>
417         where R: Read,
418               K: Readable<R> + Eq + Hash,
419               V: Readable<R>
420 {
421         #[inline]
422         fn read(r: &mut R) -> Result<Self, DecodeError> {
423                 let len: u16 = Readable::read(r)?;
424                 let mut ret = HashMap::with_capacity(len as usize);
425                 for _ in 0..len {
426                         ret.insert(K::read(r)?, V::read(r)?);
427                 }
428                 Ok(ret)
429         }
430 }
431
432 // Vectors
433 impl Writeable for Vec<u8> {
434         #[inline]
435         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
436                 (self.len() as u16).write(w)?;
437                 w.write_all(&self)
438         }
439 }
440
441 impl<R: Read> Readable<R> for Vec<u8> {
442         #[inline]
443         fn read(r: &mut R) -> Result<Self, DecodeError> {
444                 let len: u16 = Readable::read(r)?;
445                 let mut ret = Vec::with_capacity(len as usize);
446                 ret.resize(len as usize, 0);
447                 r.read_exact(&mut ret)?;
448                 Ok(ret)
449         }
450 }
451 impl Writeable for Vec<Signature> {
452         #[inline]
453         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
454                 (self.len() as u16).write(w)?;
455                 for e in self.iter() {
456                         e.write(w)?;
457                 }
458                 Ok(())
459         }
460 }
461
462 impl<R: Read> Readable<R> for Vec<Signature> {
463         #[inline]
464         fn read(r: &mut R) -> Result<Self, DecodeError> {
465                 let len: u16 = Readable::read(r)?;
466                 let byte_size = (len as usize)
467                                 .checked_mul(33)
468                                 .ok_or(DecodeError::BadLengthDescriptor)?;
469                 if byte_size > MAX_BUF_SIZE {
470                         return Err(DecodeError::BadLengthDescriptor);
471                 }
472                 let mut ret = Vec::with_capacity(len as usize);
473                 for _ in 0..len { ret.push(Signature::read(r)?); }
474                 Ok(ret)
475         }
476 }
477
478 impl Writeable for Script {
479         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
480                 (self.len() as u16).write(w)?;
481                 w.write_all(self.as_bytes())
482         }
483 }
484
485 impl<R: Read> Readable<R> for Script {
486         fn read(r: &mut R) -> Result<Self, DecodeError> {
487                 let len = <u16 as Readable<R>>::read(r)? as usize;
488                 let mut buf = vec![0; len];
489                 r.read_exact(&mut buf)?;
490                 Ok(Script::from(buf))
491         }
492 }
493
494 impl Writeable for PublicKey {
495         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
496                 self.serialize().write(w)
497         }
498 }
499
500 impl<R: Read> Readable<R> for PublicKey {
501         fn read(r: &mut R) -> Result<Self, DecodeError> {
502                 let buf: [u8; 33] = Readable::read(r)?;
503                 match PublicKey::from_slice(&buf) {
504                         Ok(key) => Ok(key),
505                         Err(_) => return Err(DecodeError::InvalidValue),
506                 }
507         }
508 }
509
510 impl Writeable for SecretKey {
511         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
512                 let mut ser = [0; 32];
513                 ser.copy_from_slice(&self[..]);
514                 ser.write(w)
515         }
516 }
517
518 impl<R: Read> Readable<R> for SecretKey {
519         fn read(r: &mut R) -> Result<Self, DecodeError> {
520                 let buf: [u8; 32] = Readable::read(r)?;
521                 match SecretKey::from_slice(&buf) {
522                         Ok(key) => Ok(key),
523                         Err(_) => return Err(DecodeError::InvalidValue),
524                 }
525         }
526 }
527
528 impl Writeable for Sha256dHash {
529         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
530                 w.write_all(&self[..])
531         }
532 }
533
534 impl<R: Read> Readable<R> for Sha256dHash {
535         fn read(r: &mut R) -> Result<Self, DecodeError> {
536                 use bitcoin_hashes::Hash;
537
538                 let buf: [u8; 32] = Readable::read(r)?;
539                 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
540         }
541 }
542
543 impl Writeable for Signature {
544         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
545                 self.serialize_compact().write(w)
546         }
547 }
548
549 impl<R: Read> Readable<R> for Signature {
550         fn read(r: &mut R) -> Result<Self, DecodeError> {
551                 let buf: [u8; 64] = Readable::read(r)?;
552                 match Signature::from_compact(&buf) {
553                         Ok(sig) => Ok(sig),
554                         Err(_) => return Err(DecodeError::InvalidValue),
555                 }
556         }
557 }
558
559 impl Writeable for PaymentPreimage {
560         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
561                 self.0.write(w)
562         }
563 }
564
565 impl<R: Read> Readable<R> for PaymentPreimage {
566         fn read(r: &mut R) -> Result<Self, DecodeError> {
567                 let buf: [u8; 32] = Readable::read(r)?;
568                 Ok(PaymentPreimage(buf))
569         }
570 }
571
572 impl Writeable for PaymentHash {
573         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
574                 self.0.write(w)
575         }
576 }
577
578 impl<R: Read> Readable<R> for PaymentHash {
579         fn read(r: &mut R) -> Result<Self, DecodeError> {
580                 let buf: [u8; 32] = Readable::read(r)?;
581                 Ok(PaymentHash(buf))
582         }
583 }
584
585 impl<T: Writeable> Writeable for Option<T> {
586         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
587                 match *self {
588                         None => 0u8.write(w)?,
589                         Some(ref data) => {
590                                 1u8.write(w)?;
591                                 data.write(w)?;
592                         }
593                 }
594                 Ok(())
595         }
596 }
597
598 impl<R, T> Readable<R> for Option<T>
599         where R: Read,
600               T: Readable<R>
601 {
602         fn read(r: &mut R) -> Result<Self, DecodeError> {
603                 match <u8 as Readable<R>>::read(r)? {
604                         0 => Ok(None),
605                         1 => Ok(Some(Readable::read(r)?)),
606                         _ => return Err(DecodeError::InvalidValue),
607                 }
608         }
609 }
610
611 impl Writeable for OutPoint {
612         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
613                 self.txid.write(w)?;
614                 self.vout.write(w)?;
615                 Ok(())
616         }
617 }
618
619 impl<R: Read> Readable<R> for OutPoint {
620         fn read(r: &mut R) -> Result<Self, DecodeError> {
621                 let txid = Readable::read(r)?;
622                 let vout = Readable::read(r)?;
623                 Ok(OutPoint {
624                         txid,
625                         vout,
626                 })
627         }
628 }
629
630 impl Writeable for Transaction {
631         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
632                 match self.consensus_encode(WriterWriteAdaptor(writer)) {
633                         Ok(_) => Ok(()),
634                         Err(consensus::encode::Error::Io(e)) => Err(e),
635                         Err(_) => panic!("We shouldn't get a consensus::encode::Error unless our Write generated an std::io::Error"),
636                 }
637         }
638 }
639
640 impl<R: Read> Readable<R> for Transaction {
641         fn read(r: &mut R) -> Result<Self, DecodeError> {
642                 match consensus::encode::Decodable::consensus_decode(r) {
643                         Ok(t) => Ok(t),
644                         Err(consensus::encode::Error::Io(ref e)) if e.kind() == ::std::io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
645                         Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e)),
646                         Err(_) => Err(DecodeError::InvalidValue),
647                 }
648         }
649 }
650
651 impl<R: Read, T: Readable<R>> Readable<R> for Mutex<T> {
652         fn read(r: &mut R) -> Result<Self, DecodeError> {
653                 let t: T = Readable::read(r)?;
654                 Ok(Mutex::new(t))
655         }
656 }
657 impl<T: Writeable> Writeable for Mutex<T> {
658         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
659                 self.lock().unwrap().write(w)
660         }
661 }
662
663 impl<R: Read, A: Readable<R>, B: Readable<R>> Readable<R> for (A, B) {
664         fn read(r: &mut R) -> Result<Self, DecodeError> {
665                 let a: A = Readable::read(r)?;
666                 let b: B = Readable::read(r)?;
667                 Ok((a, b))
668         }
669 }
670 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
671         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
672                 self.0.write(w)?;
673                 self.1.write(w)
674         }
675 }