Merge pull request #1553 from wvanlint/dns_hostname
[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
272 /// Wrapper to write each element of a Vec with no length prefix
273 pub(crate) struct VecWriteWrapper<'a, T: Writeable>(pub &'a Vec<T>);
274 impl<'a, T: Writeable> Writeable for VecWriteWrapper<'a, T> {
275         #[inline]
276         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
277                 for ref v in self.0.iter() {
278                         v.write(writer)?;
279                 }
280                 Ok(())
281         }
282 }
283
284 /// Wrapper to read elements from a given stream until it reaches the end of the stream.
285 pub(crate) struct VecReadWrapper<T>(pub Vec<T>);
286 impl<T: MaybeReadable> Readable for VecReadWrapper<T> {
287         #[inline]
288         fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
289                 let mut values = Vec::new();
290                 loop {
291                         let mut track_read = ReadTrackingReader::new(&mut reader);
292                         match MaybeReadable::read(&mut track_read) {
293                                 Ok(Some(v)) => { values.push(v); },
294                                 Ok(None) => { },
295                                 // If we failed to read any bytes at all, we reached the end of our TLV
296                                 // stream and have simply exhausted all entries.
297                                 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
298                                 Err(e) => return Err(e),
299                         }
300                 }
301                 Ok(Self(values))
302         }
303 }
304
305 pub(crate) struct U48(pub u64);
306 impl Writeable for U48 {
307         #[inline]
308         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
309                 writer.write_all(&be48_to_array(self.0))
310         }
311 }
312 impl Readable for U48 {
313         #[inline]
314         fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
315                 let mut buf = [0; 6];
316                 reader.read_exact(&mut buf)?;
317                 Ok(U48(slice_to_be48(&buf)))
318         }
319 }
320
321 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
322 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
323 ///
324 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
325 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
326 /// you're looking for an example of a variable-length integer to use for your own project, move
327 /// along, this is a rather poor design.
328 pub struct BigSize(pub u64);
329 impl Writeable for BigSize {
330         #[inline]
331         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
332                 match self.0 {
333                         0...0xFC => {
334                                 (self.0 as u8).write(writer)
335                         },
336                         0xFD...0xFFFF => {
337                                 0xFDu8.write(writer)?;
338                                 (self.0 as u16).write(writer)
339                         },
340                         0x10000...0xFFFFFFFF => {
341                                 0xFEu8.write(writer)?;
342                                 (self.0 as u32).write(writer)
343                         },
344                         _ => {
345                                 0xFFu8.write(writer)?;
346                                 (self.0 as u64).write(writer)
347                         },
348                 }
349         }
350 }
351 impl Readable for BigSize {
352         #[inline]
353         fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
354                 let n: u8 = Readable::read(reader)?;
355                 match n {
356                         0xFF => {
357                                 let x: u64 = Readable::read(reader)?;
358                                 if x < 0x100000000 {
359                                         Err(DecodeError::InvalidValue)
360                                 } else {
361                                         Ok(BigSize(x))
362                                 }
363                         }
364                         0xFE => {
365                                 let x: u32 = Readable::read(reader)?;
366                                 if x < 0x10000 {
367                                         Err(DecodeError::InvalidValue)
368                                 } else {
369                                         Ok(BigSize(x as u64))
370                                 }
371                         }
372                         0xFD => {
373                                 let x: u16 = Readable::read(reader)?;
374                                 if x < 0xFD {
375                                         Err(DecodeError::InvalidValue)
376                                 } else {
377                                         Ok(BigSize(x as u64))
378                                 }
379                         }
380                         n => Ok(BigSize(n as u64))
381                 }
382         }
383 }
384
385 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
386 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
387 /// encapsulates such integers implementing Readable/Writeable for them.
388 #[cfg_attr(test, derive(PartialEq, Debug))]
389 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
390
391 macro_rules! impl_writeable_primitive {
392         ($val_type:ty, $len: expr) => {
393                 impl Writeable for $val_type {
394                         #[inline]
395                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
396                                 writer.write_all(&self.to_be_bytes())
397                         }
398                 }
399                 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
400                         #[inline]
401                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
402                                 // Skip any full leading 0 bytes when writing (in BE):
403                                 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
404                         }
405                 }
406                 impl Readable for $val_type {
407                         #[inline]
408                         fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
409                                 let mut buf = [0; $len];
410                                 reader.read_exact(&mut buf)?;
411                                 Ok(<$val_type>::from_be_bytes(buf))
412                         }
413                 }
414                 impl Readable for HighZeroBytesDroppedVarInt<$val_type> {
415                         #[inline]
416                         fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
417                                 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
418                                 // the high bytes being dropped. To do so, we start reading into the middle of buf
419                                 // and then convert the appropriate number of bytes with extra high bytes out of
420                                 // buf.
421                                 let mut buf = [0; $len*2];
422                                 let mut read_len = reader.read(&mut buf[$len..])?;
423                                 let mut total_read_len = read_len;
424                                 while read_len != 0 && total_read_len != $len {
425                                         read_len = reader.read(&mut buf[($len + total_read_len)..])?;
426                                         total_read_len += read_len;
427                                 }
428                                 if total_read_len == 0 || buf[$len] != 0 {
429                                         let first_byte = $len - ($len - total_read_len);
430                                         let mut bytes = [0; $len];
431                                         bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
432                                         Ok(HighZeroBytesDroppedVarInt(<$val_type>::from_be_bytes(bytes)))
433                                 } else {
434                                         // If the encoding had extra zero bytes, return a failure even though we know
435                                         // what they meant (as the TLV test vectors require this)
436                                         Err(DecodeError::InvalidValue)
437                                 }
438                         }
439                 }
440         }
441 }
442
443 impl_writeable_primitive!(u64, 8);
444 impl_writeable_primitive!(u32, 4);
445 impl_writeable_primitive!(u16, 2);
446
447 impl Writeable for u8 {
448         #[inline]
449         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
450                 writer.write_all(&[*self])
451         }
452 }
453 impl Readable for u8 {
454         #[inline]
455         fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
456                 let mut buf = [0; 1];
457                 reader.read_exact(&mut buf)?;
458                 Ok(buf[0])
459         }
460 }
461
462 impl Writeable for bool {
463         #[inline]
464         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
465                 writer.write_all(&[if *self {1} else {0}])
466         }
467 }
468 impl Readable for bool {
469         #[inline]
470         fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
471                 let mut buf = [0; 1];
472                 reader.read_exact(&mut buf)?;
473                 if buf[0] != 0 && buf[0] != 1 {
474                         return Err(DecodeError::InvalidValue);
475                 }
476                 Ok(buf[0] == 1)
477         }
478 }
479
480 // u8 arrays
481 macro_rules! impl_array {
482         ( $size:expr ) => (
483                 impl Writeable for [u8; $size]
484                 {
485                         #[inline]
486                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
487                                 w.write_all(self)
488                         }
489                 }
490
491                 impl Readable for [u8; $size]
492                 {
493                         #[inline]
494                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
495                                 let mut buf = [0u8; $size];
496                                 r.read_exact(&mut buf)?;
497                                 Ok(buf)
498                         }
499                 }
500         );
501 }
502
503 impl_array!(3); // for rgb
504 impl_array!(4); // for IPv4
505 impl_array!(12); // for OnionV2
506 impl_array!(16); // for IPv6
507 impl_array!(32); // for channel id & hmac
508 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
509 impl_array!(COMPACT_SIGNATURE_SIZE); // for Signature
510 impl_array!(1300); // for OnionPacket.hop_data
511
512 // HashMap
513 impl<K, V> Writeable for HashMap<K, V>
514         where K: Writeable + Eq + Hash,
515               V: Writeable
516 {
517         #[inline]
518         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
519         (self.len() as u16).write(w)?;
520                 for (key, value) in self.iter() {
521                         key.write(w)?;
522                         value.write(w)?;
523                 }
524                 Ok(())
525         }
526 }
527
528 impl<K, V> Readable for HashMap<K, V>
529         where K: Readable + Eq + Hash,
530               V: MaybeReadable
531 {
532         #[inline]
533         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
534                 let len: u16 = Readable::read(r)?;
535                 let mut ret = HashMap::with_capacity(len as usize);
536                 for _ in 0..len {
537                         let k = K::read(r)?;
538                         let v_opt = V::read(r)?;
539                         if let Some(v) = v_opt {
540                                 if ret.insert(k, v).is_some() {
541                                         return Err(DecodeError::InvalidValue);
542                                 }
543                         }
544                 }
545                 Ok(ret)
546         }
547 }
548
549 // HashSet
550 impl<T> Writeable for HashSet<T>
551 where T: Writeable + Eq + Hash
552 {
553         #[inline]
554         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
555                 (self.len() as u16).write(w)?;
556                 for item in self.iter() {
557                         item.write(w)?;
558                 }
559                 Ok(())
560         }
561 }
562
563 impl<T> Readable for HashSet<T>
564 where T: Readable + Eq + Hash
565 {
566         #[inline]
567         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
568                 let len: u16 = Readable::read(r)?;
569                 let mut ret = HashSet::with_capacity(len as usize);
570                 for _ in 0..len {
571                         if !ret.insert(T::read(r)?) {
572                                 return Err(DecodeError::InvalidValue)
573                         }
574                 }
575                 Ok(ret)
576         }
577 }
578
579 // Vectors
580 impl Writeable for Vec<u8> {
581         #[inline]
582         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
583                 (self.len() as u16).write(w)?;
584                 w.write_all(&self)
585         }
586 }
587
588 impl Readable for Vec<u8> {
589         #[inline]
590         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
591                 let len: u16 = Readable::read(r)?;
592                 let mut ret = Vec::with_capacity(len as usize);
593                 ret.resize(len as usize, 0);
594                 r.read_exact(&mut ret)?;
595                 Ok(ret)
596         }
597 }
598 impl Writeable for Vec<Signature> {
599         #[inline]
600         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
601                 (self.len() as u16).write(w)?;
602                 for e in self.iter() {
603                         e.write(w)?;
604                 }
605                 Ok(())
606         }
607 }
608
609 impl Readable for Vec<Signature> {
610         #[inline]
611         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
612                 let len: u16 = Readable::read(r)?;
613                 let byte_size = (len as usize)
614                                 .checked_mul(COMPACT_SIGNATURE_SIZE)
615                                 .ok_or(DecodeError::BadLengthDescriptor)?;
616                 if byte_size > MAX_BUF_SIZE {
617                         return Err(DecodeError::BadLengthDescriptor);
618                 }
619                 let mut ret = Vec::with_capacity(len as usize);
620                 for _ in 0..len { ret.push(Readable::read(r)?); }
621                 Ok(ret)
622         }
623 }
624
625 impl Writeable for Script {
626         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
627                 (self.len() as u16).write(w)?;
628                 w.write_all(self.as_bytes())
629         }
630 }
631
632 impl Readable for Script {
633         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
634                 let len = <u16 as Readable>::read(r)? as usize;
635                 let mut buf = vec![0; len];
636                 r.read_exact(&mut buf)?;
637                 Ok(Script::from(buf))
638         }
639 }
640
641 impl Writeable for PublicKey {
642         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
643                 self.serialize().write(w)
644         }
645         #[inline]
646         fn serialized_length(&self) -> usize {
647                 PUBLIC_KEY_SIZE
648         }
649 }
650
651 impl Readable for PublicKey {
652         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
653                 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
654                 match PublicKey::from_slice(&buf) {
655                         Ok(key) => Ok(key),
656                         Err(_) => return Err(DecodeError::InvalidValue),
657                 }
658         }
659 }
660
661 impl Writeable for SecretKey {
662         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
663                 let mut ser = [0; SECRET_KEY_SIZE];
664                 ser.copy_from_slice(&self[..]);
665                 ser.write(w)
666         }
667         #[inline]
668         fn serialized_length(&self) -> usize {
669                 SECRET_KEY_SIZE
670         }
671 }
672
673 impl Readable for SecretKey {
674         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
675                 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
676                 match SecretKey::from_slice(&buf) {
677                         Ok(key) => Ok(key),
678                         Err(_) => return Err(DecodeError::InvalidValue),
679                 }
680         }
681 }
682
683 impl Writeable for Sha256dHash {
684         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
685                 w.write_all(&self[..])
686         }
687 }
688
689 impl Readable for Sha256dHash {
690         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
691                 use bitcoin::hashes::Hash;
692
693                 let buf: [u8; 32] = Readable::read(r)?;
694                 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
695         }
696 }
697
698 impl Writeable for Signature {
699         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
700                 self.serialize_compact().write(w)
701         }
702         #[inline]
703         fn serialized_length(&self) -> usize {
704                 COMPACT_SIGNATURE_SIZE
705         }
706 }
707
708 impl Readable for Signature {
709         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
710                 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
711                 match Signature::from_compact(&buf) {
712                         Ok(sig) => Ok(sig),
713                         Err(_) => return Err(DecodeError::InvalidValue),
714                 }
715         }
716 }
717
718 impl Writeable for PaymentPreimage {
719         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
720                 self.0.write(w)
721         }
722 }
723
724 impl Readable for PaymentPreimage {
725         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
726                 let buf: [u8; 32] = Readable::read(r)?;
727                 Ok(PaymentPreimage(buf))
728         }
729 }
730
731 impl Writeable for PaymentHash {
732         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
733                 self.0.write(w)
734         }
735 }
736
737 impl Readable for PaymentHash {
738         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
739                 let buf: [u8; 32] = Readable::read(r)?;
740                 Ok(PaymentHash(buf))
741         }
742 }
743
744 impl Writeable for PaymentSecret {
745         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
746                 self.0.write(w)
747         }
748 }
749
750 impl Readable for PaymentSecret {
751         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
752                 let buf: [u8; 32] = Readable::read(r)?;
753                 Ok(PaymentSecret(buf))
754         }
755 }
756
757 impl<T: Writeable> Writeable for Box<T> {
758         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
759                 T::write(&**self, w)
760         }
761 }
762
763 impl<T: Readable> Readable for Box<T> {
764         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
765                 Ok(Box::new(Readable::read(r)?))
766         }
767 }
768
769 impl<T: Writeable> Writeable for Option<T> {
770         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
771                 match *self {
772                         None => 0u8.write(w)?,
773                         Some(ref data) => {
774                                 BigSize(data.serialized_length() as u64 + 1).write(w)?;
775                                 data.write(w)?;
776                         }
777                 }
778                 Ok(())
779         }
780 }
781
782 impl<T: Readable> Readable for Option<T>
783 {
784         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
785                 let len: BigSize = Readable::read(r)?;
786                 match len.0 {
787                         0 => Ok(None),
788                         len => {
789                                 let mut reader = FixedLengthReader::new(r, len - 1);
790                                 Ok(Some(Readable::read(&mut reader)?))
791                         }
792                 }
793         }
794 }
795
796 impl Writeable for Txid {
797         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
798                 w.write_all(&self[..])
799         }
800 }
801
802 impl Readable for Txid {
803         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
804                 use bitcoin::hashes::Hash;
805
806                 let buf: [u8; 32] = Readable::read(r)?;
807                 Ok(Txid::from_slice(&buf[..]).unwrap())
808         }
809 }
810
811 impl Writeable for BlockHash {
812         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
813                 w.write_all(&self[..])
814         }
815 }
816
817 impl Readable for BlockHash {
818         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
819                 use bitcoin::hashes::Hash;
820
821                 let buf: [u8; 32] = Readable::read(r)?;
822                 Ok(BlockHash::from_slice(&buf[..]).unwrap())
823         }
824 }
825
826 impl Writeable for OutPoint {
827         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
828                 self.txid.write(w)?;
829                 self.vout.write(w)?;
830                 Ok(())
831         }
832 }
833
834 impl Readable for OutPoint {
835         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
836                 let txid = Readable::read(r)?;
837                 let vout = Readable::read(r)?;
838                 Ok(OutPoint {
839                         txid,
840                         vout,
841                 })
842         }
843 }
844
845 macro_rules! impl_consensus_ser {
846         ($bitcoin_type: ty) => {
847                 impl Writeable for $bitcoin_type {
848                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
849                                 match self.consensus_encode(WriterWriteAdaptor(writer)) {
850                                         Ok(_) => Ok(()),
851                                         Err(e) => Err(e),
852                                 }
853                         }
854                 }
855
856                 impl Readable for $bitcoin_type {
857                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
858                                 match consensus::encode::Decodable::consensus_decode(r) {
859                                         Ok(t) => Ok(t),
860                                         Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
861                                         Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
862                                         Err(_) => Err(DecodeError::InvalidValue),
863                                 }
864                         }
865                 }
866         }
867 }
868 impl_consensus_ser!(Transaction);
869 impl_consensus_ser!(TxOut);
870
871 impl<T: Readable> Readable for Mutex<T> {
872         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
873                 let t: T = Readable::read(r)?;
874                 Ok(Mutex::new(t))
875         }
876 }
877 impl<T: Writeable> Writeable for Mutex<T> {
878         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
879                 self.lock().unwrap().write(w)
880         }
881 }
882
883 impl<A: Readable, B: Readable> Readable for (A, B) {
884         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
885                 let a: A = Readable::read(r)?;
886                 let b: B = Readable::read(r)?;
887                 Ok((a, b))
888         }
889 }
890 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
891         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
892                 self.0.write(w)?;
893                 self.1.write(w)
894         }
895 }
896
897 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
898         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
899                 let a: A = Readable::read(r)?;
900                 let b: B = Readable::read(r)?;
901                 let c: C = Readable::read(r)?;
902                 Ok((a, b, c))
903         }
904 }
905 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
906         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
907                 self.0.write(w)?;
908                 self.1.write(w)?;
909                 self.2.write(w)
910         }
911 }
912
913 impl Writeable for () {
914         fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
915                 Ok(())
916         }
917 }
918 impl Readable for () {
919         fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
920                 Ok(())
921         }
922 }
923
924 impl Writeable for String {
925         #[inline]
926         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
927                 (self.len() as u16).write(w)?;
928                 w.write_all(self.as_bytes())
929         }
930 }
931 impl Readable for String {
932         #[inline]
933         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
934                 let v: Vec<u8> = Readable::read(r)?;
935                 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
936                 Ok(ret)
937         }
938 }
939
940 /// Represents a hostname for serialization purposes.
941 /// Only the character set and length will be validated.
942 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
943 /// Its length is guaranteed to be representable by a single byte.
944 /// This serialization is used by BOLT 7 hostnames.
945 #[derive(Clone, Debug, PartialEq)]
946 pub struct Hostname(String);
947 impl Hostname {
948         /// Returns the length of the hostname.
949         pub fn len(&self) -> u8 {
950                 (&self.0).len() as u8
951         }
952 }
953 impl Deref for Hostname {
954         type Target = String;
955
956         fn deref(&self) -> &Self::Target {
957                 &self.0
958         }
959 }
960 impl From<Hostname> for String {
961         fn from(hostname: Hostname) -> Self {
962                 hostname.0
963         }
964 }
965 impl TryFrom<Vec<u8>> for Hostname {
966         type Error = ();
967
968         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
969                 if let Ok(s) = String::from_utf8(bytes) {
970                         Hostname::try_from(s)
971                 } else {
972                         Err(())
973                 }
974         }
975 }
976 impl TryFrom<String> for Hostname {
977         type Error = ();
978
979         fn try_from(s: String) -> Result<Self, Self::Error> {
980                 if s.len() <= 255 && s.chars().all(|c|
981                         c.is_ascii_alphanumeric() ||
982                         c == '.' ||
983                         c == '-'
984                 ) {
985                         Ok(Hostname(s))
986                 } else {
987                         Err(())
988                 }
989         }
990 }
991 impl Writeable for Hostname {
992         #[inline]
993         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
994                 self.len().write(w)?;
995                 w.write_all(self.as_bytes())
996         }
997 }
998 impl Readable for Hostname {
999         #[inline]
1000         fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1001                 let len: u8 = Readable::read(r)?;
1002                 let mut vec = Vec::with_capacity(len.into());
1003                 vec.resize(len.into(), 0);
1004                 r.read_exact(&mut vec)?;
1005                 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1006         }
1007 }
1008
1009 impl Writeable for Duration {
1010         #[inline]
1011         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1012                 self.as_secs().write(w)?;
1013                 self.subsec_nanos().write(w)
1014         }
1015 }
1016 impl Readable for Duration {
1017         #[inline]
1018         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1019                 let secs = Readable::read(r)?;
1020                 let nanos = Readable::read(r)?;
1021                 Ok(Duration::new(secs, nanos))
1022         }
1023 }
1024
1025 #[cfg(test)]
1026 mod tests {
1027         use core::convert::TryFrom;
1028         use util::ser::{Readable, Hostname, Writeable};
1029
1030         #[test]
1031         fn hostname_conversion() {
1032                 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1033
1034                 assert!(Hostname::try_from(String::from("\"")).is_err());
1035                 assert!(Hostname::try_from(String::from("$")).is_err());
1036                 assert!(Hostname::try_from(String::from("⚡")).is_err());
1037                 let mut large_vec = Vec::with_capacity(256);
1038                 large_vec.resize(256, b'A');
1039                 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1040         }
1041
1042         #[test]
1043         fn hostname_serialization() {
1044                 let hostname = Hostname::try_from(String::from("test")).unwrap();
1045                 let mut buf: Vec<u8> = Vec::new();
1046                 hostname.write(&mut buf).unwrap();
1047                 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1048         }
1049 }