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