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