Do not execute the default_value expr until we need it in TLV deser
[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 io::{self, Read, Write};
15 use io_extras::{copy, sink};
16 use core::hash::Hash;
17 use sync::Mutex;
18 use core::cmp;
19
20 use bitcoin::secp256k1::{PublicKey, SecretKey};
21 use bitcoin::secp256k1::constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE, COMPACT_SIGNATURE_SIZE};
22 use bitcoin::secp256k1::ecdsa::Signature;
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 core::time::Duration;
31 use ln::msgs::DecodeError;
32 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
33
34 use util::byte_utils::{be48_to_array, slice_to_be48};
35
36 /// serialization buffer size
37 pub const MAX_BUF_SIZE: usize = 64 * 1024;
38
39 /// A simplified version of std::io::Write that exists largely for backwards compatibility.
40 /// An impl is provided for any type that also impls std::io::Write.
41 ///
42 /// (C-not exported) as we only export serialization to/from byte arrays instead
43 pub trait Writer {
44         /// Writes the given buf out. See std::io::Write::write_all for more
45         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
46 }
47
48 impl<W: Write> Writer for W {
49         #[inline]
50         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
51                 <Self as io::Write>::write_all(self, buf)
52         }
53 }
54
55 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
56 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
57         #[inline]
58         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
59                 self.0.write_all(buf)
60         }
61         #[inline]
62         fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
63                 self.0.write_all(buf)?;
64                 Ok(buf.len())
65         }
66         #[inline]
67         fn flush(&mut self) -> Result<(), io::Error> {
68                 Ok(())
69         }
70 }
71
72 pub(crate) struct VecWriter(pub Vec<u8>);
73 impl Writer for VecWriter {
74         #[inline]
75         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
76                 self.0.extend_from_slice(buf);
77                 Ok(())
78         }
79 }
80
81 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
82 /// of some data when serialized but don't yet need the full data.
83 pub(crate) struct LengthCalculatingWriter(pub usize);
84 impl Writer for LengthCalculatingWriter {
85         #[inline]
86         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
87                 self.0 += buf.len();
88                 Ok(())
89         }
90 }
91
92 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
93 /// forward to ensure we always consume exactly the fixed length specified.
94 pub(crate) struct FixedLengthReader<R: Read> {
95         read: R,
96         bytes_read: u64,
97         total_bytes: u64,
98 }
99 impl<R: Read> FixedLengthReader<R> {
100         pub fn new(read: R, total_bytes: u64) -> Self {
101                 Self { read, bytes_read: 0, total_bytes }
102         }
103
104         #[inline]
105         pub fn bytes_remain(&mut self) -> bool {
106                 self.bytes_read != self.total_bytes
107         }
108
109         #[inline]
110         pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
111                 copy(self, &mut sink()).unwrap();
112                 if self.bytes_read != self.total_bytes {
113                         Err(DecodeError::ShortRead)
114                 } else {
115                         Ok(())
116                 }
117         }
118 }
119 impl<R: Read> Read for FixedLengthReader<R> {
120         #[inline]
121         fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
122                 if self.total_bytes == self.bytes_read {
123                         Ok(0)
124                 } else {
125                         let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
126                         match self.read.read(&mut dest[0..(read_len as usize)]) {
127                                 Ok(v) => {
128                                         self.bytes_read += v as u64;
129                                         Ok(v)
130                                 },
131                                 Err(e) => Err(e),
132                         }
133                 }
134         }
135 }
136
137 impl<R: Read> LengthRead for FixedLengthReader<R> {
138         #[inline]
139         fn total_bytes(&self) -> u64 {
140                 self.total_bytes
141         }
142 }
143
144 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
145 /// between "EOF reached before we started" and "EOF reached mid-read".
146 pub(crate) struct ReadTrackingReader<R: Read> {
147         read: R,
148         pub have_read: bool,
149 }
150 impl<R: Read> ReadTrackingReader<R> {
151         pub fn new(read: R) -> Self {
152                 Self { read, have_read: false }
153         }
154 }
155 impl<R: Read> Read for ReadTrackingReader<R> {
156         #[inline]
157         fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
158                 match self.read.read(dest) {
159                         Ok(0) => Ok(0),
160                         Ok(len) => {
161                                 self.have_read = true;
162                                 Ok(len)
163                         },
164                         Err(e) => Err(e),
165                 }
166         }
167 }
168
169 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
170 ///
171 /// (C-not exported) as we only export serialization to/from byte arrays instead
172 pub trait Writeable {
173         /// Writes self out to the given Writer
174         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
175
176         /// Writes self out to a Vec<u8>
177         fn encode(&self) -> Vec<u8> {
178                 let mut msg = VecWriter(Vec::new());
179                 self.write(&mut msg).unwrap();
180                 msg.0
181         }
182
183         /// Writes self out to a Vec<u8>
184         #[cfg(test)]
185         fn encode_with_len(&self) -> Vec<u8> {
186                 let mut msg = VecWriter(Vec::new());
187                 0u16.write(&mut msg).unwrap();
188                 self.write(&mut msg).unwrap();
189                 let len = msg.0.len();
190                 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
191                 msg.0
192         }
193
194         /// Gets the length of this object after it has been serialized. This can be overridden to
195         /// optimize cases where we prepend an object with its length.
196         // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
197         #[inline]
198         fn serialized_length(&self) -> usize {
199                 let mut len_calc = LengthCalculatingWriter(0);
200                 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
201                 len_calc.0
202         }
203 }
204
205 impl<'a, T: Writeable> Writeable for &'a T {
206         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
207 }
208
209 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
210 ///
211 /// (C-not exported) as we only export serialization to/from byte arrays instead
212 pub trait Readable
213         where Self: Sized
214 {
215         /// Reads a Self in from the given Read
216         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
217 }
218
219 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
220 /// from a Read given some additional set of arguments which is required to deserialize.
221 ///
222 /// (C-not exported) as we only export serialization to/from byte arrays instead
223 pub trait ReadableArgs<P>
224         where Self: Sized
225 {
226         /// Reads a Self in from the given Read
227         fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
228 }
229
230 /// A std::io::Read that also provides the total bytes available to read.
231 pub(crate) trait LengthRead: Read {
232         /// The total number of bytes available to read.
233         fn total_bytes(&self) -> u64;
234 }
235
236 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
237 /// from a Read given some additional set of arguments which is required to deserialize, requiring
238 /// the implementer to provide the total length of the read.
239 pub(crate) trait LengthReadableArgs<P> where Self: Sized
240 {
241         /// Reads a Self in from the given LengthRead
242         fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
243 }
244
245 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
246 ///
247 /// (C-not exported) as we only export serialization to/from byte arrays instead
248 pub trait MaybeReadable
249         where Self: Sized
250 {
251         /// Reads a Self in from the given Read
252         fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
253 }
254
255 impl<T: Readable> MaybeReadable for T {
256         #[inline]
257         fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
258                 Ok(Some(Readable::read(reader)?))
259         }
260 }
261
262 pub(crate) struct OptionDeserWrapper<T: Readable>(pub Option<T>);
263 impl<T: Readable> Readable for OptionDeserWrapper<T> {
264         #[inline]
265         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
266                 Ok(Self(Some(Readable::read(reader)?)))
267         }
268 }
269 /// When handling default_values, we want to map the default-value T directly
270 /// to a OptionDeserWrapper<T> in a way that works for `field: T = t;` as
271 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
272 impl<T: Readable> From<T> for OptionDeserWrapper<T> {
273         fn from(t: T) -> OptionDeserWrapper<T> { OptionDeserWrapper(Some(t)) }
274 }
275
276 /// Wrapper to write each element of a Vec with no length prefix
277 pub(crate) struct VecWriteWrapper<'a, T: Writeable>(pub &'a Vec<T>);
278 impl<'a, T: Writeable> Writeable for VecWriteWrapper<'a, T> {
279         #[inline]
280         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
281                 for ref v in self.0.iter() {
282                         v.write(writer)?;
283                 }
284                 Ok(())
285         }
286 }
287
288 /// Wrapper to read elements from a given stream until it reaches the end of the stream.
289 pub(crate) struct VecReadWrapper<T>(pub Vec<T>);
290 impl<T: MaybeReadable> Readable for VecReadWrapper<T> {
291         #[inline]
292         fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
293                 let mut values = Vec::new();
294                 loop {
295                         let mut track_read = ReadTrackingReader::new(&mut reader);
296                         match MaybeReadable::read(&mut track_read) {
297                                 Ok(Some(v)) => { values.push(v); },
298                                 Ok(None) => { },
299                                 // If we failed to read any bytes at all, we reached the end of our TLV
300                                 // stream and have simply exhausted all entries.
301                                 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
302                                 Err(e) => return Err(e),
303                         }
304                 }
305                 Ok(Self(values))
306         }
307 }
308
309 pub(crate) struct U48(pub u64);
310 impl Writeable for U48 {
311         #[inline]
312         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
313                 writer.write_all(&be48_to_array(self.0))
314         }
315 }
316 impl Readable for U48 {
317         #[inline]
318         fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
319                 let mut buf = [0; 6];
320                 reader.read_exact(&mut buf)?;
321                 Ok(U48(slice_to_be48(&buf)))
322         }
323 }
324
325 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
326 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
327 ///
328 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
329 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
330 /// you're looking for an example of a variable-length integer to use for your own project, move
331 /// along, this is a rather poor design.
332 pub struct BigSize(pub u64);
333 impl Writeable for BigSize {
334         #[inline]
335         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
336                 match self.0 {
337                         0...0xFC => {
338                                 (self.0 as u8).write(writer)
339                         },
340                         0xFD...0xFFFF => {
341                                 0xFDu8.write(writer)?;
342                                 (self.0 as u16).write(writer)
343                         },
344                         0x10000...0xFFFFFFFF => {
345                                 0xFEu8.write(writer)?;
346                                 (self.0 as u32).write(writer)
347                         },
348                         _ => {
349                                 0xFFu8.write(writer)?;
350                                 (self.0 as u64).write(writer)
351                         },
352                 }
353         }
354 }
355 impl Readable for BigSize {
356         #[inline]
357         fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
358                 let n: u8 = Readable::read(reader)?;
359                 match n {
360                         0xFF => {
361                                 let x: u64 = Readable::read(reader)?;
362                                 if x < 0x100000000 {
363                                         Err(DecodeError::InvalidValue)
364                                 } else {
365                                         Ok(BigSize(x))
366                                 }
367                         }
368                         0xFE => {
369                                 let x: u32 = Readable::read(reader)?;
370                                 if x < 0x10000 {
371                                         Err(DecodeError::InvalidValue)
372                                 } else {
373                                         Ok(BigSize(x as u64))
374                                 }
375                         }
376                         0xFD => {
377                                 let x: u16 = Readable::read(reader)?;
378                                 if x < 0xFD {
379                                         Err(DecodeError::InvalidValue)
380                                 } else {
381                                         Ok(BigSize(x as u64))
382                                 }
383                         }
384                         n => Ok(BigSize(n as u64))
385                 }
386         }
387 }
388
389 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
390 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
391 /// encapsulates such integers implementing Readable/Writeable for them.
392 #[cfg_attr(test, derive(PartialEq, Debug))]
393 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
394
395 macro_rules! impl_writeable_primitive {
396         ($val_type:ty, $len: expr) => {
397                 impl Writeable for $val_type {
398                         #[inline]
399                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
400                                 writer.write_all(&self.to_be_bytes())
401                         }
402                 }
403                 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
404                         #[inline]
405                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
406                                 // Skip any full leading 0 bytes when writing (in BE):
407                                 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
408                         }
409                 }
410                 impl Readable for $val_type {
411                         #[inline]
412                         fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
413                                 let mut buf = [0; $len];
414                                 reader.read_exact(&mut buf)?;
415                                 Ok(<$val_type>::from_be_bytes(buf))
416                         }
417                 }
418                 impl Readable for HighZeroBytesDroppedVarInt<$val_type> {
419                         #[inline]
420                         fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
421                                 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
422                                 // the high bytes being dropped. To do so, we start reading into the middle of buf
423                                 // and then convert the appropriate number of bytes with extra high bytes out of
424                                 // buf.
425                                 let mut buf = [0; $len*2];
426                                 let mut read_len = reader.read(&mut buf[$len..])?;
427                                 let mut total_read_len = read_len;
428                                 while read_len != 0 && total_read_len != $len {
429                                         read_len = reader.read(&mut buf[($len + total_read_len)..])?;
430                                         total_read_len += read_len;
431                                 }
432                                 if total_read_len == 0 || buf[$len] != 0 {
433                                         let first_byte = $len - ($len - total_read_len);
434                                         let mut bytes = [0; $len];
435                                         bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
436                                         Ok(HighZeroBytesDroppedVarInt(<$val_type>::from_be_bytes(bytes)))
437                                 } else {
438                                         // If the encoding had extra zero bytes, return a failure even though we know
439                                         // what they meant (as the TLV test vectors require this)
440                                         Err(DecodeError::InvalidValue)
441                                 }
442                         }
443                 }
444         }
445 }
446
447 impl_writeable_primitive!(u64, 8);
448 impl_writeable_primitive!(u32, 4);
449 impl_writeable_primitive!(u16, 2);
450
451 impl Writeable for u8 {
452         #[inline]
453         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
454                 writer.write_all(&[*self])
455         }
456 }
457 impl Readable for u8 {
458         #[inline]
459         fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
460                 let mut buf = [0; 1];
461                 reader.read_exact(&mut buf)?;
462                 Ok(buf[0])
463         }
464 }
465
466 impl Writeable for bool {
467         #[inline]
468         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
469                 writer.write_all(&[if *self {1} else {0}])
470         }
471 }
472 impl Readable for bool {
473         #[inline]
474         fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
475                 let mut buf = [0; 1];
476                 reader.read_exact(&mut buf)?;
477                 if buf[0] != 0 && buf[0] != 1 {
478                         return Err(DecodeError::InvalidValue);
479                 }
480                 Ok(buf[0] == 1)
481         }
482 }
483
484 // u8 arrays
485 macro_rules! impl_array {
486         ( $size:expr ) => (
487                 impl Writeable for [u8; $size]
488                 {
489                         #[inline]
490                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
491                                 w.write_all(self)
492                         }
493                 }
494
495                 impl Readable for [u8; $size]
496                 {
497                         #[inline]
498                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
499                                 let mut buf = [0u8; $size];
500                                 r.read_exact(&mut buf)?;
501                                 Ok(buf)
502                         }
503                 }
504         );
505 }
506
507 impl_array!(3); // for rgb
508 impl_array!(4); // for IPv4
509 impl_array!(12); // for OnionV2
510 impl_array!(16); // for IPv6
511 impl_array!(32); // for channel id & hmac
512 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
513 impl_array!(COMPACT_SIGNATURE_SIZE); // for Signature
514 impl_array!(1300); // for OnionPacket.hop_data
515
516 // HashMap
517 impl<K, V> Writeable for HashMap<K, V>
518         where K: Writeable + Eq + Hash,
519               V: Writeable
520 {
521         #[inline]
522         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
523         (self.len() as u16).write(w)?;
524                 for (key, value) in self.iter() {
525                         key.write(w)?;
526                         value.write(w)?;
527                 }
528                 Ok(())
529         }
530 }
531
532 impl<K, V> Readable for HashMap<K, V>
533         where K: Readable + Eq + Hash,
534               V: MaybeReadable
535 {
536         #[inline]
537         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
538                 let len: u16 = Readable::read(r)?;
539                 let mut ret = HashMap::with_capacity(len as usize);
540                 for _ in 0..len {
541                         let k = K::read(r)?;
542                         let v_opt = V::read(r)?;
543                         if let Some(v) = v_opt {
544                                 if ret.insert(k, v).is_some() {
545                                         return Err(DecodeError::InvalidValue);
546                                 }
547                         }
548                 }
549                 Ok(ret)
550         }
551 }
552
553 // HashSet
554 impl<T> Writeable for HashSet<T>
555 where T: Writeable + Eq + Hash
556 {
557         #[inline]
558         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
559                 (self.len() as u16).write(w)?;
560                 for item in self.iter() {
561                         item.write(w)?;
562                 }
563                 Ok(())
564         }
565 }
566
567 impl<T> Readable for HashSet<T>
568 where T: Readable + Eq + Hash
569 {
570         #[inline]
571         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
572                 let len: u16 = Readable::read(r)?;
573                 let mut ret = HashSet::with_capacity(len as usize);
574                 for _ in 0..len {
575                         if !ret.insert(T::read(r)?) {
576                                 return Err(DecodeError::InvalidValue)
577                         }
578                 }
579                 Ok(ret)
580         }
581 }
582
583 // Vectors
584 impl Writeable for Vec<u8> {
585         #[inline]
586         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
587                 (self.len() as u16).write(w)?;
588                 w.write_all(&self)
589         }
590 }
591
592 impl Readable for Vec<u8> {
593         #[inline]
594         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
595                 let len: u16 = Readable::read(r)?;
596                 let mut ret = Vec::with_capacity(len as usize);
597                 ret.resize(len as usize, 0);
598                 r.read_exact(&mut ret)?;
599                 Ok(ret)
600         }
601 }
602 impl Writeable for Vec<Signature> {
603         #[inline]
604         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
605                 (self.len() as u16).write(w)?;
606                 for e in self.iter() {
607                         e.write(w)?;
608                 }
609                 Ok(())
610         }
611 }
612
613 impl Readable for Vec<Signature> {
614         #[inline]
615         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
616                 let len: u16 = Readable::read(r)?;
617                 let byte_size = (len as usize)
618                                 .checked_mul(COMPACT_SIGNATURE_SIZE)
619                                 .ok_or(DecodeError::BadLengthDescriptor)?;
620                 if byte_size > MAX_BUF_SIZE {
621                         return Err(DecodeError::BadLengthDescriptor);
622                 }
623                 let mut ret = Vec::with_capacity(len as usize);
624                 for _ in 0..len { ret.push(Readable::read(r)?); }
625                 Ok(ret)
626         }
627 }
628
629 impl Writeable for Script {
630         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
631                 (self.len() as u16).write(w)?;
632                 w.write_all(self.as_bytes())
633         }
634 }
635
636 impl Readable for Script {
637         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
638                 let len = <u16 as Readable>::read(r)? as usize;
639                 let mut buf = vec![0; len];
640                 r.read_exact(&mut buf)?;
641                 Ok(Script::from(buf))
642         }
643 }
644
645 impl Writeable for PublicKey {
646         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
647                 self.serialize().write(w)
648         }
649         #[inline]
650         fn serialized_length(&self) -> usize {
651                 PUBLIC_KEY_SIZE
652         }
653 }
654
655 impl Readable for PublicKey {
656         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
657                 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
658                 match PublicKey::from_slice(&buf) {
659                         Ok(key) => Ok(key),
660                         Err(_) => return Err(DecodeError::InvalidValue),
661                 }
662         }
663 }
664
665 impl Writeable for SecretKey {
666         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
667                 let mut ser = [0; SECRET_KEY_SIZE];
668                 ser.copy_from_slice(&self[..]);
669                 ser.write(w)
670         }
671         #[inline]
672         fn serialized_length(&self) -> usize {
673                 SECRET_KEY_SIZE
674         }
675 }
676
677 impl Readable for SecretKey {
678         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
679                 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
680                 match SecretKey::from_slice(&buf) {
681                         Ok(key) => Ok(key),
682                         Err(_) => return Err(DecodeError::InvalidValue),
683                 }
684         }
685 }
686
687 impl Writeable for Sha256dHash {
688         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
689                 w.write_all(&self[..])
690         }
691 }
692
693 impl Readable for Sha256dHash {
694         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
695                 use bitcoin::hashes::Hash;
696
697                 let buf: [u8; 32] = Readable::read(r)?;
698                 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
699         }
700 }
701
702 impl Writeable for Signature {
703         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
704                 self.serialize_compact().write(w)
705         }
706         #[inline]
707         fn serialized_length(&self) -> usize {
708                 COMPACT_SIGNATURE_SIZE
709         }
710 }
711
712 impl Readable for Signature {
713         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
714                 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
715                 match Signature::from_compact(&buf) {
716                         Ok(sig) => Ok(sig),
717                         Err(_) => return Err(DecodeError::InvalidValue),
718                 }
719         }
720 }
721
722 impl Writeable for PaymentPreimage {
723         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
724                 self.0.write(w)
725         }
726 }
727
728 impl Readable for PaymentPreimage {
729         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
730                 let buf: [u8; 32] = Readable::read(r)?;
731                 Ok(PaymentPreimage(buf))
732         }
733 }
734
735 impl Writeable for PaymentHash {
736         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
737                 self.0.write(w)
738         }
739 }
740
741 impl Readable for PaymentHash {
742         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
743                 let buf: [u8; 32] = Readable::read(r)?;
744                 Ok(PaymentHash(buf))
745         }
746 }
747
748 impl Writeable for PaymentSecret {
749         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
750                 self.0.write(w)
751         }
752 }
753
754 impl Readable for PaymentSecret {
755         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
756                 let buf: [u8; 32] = Readable::read(r)?;
757                 Ok(PaymentSecret(buf))
758         }
759 }
760
761 impl<T: Writeable> Writeable for Box<T> {
762         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
763                 T::write(&**self, w)
764         }
765 }
766
767 impl<T: Readable> Readable for Box<T> {
768         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
769                 Ok(Box::new(Readable::read(r)?))
770         }
771 }
772
773 impl<T: Writeable> Writeable for Option<T> {
774         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
775                 match *self {
776                         None => 0u8.write(w)?,
777                         Some(ref data) => {
778                                 BigSize(data.serialized_length() as u64 + 1).write(w)?;
779                                 data.write(w)?;
780                         }
781                 }
782                 Ok(())
783         }
784 }
785
786 impl<T: Readable> Readable for Option<T>
787 {
788         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
789                 let len: BigSize = Readable::read(r)?;
790                 match len.0 {
791                         0 => Ok(None),
792                         len => {
793                                 let mut reader = FixedLengthReader::new(r, len - 1);
794                                 Ok(Some(Readable::read(&mut reader)?))
795                         }
796                 }
797         }
798 }
799
800 impl Writeable for Txid {
801         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
802                 w.write_all(&self[..])
803         }
804 }
805
806 impl Readable for Txid {
807         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
808                 use bitcoin::hashes::Hash;
809
810                 let buf: [u8; 32] = Readable::read(r)?;
811                 Ok(Txid::from_slice(&buf[..]).unwrap())
812         }
813 }
814
815 impl Writeable for BlockHash {
816         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
817                 w.write_all(&self[..])
818         }
819 }
820
821 impl Readable for BlockHash {
822         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
823                 use bitcoin::hashes::Hash;
824
825                 let buf: [u8; 32] = Readable::read(r)?;
826                 Ok(BlockHash::from_slice(&buf[..]).unwrap())
827         }
828 }
829
830 impl Writeable for OutPoint {
831         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
832                 self.txid.write(w)?;
833                 self.vout.write(w)?;
834                 Ok(())
835         }
836 }
837
838 impl Readable for OutPoint {
839         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
840                 let txid = Readable::read(r)?;
841                 let vout = Readable::read(r)?;
842                 Ok(OutPoint {
843                         txid,
844                         vout,
845                 })
846         }
847 }
848
849 macro_rules! impl_consensus_ser {
850         ($bitcoin_type: ty) => {
851                 impl Writeable for $bitcoin_type {
852                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
853                                 match self.consensus_encode(WriterWriteAdaptor(writer)) {
854                                         Ok(_) => Ok(()),
855                                         Err(e) => Err(e),
856                                 }
857                         }
858                 }
859
860                 impl Readable for $bitcoin_type {
861                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
862                                 match consensus::encode::Decodable::consensus_decode(r) {
863                                         Ok(t) => Ok(t),
864                                         Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
865                                         Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
866                                         Err(_) => Err(DecodeError::InvalidValue),
867                                 }
868                         }
869                 }
870         }
871 }
872 impl_consensus_ser!(Transaction);
873 impl_consensus_ser!(TxOut);
874
875 impl<T: Readable> Readable for Mutex<T> {
876         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
877                 let t: T = Readable::read(r)?;
878                 Ok(Mutex::new(t))
879         }
880 }
881 impl<T: Writeable> Writeable for Mutex<T> {
882         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
883                 self.lock().unwrap().write(w)
884         }
885 }
886
887 impl<A: Readable, B: Readable> Readable for (A, B) {
888         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
889                 let a: A = Readable::read(r)?;
890                 let b: B = Readable::read(r)?;
891                 Ok((a, b))
892         }
893 }
894 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
895         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
896                 self.0.write(w)?;
897                 self.1.write(w)
898         }
899 }
900
901 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
902         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
903                 let a: A = Readable::read(r)?;
904                 let b: B = Readable::read(r)?;
905                 let c: C = Readable::read(r)?;
906                 Ok((a, b, c))
907         }
908 }
909 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
910         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
911                 self.0.write(w)?;
912                 self.1.write(w)?;
913                 self.2.write(w)
914         }
915 }
916
917 impl Writeable for () {
918         fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
919                 Ok(())
920         }
921 }
922 impl Readable for () {
923         fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
924                 Ok(())
925         }
926 }
927
928 impl Writeable for String {
929         #[inline]
930         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
931                 (self.len() as u16).write(w)?;
932                 w.write_all(self.as_bytes())
933         }
934 }
935 impl Readable for String {
936         #[inline]
937         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
938                 let v: Vec<u8> = Readable::read(r)?;
939                 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
940                 Ok(ret)
941         }
942 }
943
944 impl Writeable for Duration {
945         #[inline]
946         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
947                 self.as_secs().write(w)?;
948                 self.subsec_nanos().write(w)
949         }
950 }
951 impl Readable for Duration {
952         #[inline]
953         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
954                 let secs = Readable::read(r)?;
955                 let nanos = Readable::read(r)?;
956                 Ok(Duration::new(secs, nanos))
957         }
958 }