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