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