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