Drop writer size hinting/message vec preallocation
[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 // Vectors
519 impl Writeable for Vec<u8> {
520         #[inline]
521         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
522                 (self.len() as u16).write(w)?;
523                 w.write_all(&self)
524         }
525 }
526
527 impl Readable for Vec<u8> {
528         #[inline]
529         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
530                 let len: u16 = Readable::read(r)?;
531                 let mut ret = Vec::with_capacity(len as usize);
532                 ret.resize(len as usize, 0);
533                 r.read_exact(&mut ret)?;
534                 Ok(ret)
535         }
536 }
537 impl Writeable for Vec<Signature> {
538         #[inline]
539         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
540                 (self.len() as u16).write(w)?;
541                 for e in self.iter() {
542                         e.write(w)?;
543                 }
544                 Ok(())
545         }
546 }
547
548 impl Readable for Vec<Signature> {
549         #[inline]
550         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
551                 let len: u16 = Readable::read(r)?;
552                 let byte_size = (len as usize)
553                                 .checked_mul(COMPACT_SIGNATURE_SIZE)
554                                 .ok_or(DecodeError::BadLengthDescriptor)?;
555                 if byte_size > MAX_BUF_SIZE {
556                         return Err(DecodeError::BadLengthDescriptor);
557                 }
558                 let mut ret = Vec::with_capacity(len as usize);
559                 for _ in 0..len { ret.push(Readable::read(r)?); }
560                 Ok(ret)
561         }
562 }
563
564 impl Writeable for Script {
565         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
566                 (self.len() as u16).write(w)?;
567                 w.write_all(self.as_bytes())
568         }
569 }
570
571 impl Readable for Script {
572         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
573                 let len = <u16 as Readable>::read(r)? as usize;
574                 let mut buf = vec![0; len];
575                 r.read_exact(&mut buf)?;
576                 Ok(Script::from(buf))
577         }
578 }
579
580 impl Writeable for PublicKey {
581         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
582                 self.serialize().write(w)
583         }
584         #[inline]
585         fn serialized_length(&self) -> usize {
586                 PUBLIC_KEY_SIZE
587         }
588 }
589
590 impl Readable for PublicKey {
591         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
592                 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
593                 match PublicKey::from_slice(&buf) {
594                         Ok(key) => Ok(key),
595                         Err(_) => return Err(DecodeError::InvalidValue),
596                 }
597         }
598 }
599
600 impl Writeable for SecretKey {
601         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
602                 let mut ser = [0; SECRET_KEY_SIZE];
603                 ser.copy_from_slice(&self[..]);
604                 ser.write(w)
605         }
606         #[inline]
607         fn serialized_length(&self) -> usize {
608                 SECRET_KEY_SIZE
609         }
610 }
611
612 impl Readable for SecretKey {
613         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
614                 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
615                 match SecretKey::from_slice(&buf) {
616                         Ok(key) => Ok(key),
617                         Err(_) => return Err(DecodeError::InvalidValue),
618                 }
619         }
620 }
621
622 impl Writeable for Sha256dHash {
623         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
624                 w.write_all(&self[..])
625         }
626 }
627
628 impl Readable for Sha256dHash {
629         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
630                 use bitcoin::hashes::Hash;
631
632                 let buf: [u8; 32] = Readable::read(r)?;
633                 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
634         }
635 }
636
637 impl Writeable for Signature {
638         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
639                 self.serialize_compact().write(w)
640         }
641         #[inline]
642         fn serialized_length(&self) -> usize {
643                 COMPACT_SIGNATURE_SIZE
644         }
645 }
646
647 impl Readable for Signature {
648         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
649                 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
650                 match Signature::from_compact(&buf) {
651                         Ok(sig) => Ok(sig),
652                         Err(_) => return Err(DecodeError::InvalidValue),
653                 }
654         }
655 }
656
657 impl Writeable for PaymentPreimage {
658         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
659                 self.0.write(w)
660         }
661 }
662
663 impl Readable for PaymentPreimage {
664         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
665                 let buf: [u8; 32] = Readable::read(r)?;
666                 Ok(PaymentPreimage(buf))
667         }
668 }
669
670 impl Writeable for PaymentHash {
671         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
672                 self.0.write(w)
673         }
674 }
675
676 impl Readable for PaymentHash {
677         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
678                 let buf: [u8; 32] = Readable::read(r)?;
679                 Ok(PaymentHash(buf))
680         }
681 }
682
683 impl Writeable for PaymentSecret {
684         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
685                 self.0.write(w)
686         }
687 }
688
689 impl Readable for PaymentSecret {
690         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
691                 let buf: [u8; 32] = Readable::read(r)?;
692                 Ok(PaymentSecret(buf))
693         }
694 }
695
696 impl<T: Writeable> Writeable for Box<T> {
697         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
698                 T::write(&**self, w)
699         }
700 }
701
702 impl<T: Readable> Readable for Box<T> {
703         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
704                 Ok(Box::new(Readable::read(r)?))
705         }
706 }
707
708 impl<T: Writeable> Writeable for Option<T> {
709         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
710                 match *self {
711                         None => 0u8.write(w)?,
712                         Some(ref data) => {
713                                 BigSize(data.serialized_length() as u64 + 1).write(w)?;
714                                 data.write(w)?;
715                         }
716                 }
717                 Ok(())
718         }
719 }
720
721 impl<T: Readable> Readable for Option<T>
722 {
723         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
724                 let len: BigSize = Readable::read(r)?;
725                 match len.0 {
726                         0 => Ok(None),
727                         len => {
728                                 let mut reader = FixedLengthReader::new(r, len - 1);
729                                 Ok(Some(Readable::read(&mut reader)?))
730                         }
731                 }
732         }
733 }
734
735 impl Writeable for Txid {
736         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
737                 w.write_all(&self[..])
738         }
739 }
740
741 impl Readable for Txid {
742         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
743                 use bitcoin::hashes::Hash;
744
745                 let buf: [u8; 32] = Readable::read(r)?;
746                 Ok(Txid::from_slice(&buf[..]).unwrap())
747         }
748 }
749
750 impl Writeable for BlockHash {
751         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
752                 w.write_all(&self[..])
753         }
754 }
755
756 impl Readable for BlockHash {
757         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
758                 use bitcoin::hashes::Hash;
759
760                 let buf: [u8; 32] = Readable::read(r)?;
761                 Ok(BlockHash::from_slice(&buf[..]).unwrap())
762         }
763 }
764
765 impl Writeable for OutPoint {
766         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
767                 self.txid.write(w)?;
768                 self.vout.write(w)?;
769                 Ok(())
770         }
771 }
772
773 impl Readable for OutPoint {
774         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
775                 let txid = Readable::read(r)?;
776                 let vout = Readable::read(r)?;
777                 Ok(OutPoint {
778                         txid,
779                         vout,
780                 })
781         }
782 }
783
784 macro_rules! impl_consensus_ser {
785         ($bitcoin_type: ty) => {
786                 impl Writeable for $bitcoin_type {
787                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
788                                 match self.consensus_encode(WriterWriteAdaptor(writer)) {
789                                         Ok(_) => Ok(()),
790                                         Err(e) => Err(e),
791                                 }
792                         }
793                 }
794
795                 impl Readable for $bitcoin_type {
796                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
797                                 match consensus::encode::Decodable::consensus_decode(r) {
798                                         Ok(t) => Ok(t),
799                                         Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
800                                         Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
801                                         Err(_) => Err(DecodeError::InvalidValue),
802                                 }
803                         }
804                 }
805         }
806 }
807 impl_consensus_ser!(Transaction);
808 impl_consensus_ser!(TxOut);
809
810 impl<T: Readable> Readable for Mutex<T> {
811         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
812                 let t: T = Readable::read(r)?;
813                 Ok(Mutex::new(t))
814         }
815 }
816 impl<T: Writeable> Writeable for Mutex<T> {
817         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
818                 self.lock().unwrap().write(w)
819         }
820 }
821
822 impl<A: Readable, B: Readable> Readable for (A, B) {
823         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
824                 let a: A = Readable::read(r)?;
825                 let b: B = Readable::read(r)?;
826                 Ok((a, b))
827         }
828 }
829 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
830         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
831                 self.0.write(w)?;
832                 self.1.write(w)
833         }
834 }
835
836 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
837         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
838                 let a: A = Readable::read(r)?;
839                 let b: B = Readable::read(r)?;
840                 let c: C = Readable::read(r)?;
841                 Ok((a, b, c))
842         }
843 }
844 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
845         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
846                 self.0.write(w)?;
847                 self.1.write(w)?;
848                 self.2.write(w)
849         }
850 }
851
852 impl Readable for () {
853         fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
854                 Ok(())
855         }
856 }