7bc09e7f8da00c4bc62c5a9944a1f0f8f3cf2e0d
[rust-lightning] / lightning / src / util / ser.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! A very simple serialization framework which is used to serialize/deserialize messages as well
11 //! as ChannelsManagers and ChannelMonitors.
12
13 use prelude::*;
14 use std::io::{Read, Write};
15 use std::collections::HashMap;
16 use core::hash::Hash;
17 use std::sync::Mutex;
18 use core::cmp;
19
20 use bitcoin::secp256k1::Signature;
21 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
22 use bitcoin::secp256k1::constants::{PUBLIC_KEY_SIZE, 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<(), ::std::io::Error>;
47         /// Hints that data of the given size is about the be written. This may not always be called
48         /// prior to data being written and may be safely ignored.
49         fn size_hint(&mut self, size: usize);
50 }
51
52 impl<W: Write> Writer for W {
53         #[inline]
54         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
55                 <Self as ::std::io::Write>::write_all(self, buf)
56         }
57         #[inline]
58         fn size_hint(&mut self, _size: usize) { }
59 }
60
61 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
62 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
63         #[inline]
64         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
65                 self.0.write_all(buf)
66         }
67         #[inline]
68         fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
69                 self.0.write_all(buf)?;
70                 Ok(buf.len())
71         }
72         #[inline]
73         fn flush(&mut self) -> Result<(), ::std::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<(), ::std::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<(), ::std::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                 ::std::io::copy(self, &mut ::std::io::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, ::std::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, ::std::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<(), ::std::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<(), ::std::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 pub(crate) struct OptionDeserWrapper<T: Readable>(pub Option<T>);
245 impl<T: Readable> Readable for OptionDeserWrapper<T> {
246         #[inline]
247         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
248                 Ok(Self(Some(Readable::read(reader)?)))
249         }
250 }
251
252 const MAX_ALLOC_SIZE: u64 = 64*1024;
253
254 pub(crate) struct VecWriteWrapper<'a, T: Writeable>(pub &'a Vec<T>);
255 impl<'a, T: Writeable> Writeable for VecWriteWrapper<'a, T> {
256         #[inline]
257         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
258                 (self.0.len() as u64).write(writer)?;
259                 for ref v in self.0.iter() {
260                         v.write(writer)?;
261                 }
262                 Ok(())
263         }
264 }
265 pub(crate) struct VecReadWrapper<T: Readable>(pub Vec<T>);
266 impl<T: Readable> Readable for VecReadWrapper<T> {
267         #[inline]
268         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
269                 let count: u64 = Readable::read(reader)?;
270                 let mut values = Vec::with_capacity(cmp::min(count, MAX_ALLOC_SIZE / (core::mem::size_of::<T>() as u64)) as usize);
271                 for _ in 0..count {
272                         match Readable::read(reader) {
273                                 Ok(v) => { values.push(v); },
274                                 Err(e) => return Err(e),
275                         }
276                 }
277                 Ok(Self(values))
278         }
279 }
280
281 pub(crate) struct U48(pub u64);
282 impl Writeable for U48 {
283         #[inline]
284         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
285                 writer.write_all(&be48_to_array(self.0))
286         }
287 }
288 impl Readable for U48 {
289         #[inline]
290         fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
291                 let mut buf = [0; 6];
292                 reader.read_exact(&mut buf)?;
293                 Ok(U48(slice_to_be48(&buf)))
294         }
295 }
296
297 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
298 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
299 ///
300 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
301 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
302 /// you're looking for an example of a variable-length integer to use for your own project, move
303 /// along, this is a rather poor design.
304 pub(crate) struct BigSize(pub u64);
305 impl Writeable for BigSize {
306         #[inline]
307         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
308                 match self.0 {
309                         0...0xFC => {
310                                 (self.0 as u8).write(writer)
311                         },
312                         0xFD...0xFFFF => {
313                                 0xFDu8.write(writer)?;
314                                 (self.0 as u16).write(writer)
315                         },
316                         0x10000...0xFFFFFFFF => {
317                                 0xFEu8.write(writer)?;
318                                 (self.0 as u32).write(writer)
319                         },
320                         _ => {
321                                 0xFFu8.write(writer)?;
322                                 (self.0 as u64).write(writer)
323                         },
324                 }
325         }
326 }
327 impl Readable for BigSize {
328         #[inline]
329         fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
330                 let n: u8 = Readable::read(reader)?;
331                 match n {
332                         0xFF => {
333                                 let x: u64 = Readable::read(reader)?;
334                                 if x < 0x100000000 {
335                                         Err(DecodeError::InvalidValue)
336                                 } else {
337                                         Ok(BigSize(x))
338                                 }
339                         }
340                         0xFE => {
341                                 let x: u32 = Readable::read(reader)?;
342                                 if x < 0x10000 {
343                                         Err(DecodeError::InvalidValue)
344                                 } else {
345                                         Ok(BigSize(x as u64))
346                                 }
347                         }
348                         0xFD => {
349                                 let x: u16 = Readable::read(reader)?;
350                                 if x < 0xFD {
351                                         Err(DecodeError::InvalidValue)
352                                 } else {
353                                         Ok(BigSize(x as u64))
354                                 }
355                         }
356                         n => Ok(BigSize(n as u64))
357                 }
358         }
359 }
360
361 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
362 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
363 /// encapsulates such integers implementing Readable/Writeable for them.
364 #[cfg_attr(test, derive(PartialEq, Debug))]
365 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
366
367 macro_rules! impl_writeable_primitive {
368         ($val_type:ty, $len: expr) => {
369                 impl Writeable for $val_type {
370                         #[inline]
371                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
372                                 writer.write_all(&self.to_be_bytes())
373                         }
374                 }
375                 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
376                         #[inline]
377                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
378                                 // Skip any full leading 0 bytes when writing (in BE):
379                                 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
380                         }
381                 }
382                 impl Readable for $val_type {
383                         #[inline]
384                         fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
385                                 let mut buf = [0; $len];
386                                 reader.read_exact(&mut buf)?;
387                                 Ok(<$val_type>::from_be_bytes(buf))
388                         }
389                 }
390                 impl Readable for HighZeroBytesDroppedVarInt<$val_type> {
391                         #[inline]
392                         fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
393                                 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
394                                 // the high bytes being dropped. To do so, we start reading into the middle of buf
395                                 // and then convert the appropriate number of bytes with extra high bytes out of
396                                 // buf.
397                                 let mut buf = [0; $len*2];
398                                 let mut read_len = reader.read(&mut buf[$len..])?;
399                                 let mut total_read_len = read_len;
400                                 while read_len != 0 && total_read_len != $len {
401                                         read_len = reader.read(&mut buf[($len + total_read_len)..])?;
402                                         total_read_len += read_len;
403                                 }
404                                 if total_read_len == 0 || buf[$len] != 0 {
405                                         let first_byte = $len - ($len - total_read_len);
406                                         let mut bytes = [0; $len];
407                                         bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
408                                         Ok(HighZeroBytesDroppedVarInt(<$val_type>::from_be_bytes(bytes)))
409                                 } else {
410                                         // If the encoding had extra zero bytes, return a failure even though we know
411                                         // what they meant (as the TLV test vectors require this)
412                                         Err(DecodeError::InvalidValue)
413                                 }
414                         }
415                 }
416         }
417 }
418
419 impl_writeable_primitive!(u64, 8);
420 impl_writeable_primitive!(u32, 4);
421 impl_writeable_primitive!(u16, 2);
422
423 impl Writeable for u8 {
424         #[inline]
425         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
426                 writer.write_all(&[*self])
427         }
428 }
429 impl Readable for u8 {
430         #[inline]
431         fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
432                 let mut buf = [0; 1];
433                 reader.read_exact(&mut buf)?;
434                 Ok(buf[0])
435         }
436 }
437
438 impl Writeable for bool {
439         #[inline]
440         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
441                 writer.write_all(&[if *self {1} else {0}])
442         }
443 }
444 impl Readable for bool {
445         #[inline]
446         fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
447                 let mut buf = [0; 1];
448                 reader.read_exact(&mut buf)?;
449                 if buf[0] != 0 && buf[0] != 1 {
450                         return Err(DecodeError::InvalidValue);
451                 }
452                 Ok(buf[0] == 1)
453         }
454 }
455
456 // u8 arrays
457 macro_rules! impl_array {
458         ( $size:expr ) => (
459                 impl Writeable for [u8; $size]
460                 {
461                         #[inline]
462                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
463                                 w.write_all(self)
464                         }
465                 }
466
467                 impl Readable for [u8; $size]
468                 {
469                         #[inline]
470                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
471                                 let mut buf = [0u8; $size];
472                                 r.read_exact(&mut buf)?;
473                                 Ok(buf)
474                         }
475                 }
476         );
477 }
478
479 //TODO: performance issue with [u8; size] with impl_array!()
480 impl_array!(3); // for rgb
481 impl_array!(4); // for IPv4
482 impl_array!(10); // for OnionV2
483 impl_array!(16); // for IPv6
484 impl_array!(32); // for channel id & hmac
485 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
486 impl_array!(COMPACT_SIGNATURE_SIZE); // for Signature
487 impl_array!(1300); // for OnionPacket.hop_data
488
489 // HashMap
490 impl<K, V> Writeable for HashMap<K, V>
491         where K: Writeable + Eq + Hash,
492               V: Writeable
493 {
494         #[inline]
495         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
496         (self.len() as u16).write(w)?;
497                 for (key, value) in self.iter() {
498                         key.write(w)?;
499                         value.write(w)?;
500                 }
501                 Ok(())
502         }
503 }
504
505 impl<K, V> Readable for HashMap<K, V>
506         where K: Readable + Eq + Hash,
507               V: Readable
508 {
509         #[inline]
510         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
511                 let len: u16 = Readable::read(r)?;
512                 let mut ret = HashMap::with_capacity(len as usize);
513                 for _ in 0..len {
514                         ret.insert(K::read(r)?, V::read(r)?);
515                 }
516                 Ok(ret)
517         }
518 }
519
520 // Vectors
521 impl Writeable for Vec<u8> {
522         #[inline]
523         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
524                 (self.len() as u16).write(w)?;
525                 w.write_all(&self)
526         }
527 }
528
529 impl Readable for Vec<u8> {
530         #[inline]
531         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
532                 let len: u16 = Readable::read(r)?;
533                 let mut ret = Vec::with_capacity(len as usize);
534                 ret.resize(len as usize, 0);
535                 r.read_exact(&mut ret)?;
536                 Ok(ret)
537         }
538 }
539 impl Writeable for Vec<Signature> {
540         #[inline]
541         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
542                 (self.len() as u16).write(w)?;
543                 for e in self.iter() {
544                         e.write(w)?;
545                 }
546                 Ok(())
547         }
548 }
549
550 impl Readable for Vec<Signature> {
551         #[inline]
552         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
553                 let len: u16 = Readable::read(r)?;
554                 let byte_size = (len as usize)
555                                 .checked_mul(COMPACT_SIGNATURE_SIZE)
556                                 .ok_or(DecodeError::BadLengthDescriptor)?;
557                 if byte_size > MAX_BUF_SIZE {
558                         return Err(DecodeError::BadLengthDescriptor);
559                 }
560                 let mut ret = Vec::with_capacity(len as usize);
561                 for _ in 0..len { ret.push(Signature::read(r)?); }
562                 Ok(ret)
563         }
564 }
565
566 impl Writeable for Script {
567         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
568                 (self.len() as u16).write(w)?;
569                 w.write_all(self.as_bytes())
570         }
571 }
572
573 impl Readable for Script {
574         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
575                 let len = <u16 as Readable>::read(r)? as usize;
576                 let mut buf = vec![0; len];
577                 r.read_exact(&mut buf)?;
578                 Ok(Script::from(buf))
579         }
580 }
581
582 impl Writeable for PublicKey {
583         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
584                 self.serialize().write(w)
585         }
586         #[inline]
587         fn serialized_length(&self) -> usize {
588                 PUBLIC_KEY_SIZE
589         }
590 }
591
592 impl Readable for PublicKey {
593         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
594                 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
595                 match PublicKey::from_slice(&buf) {
596                         Ok(key) => Ok(key),
597                         Err(_) => return Err(DecodeError::InvalidValue),
598                 }
599         }
600 }
601
602 impl Writeable for SecretKey {
603         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
604                 let mut ser = [0; SECRET_KEY_SIZE];
605                 ser.copy_from_slice(&self[..]);
606                 ser.write(w)
607         }
608         #[inline]
609         fn serialized_length(&self) -> usize {
610                 SECRET_KEY_SIZE
611         }
612 }
613
614 impl Readable for SecretKey {
615         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
616                 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
617                 match SecretKey::from_slice(&buf) {
618                         Ok(key) => Ok(key),
619                         Err(_) => return Err(DecodeError::InvalidValue),
620                 }
621         }
622 }
623
624 impl Writeable for Sha256dHash {
625         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
626                 w.write_all(&self[..])
627         }
628 }
629
630 impl Readable for Sha256dHash {
631         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
632                 use bitcoin::hashes::Hash;
633
634                 let buf: [u8; 32] = Readable::read(r)?;
635                 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
636         }
637 }
638
639 impl Writeable for Signature {
640         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
641                 self.serialize_compact().write(w)
642         }
643         #[inline]
644         fn serialized_length(&self) -> usize {
645                 COMPACT_SIGNATURE_SIZE
646         }
647 }
648
649 impl Readable for Signature {
650         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
651                 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
652                 match Signature::from_compact(&buf) {
653                         Ok(sig) => Ok(sig),
654                         Err(_) => return Err(DecodeError::InvalidValue),
655                 }
656         }
657 }
658
659 impl Writeable for PaymentPreimage {
660         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
661                 self.0.write(w)
662         }
663 }
664
665 impl Readable for PaymentPreimage {
666         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
667                 let buf: [u8; 32] = Readable::read(r)?;
668                 Ok(PaymentPreimage(buf))
669         }
670 }
671
672 impl Writeable for PaymentHash {
673         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
674                 self.0.write(w)
675         }
676 }
677
678 impl Readable for PaymentHash {
679         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
680                 let buf: [u8; 32] = Readable::read(r)?;
681                 Ok(PaymentHash(buf))
682         }
683 }
684
685 impl Writeable for PaymentSecret {
686         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
687                 self.0.write(w)
688         }
689 }
690
691 impl Readable for PaymentSecret {
692         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
693                 let buf: [u8; 32] = Readable::read(r)?;
694                 Ok(PaymentSecret(buf))
695         }
696 }
697
698 impl<T: Writeable> Writeable for Option<T> {
699         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
700                 match *self {
701                         None => 0u8.write(w)?,
702                         Some(ref data) => {
703                                 BigSize(data.serialized_length() as u64 + 1).write(w)?;
704                                 data.write(w)?;
705                         }
706                 }
707                 Ok(())
708         }
709 }
710
711 impl<T: Readable> Readable for Option<T>
712 {
713         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
714                 match BigSize::read(r)?.0 {
715                         0 => Ok(None),
716                         len => {
717                                 let mut reader = FixedLengthReader::new(r, len - 1);
718                                 Ok(Some(Readable::read(&mut reader)?))
719                         }
720                 }
721         }
722 }
723
724 impl Writeable for Txid {
725         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
726                 w.write_all(&self[..])
727         }
728 }
729
730 impl Readable for Txid {
731         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
732                 use bitcoin::hashes::Hash;
733
734                 let buf: [u8; 32] = Readable::read(r)?;
735                 Ok(Txid::from_slice(&buf[..]).unwrap())
736         }
737 }
738
739 impl Writeable for BlockHash {
740         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
741                 w.write_all(&self[..])
742         }
743 }
744
745 impl Readable for BlockHash {
746         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
747                 use bitcoin::hashes::Hash;
748
749                 let buf: [u8; 32] = Readable::read(r)?;
750                 Ok(BlockHash::from_slice(&buf[..]).unwrap())
751         }
752 }
753
754 impl Writeable for OutPoint {
755         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
756                 self.txid.write(w)?;
757                 self.vout.write(w)?;
758                 Ok(())
759         }
760 }
761
762 impl Readable for OutPoint {
763         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
764                 let txid = Readable::read(r)?;
765                 let vout = Readable::read(r)?;
766                 Ok(OutPoint {
767                         txid,
768                         vout,
769                 })
770         }
771 }
772
773 macro_rules! impl_consensus_ser {
774         ($bitcoin_type: ty) => {
775                 impl Writeable for $bitcoin_type {
776                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
777                                 match self.consensus_encode(WriterWriteAdaptor(writer)) {
778                                         Ok(_) => Ok(()),
779                                         Err(e) => Err(e),
780                                 }
781                         }
782                 }
783
784                 impl Readable for $bitcoin_type {
785                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
786                                 match consensus::encode::Decodable::consensus_decode(r) {
787                                         Ok(t) => Ok(t),
788                                         Err(consensus::encode::Error::Io(ref e)) if e.kind() == ::std::io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
789                                         Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
790                                         Err(_) => Err(DecodeError::InvalidValue),
791                                 }
792                         }
793                 }
794         }
795 }
796 impl_consensus_ser!(Transaction);
797 impl_consensus_ser!(TxOut);
798
799 impl<T: Readable> Readable for Mutex<T> {
800         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
801                 let t: T = Readable::read(r)?;
802                 Ok(Mutex::new(t))
803         }
804 }
805 impl<T: Writeable> Writeable for Mutex<T> {
806         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
807                 self.lock().unwrap().write(w)
808         }
809 }
810
811 impl<A: Readable, B: Readable> Readable for (A, B) {
812         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
813                 let a: A = Readable::read(r)?;
814                 let b: B = Readable::read(r)?;
815                 Ok((a, b))
816         }
817 }
818 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
819         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
820                 self.0.write(w)?;
821                 self.1.write(w)
822         }
823 }