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