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