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