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