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