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