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