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