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